|
2 | 2 |
|
3 | 3 | namespace App\Commands;
|
4 | 4 |
|
| 5 | +use App\Actions\FixCode; |
5 | 6 | use LaravelZero\Framework\Commands\Command;
|
6 | 7 | use Symfony\Component\Console\Input\InputArgument;
|
7 | 8 | use Symfony\Component\Console\Input\InputOption;
|
| 9 | +use Throwable; |
8 | 10 |
|
9 | 11 | class DefaultCommand extends Command
|
10 | 12 | {
|
@@ -62,8 +64,58 @@ protected function configure()
|
62 | 64 | */
|
63 | 65 | public function handle($fixCode, $elaborateSummary)
|
64 | 66 | {
|
| 67 | + if ($this->hasStdinInput()) { |
| 68 | + return $this->fixStdinInput($fixCode); |
| 69 | + } |
| 70 | + |
65 | 71 | [$totalFiles, $changes] = $fixCode->execute();
|
66 | 72 |
|
67 | 73 | return $elaborateSummary->execute($totalFiles, $changes);
|
68 | 74 | }
|
| 75 | + |
| 76 | + /** |
| 77 | + * Fix the code sent to Pint on stdin and output to stdout. |
| 78 | + */ |
| 79 | + protected function fixStdinInput(FixCode $fixCode): int |
| 80 | + { |
| 81 | + $paths = $this->argument('path'); |
| 82 | + |
| 83 | + $contextPath = ! empty($paths) ? $paths[0] : 'stdin.php'; |
| 84 | + $tempFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pint_stdin_'.uniqid().'.php'; |
| 85 | + |
| 86 | + $this->input->setArgument('path', [$tempFile]); |
| 87 | + $this->input->setOption('format', 'json'); |
| 88 | + |
| 89 | + try { |
| 90 | + file_put_contents($tempFile, stream_get_contents(STDIN)); |
| 91 | + $fixCode->execute(); |
| 92 | + fwrite(STDOUT, file_get_contents($tempFile)); |
| 93 | + |
| 94 | + return self::SUCCESS; |
| 95 | + } catch (Throwable $e) { |
| 96 | + fwrite(STDERR, "pint: error processing {$contextPath}: {$e->getMessage()}\n"); |
| 97 | + |
| 98 | + return self::FAILURE; |
| 99 | + } finally { |
| 100 | + if (file_exists($tempFile)) { |
| 101 | + @unlink($tempFile); |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Determine if there is input available on stdin. |
| 108 | + */ |
| 109 | + protected function hasStdinInput(): bool |
| 110 | + { |
| 111 | + if ($this->option('test') || $this->option('bail') || $this->option('repair')) { |
| 112 | + return false; |
| 113 | + } |
| 114 | + |
| 115 | + if (! is_resource(STDIN) || stream_isatty(STDIN)) { |
| 116 | + return false; |
| 117 | + } |
| 118 | + |
| 119 | + return ! stream_get_meta_data(STDIN)['eof']; |
| 120 | + } |
69 | 121 | }
|
0 commit comments