ProcScanHandler.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Di\ScanHandler;
  12. use function Hyperf\Support\env;
  13. class ProcScanHandler implements ScanHandlerInterface
  14. {
  15. public const SCAN_PROC_WORKER = 'SCAN_PROC_WORKER';
  16. protected string $bin;
  17. protected string $stub;
  18. public function __construct(?string $bin = null, ?string $stub = null)
  19. {
  20. if ($bin === null) {
  21. $bin = PHP_BINARY;
  22. }
  23. if ($stub === null) {
  24. $stub = BASE_PATH . '/bin/hyperf.php';
  25. }
  26. $this->bin = $bin;
  27. $this->stub = $stub;
  28. }
  29. public function scan(): Scanned
  30. {
  31. if (env(static::SCAN_PROC_WORKER)) {
  32. return new Scanned(false);
  33. }
  34. $proc = proc_open(
  35. [$this->bin, $this->stub],
  36. [0 => STDIN, 1 => ['pipe', 'w'], 2 => ['redirect', 1]],
  37. $pipes,
  38. null,
  39. [static::SCAN_PROC_WORKER => '(true)']
  40. );
  41. $output = '';
  42. do {
  43. $output .= fread($pipes[1], 8192);
  44. } while (! feof($pipes[1]));
  45. if (proc_close($proc) !== 0) {
  46. echo $output;
  47. exit(-1);
  48. }
  49. return new Scanned(true);
  50. }
  51. }