• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

keradus / PHP-CS-Fixer / 16999983712

15 Aug 2025 09:42PM UTC coverage: 94.75% (-0.09%) from 94.839%
16999983712

push

github

keradus
ci: more self-fixing checks on lowest/highest PHP

28263 of 29829 relevant lines covered (94.75%)

45.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.3
/src/Console/Command/WorkerCommand.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <fabien@symfony.com>
9
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14

15
namespace PhpCsFixer\Console\Command;
16

17
use Clue\React\NDJson\Decoder;
18
use Clue\React\NDJson\Encoder;
19
use PhpCsFixer\Cache\NullCacheManager;
20
use PhpCsFixer\Config;
21
use PhpCsFixer\Console\ConfigurationResolver;
22
use PhpCsFixer\Error\ErrorsManager;
23
use PhpCsFixer\Runner\Event\FileProcessed;
24
use PhpCsFixer\Runner\Parallel\ParallelAction;
25
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;
26
use PhpCsFixer\Runner\Parallel\ParallelisationException;
27
use PhpCsFixer\Runner\Runner;
28
use PhpCsFixer\ToolInfoInterface;
29
use React\EventLoop\StreamSelectLoop;
30
use React\Socket\ConnectionInterface;
31
use React\Socket\TcpConnector;
32
use Symfony\Component\Console\Attribute\AsCommand;
33
use Symfony\Component\Console\Command\Command;
34
use Symfony\Component\Console\Input\InputInterface;
35
use Symfony\Component\Console\Input\InputOption;
36
use Symfony\Component\Console\Output\ConsoleOutputInterface;
37
use Symfony\Component\Console\Output\OutputInterface;
38
use Symfony\Component\EventDispatcher\EventDispatcher;
39
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
40

41
/**
42
 * @author Greg Korba <greg@codito.dev>
43
 *
44
 * @internal
45
 */
46
#[AsCommand(name: 'worker', description: 'Internal command for running fixers in parallel', hidden: true)]
47
final class WorkerCommand extends Command
48
{
49
    /** @var string Prefix used before JSON-encoded error printed in the worker's process */
50
    public const ERROR_PREFIX = 'WORKER_ERROR::';
51

52
    /** @TODO PHP 8.0 - remove the property */
53
    protected static $defaultName = 'worker';
54

55
    /** @TODO PHP 8.0 - remove the property */
56
    protected static $defaultDescription = 'Internal command for running fixers in parallel';
57

58
    private ToolInfoInterface $toolInfo;
59
    private ConfigurationResolver $configurationResolver;
60
    private ErrorsManager $errorsManager;
61
    private EventDispatcherInterface $eventDispatcher;
62

63
    /** @var list<FileProcessed> */
64
    private array $events;
65

66
    public function __construct(ToolInfoInterface $toolInfo)
67
    {
68
        parent::__construct();
5✔
69

70
        $this->setHidden(true);
5✔
71
        $this->toolInfo = $toolInfo;
5✔
72
        $this->errorsManager = new ErrorsManager();
5✔
73
        $this->eventDispatcher = new EventDispatcher();
5✔
74
    }
75

76
    protected function configure(): void
77
    {
78
        $this->setDefinition(
5✔
79
            [
5✔
80
                new InputOption('port', null, InputOption::VALUE_REQUIRED, 'Specifies parallelisation server\'s port.'),
5✔
81
                new InputOption('identifier', null, InputOption::VALUE_REQUIRED, 'Specifies parallelisation process\' identifier.'),
5✔
82
                new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Are risky fixers allowed (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES),
5✔
83
                new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a config file.'),
5✔
84
                new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'),
5✔
85
                new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'List of rules that should be run against configured paths.'),
5✔
86
                new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, HelpCommand::getDescriptionWithAllowedValues('Should cache be used (%s).', ConfigurationResolver::BOOL_VALUES), null, ConfigurationResolver::BOOL_VALUES),
5✔
87
                new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'),
5✔
88
                new InputOption('diff', '', InputOption::VALUE_NONE, 'Prints diff for each file.'),
5✔
89
                new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'),
5✔
90
            ]
5✔
91
        );
5✔
92
    }
93

94
    protected function execute(InputInterface $input, OutputInterface $output): int
95
    {
96
        $errorOutput = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
3✔
97
        $identifier = $input->getOption('identifier');
3✔
98
        $port = $input->getOption('port');
3✔
99

100
        if (null === $identifier || !is_numeric($port)) {
3✔
101
            throw new ParallelisationException('Missing parallelisation options');
2✔
102
        }
103

104
        try {
105
            $runner = $this->createRunner($input);
1✔
106
        } catch (\Throwable $e) {
×
107
            throw new ParallelisationException('Unable to create runner: '.$e->getMessage(), 0, $e);
×
108
        }
109

110
        $loop = new StreamSelectLoop();
1✔
111
        $tcpConnector = new TcpConnector($loop);
1✔
112
        $tcpConnector
1✔
113
            ->connect(\sprintf('127.0.0.1:%d', $port))
1✔
114
            ->then(
1✔
115
                /** @codeCoverageIgnore */
116
                function (ConnectionInterface $connection) use ($loop, $runner, $identifier): void {
1✔
117
                    $out = new Encoder($connection, \JSON_INVALID_UTF8_IGNORE);
×
118
                    $in = new Decoder($connection, true, 512, \JSON_INVALID_UTF8_IGNORE);
×
119

120
                    // [REACT] Initialise connection with the parallelisation operator
121
                    $out->write(['action' => ParallelAction::WORKER_HELLO, 'identifier' => $identifier]);
×
122

123
                    $handleError = static function (\Throwable $error) use ($out): void {
×
124
                        $out->write([
×
125
                            'action' => ParallelAction::WORKER_ERROR_REPORT,
×
126
                            'class' => \get_class($error),
×
127
                            'message' => $error->getMessage(),
×
128
                            'file' => $error->getFile(),
×
129
                            'line' => $error->getLine(),
×
130
                            'code' => $error->getCode(),
×
131
                            'trace' => $error->getTraceAsString(),
×
132
                        ]);
×
133
                    };
×
134
                    $out->on('error', $handleError);
×
135
                    $in->on('error', $handleError);
×
136

137
                    // [REACT] Listen for messages from the parallelisation operator (analysis requests)
138
                    $in->on('data', function (array $json) use ($loop, $runner, $out): void {
×
139
                        $action = $json['action'] ?? null;
×
140

141
                        // Parallelisation operator does not have more to do, let's close the connection
142
                        if (ParallelAction::RUNNER_THANK_YOU === $action) {
×
143
                            $loop->stop();
×
144

145
                            return;
×
146
                        }
147

148
                        if (ParallelAction::RUNNER_REQUEST_ANALYSIS !== $action) {
×
149
                            // At this point we only expect analysis requests, if any other action happen, we need to fix the code.
150
                            throw new \LogicException(\sprintf('Unexpected action ParallelAction::%s.', $action));
×
151
                        }
152

153
                        /** @var iterable<int, string> $files */
154
                        $files = $json['files'];
×
155

156
                        foreach ($files as $path) {
×
157
                            // Reset events because we want to collect only those coming from analysed files chunk
158
                            $this->events = [];
×
159
                            $runner->setFileIterator(new \ArrayIterator([new \SplFileInfo($path)]));
×
160
                            $analysisResult = $runner->fix();
×
161

162
                            if (1 !== \count($this->events)) {
×
163
                                throw new ParallelisationException('Runner did not report a fixing event or reported too many.');
×
164
                            }
165

166
                            if (1 < \count($analysisResult)) {
×
167
                                throw new ParallelisationException('Runner returned more analysis results than expected.');
×
168
                            }
169

170
                            $out->write([
×
171
                                'action' => ParallelAction::WORKER_RESULT,
×
172
                                'file' => $path,
×
173
                                'fileHash' => $this->events[0]->getFileHash(),
×
174
                                'status' => $this->events[0]->getStatus(),
×
175
                                'fixInfo' => array_pop($analysisResult),
×
176
                                'errors' => $this->errorsManager->forPath($path),
×
177
                            ]);
×
178
                        }
179

180
                        // Request another file chunk (if available, the parallelisation operator will request new "run" action)
181
                        $out->write(['action' => ParallelAction::WORKER_GET_FILE_CHUNK]);
×
182
                    });
×
183
                },
1✔
184
                static function (\Throwable $error) use ($errorOutput): void {
1✔
185
                    // @TODO Verify onRejected behaviour → https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/pull/7777#discussion_r1590399285
186
                    $errorOutput->writeln($error->getMessage());
1✔
187
                }
1✔
188
            )
1✔
189
        ;
1✔
190

191
        $loop->run();
1✔
192

193
        return Command::SUCCESS;
1✔
194
    }
195

196
    private function createRunner(InputInterface $input): Runner
197
    {
198
        $passedConfig = $input->getOption('config');
1✔
199
        $passedRules = $input->getOption('rules');
1✔
200

201
        if (null !== $passedConfig && null !== $passedRules) {
1✔
202
            throw new \RuntimeException('Passing both `--config` and `--rules` options is not allowed');
×
203
        }
204

205
        // There's no one single source of truth when it comes to fixing single file, we need to collect statuses from events.
206
        $this->eventDispatcher->addListener(FileProcessed::NAME, function (FileProcessed $event): void {
1✔
207
            $this->events[] = $event;
×
208
        });
1✔
209

210
        $this->configurationResolver = new ConfigurationResolver(
1✔
211
            new Config(),
1✔
212
            [
1✔
213
                'allow-risky' => $input->getOption('allow-risky'),
1✔
214
                'config' => $passedConfig,
1✔
215
                'dry-run' => $input->getOption('dry-run'),
1✔
216
                'rules' => $passedRules,
1✔
217
                'path' => [],
1✔
218
                'path-mode' => ConfigurationResolver::PATH_MODE_OVERRIDE, // IMPORTANT! WorkerCommand is called with file that already passed filtering, so here we can rely on PATH_MODE_OVERRIDE.
1✔
219
                'using-cache' => $input->getOption('using-cache'),
1✔
220
                'cache-file' => $input->getOption('cache-file'),
1✔
221
                'diff' => $input->getOption('diff'),
1✔
222
                'stop-on-violation' => $input->getOption('stop-on-violation'),
1✔
223
            ],
1✔
224
            getcwd(), // @phpstan-ignore-line
1✔
225
            $this->toolInfo
1✔
226
        );
1✔
227

228
        return new Runner(
1✔
229
            null, // Paths are known when parallelisation server requests new chunk, not now
1✔
230
            $this->configurationResolver->getFixers(),
1✔
231
            $this->configurationResolver->getDiffer(),
1✔
232
            $this->eventDispatcher,
1✔
233
            $this->errorsManager,
1✔
234
            $this->configurationResolver->getLinter(),
1✔
235
            $this->configurationResolver->isDryRun(),
1✔
236
            new NullCacheManager(), // IMPORTANT! We pass null cache, as cache is read&write in main process and we do not need to do it again.
1✔
237
            $this->configurationResolver->getDirectory(),
1✔
238
            $this->configurationResolver->shouldStopOnViolation(),
1✔
239
            ParallelConfigFactory::sequential(), // IMPORTANT! Worker must run in sequential mode.
1✔
240
            null,
1✔
241
            $this->configurationResolver->getConfigFile()
1✔
242
        );
1✔
243
    }
244
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc