ParallelTask::configure()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
/**
4
 * This file is part of Bldr.io
5
 *
6
 * (c) Aaron Scherer <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE
10
 */
11
12
namespace Bldr\Block\Execute\Task;
13
14
use Bldr\Block\Core\Task\AbstractTask;
15
use Bldr\Event;
16
use Bldr\Event\PostExecuteEvent;
17
use Bldr\Event\PreExecuteEvent;
18
use Bldr\Exception\TaskRuntimeException;
19
use Symfony\Component\Console\Helper\DebugFormatterHelper;
20
use Symfony\Component\Console\Output\OutputInterface;
21
use Symfony\Component\Console\Output\StreamOutput;
22
use Symfony\Component\Process\Process;
23
use Symfony\Component\Process\ProcessBuilder;
24
25
/**
26
 * @author Aaron Scherer <[email protected]>
27
 */
28
class ParallelTask extends AbstractTask
29
{
30
    /**
31
     * @type OutputInterface
32
     */
33
    private $output;
34
35
    /**
36
     * Configures the Task
37
     */
38
    public function configure()
39
    {
40
        $this->setName('parallel')
41
            ->setDescription('Executes the given commands in parallel, waiting for them all to finish')
42
            ->addParameter('commands', true, 'Commands to run (string, or array of strings)')
43
            ->addParameter('cwd', false, 'Sets the working directory for the executable')
44
            ->addParameter('output', false, 'Sets the location to output to')
45
            ->addParameter('raw', false, 'Should the output be raw (unformatted)')
46
            ->addParameter('successCodes', false, 'Sets the status codes allowed for a success (Array)', [0])
47
            ->addParameter('append', false, 'If output is set, should it append?', false)
48
            ->addParameter('dry_run', false, 'If set will not run command', false)
49
            ->addParameter('timeout', false, 'Timeout for the command', 0);
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     */
55
    public function run(OutputInterface $output)
56
    {
57
        $this->output = $output;
58
59
        if (get_class($this) === ParallelTask::class) {
60
            $this->output->writeln(
61
                ['', sprintf('    <info>[%s]</info> - <comment>Starting</comment>', $this->getName()), '']
62
            );
63
        }
64
65
        $output->writeln("<fg=blue>==============================\n</fg=blue>");
66
67
        /** @type Process[] $processes */
68
        $processes = [];
69
        foreach ($this->resolveCommands() as $command) {
70
            $processes[] = $this->runCommand($command);
71
        }
72
73
        $this->waitForCommandsToFinish($processes);
74
75
        /** @type DebugFormatterHelper $debugFormatter */
76
        $debugFormatter = $this->getHelperSet()->get('debug_formatter');
77
        foreach ($processes as $process) {
78
            $output->writeln(
79
                [
80
                    "",
81
                    $debugFormatter->stop(
82
                        spl_object_hash($process),
83
                        $process->getCommandLine(),
84
                        $process->isSuccessful()
85
                    )
86
                ]
87
            );
88
89
            if (null !== $dispatcher = $this->getEventDispatcher()) {
90
                $event = new PostExecuteEvent($this, $process);
0 ignored issues
show
Bug introduced by
It seems like $process defined by $process on line 77 can also be of type boolean; however, Bldr\Event\PostExecuteEvent::__construct() does only seem to accept object<Symfony\Component\Process\Process>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
91
                $dispatcher->dispatch(Event::POST_EXECUTE, $event);
92
            }
93
94
            if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) {
95
                throw new TaskRuntimeException($this->getName(), $process->getErrorOutput());
96
            }
97
        }
98
99
        $output->writeln("<fg=blue>==============================\n</fg=blue>");
100
    }
101
102
    /**
103
     * @param Process $process
104
     *
105
     * @return bool
106
     * @throws TaskRuntimeException
107
     * @throws \Bldr\Exception\BldrException
108
     * @throws \Bldr\Exception\ParameterNotFoundException
109
     * @throws \Bldr\Exception\RequiredParameterException
110
     */
111
    private function runCommand(Process $process)
112
    {
113
        $output = $this->output;
114
115
        /** @type DebugFormatterHelper $debugFormatter */
116
        $debugFormatter = $this->getHelperSet()->get('debug_formatter');
117
        if (null !== $dispatcher = $this->getEventDispatcher()) {
118
            $event = new PreExecuteEvent($this, $process);
119
            $dispatcher->dispatch(Event::PRE_EXECUTE, $event);
120
121
            if ($event->isPropagationStopped()) {
122
                $output->writeln(
123
                    ['', sprintf('    <info>[%s]</info> - <comment>Stopped</comment>', $this->getName()), '']
124
                );
125
126
                return true;
127
            }
128
        }
129
130
        if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE || $this->getParameter('dry_run')) {
131
            $output->writeln('        // '.$process->getCommandLine());
132
        }
133
134
        if ($this->getParameter('dry_run')) {
135
            return true;
136
        }
137
138
        if ($this->hasParameter('cwd')) {
139
            $process->setWorkingDirectory($this->getParameter('cwd'));
0 ignored issues
show
Bug introduced by
It seems like $this->getParameter('cwd') targeting Bldr\Block\Core\Task\AbstractTask::getParameter() can also be of type array; however, Symfony\Component\Proces...::setWorkingDirectory() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
140
        }
141
142
        if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) {
143
            $output->writeln(
144
                sprintf(
145
                    '        // Setting timeout for %d seconds.',
146
                    $this->getParameter('timeout')
147
                )
148
            );
149
        }
150
        $process->setTimeout($this->getParameter('timeout') !== 0 ? $this->getParameter('timeout') : null);
0 ignored issues
show
Bug introduced by
It seems like $this->getParameter('tim...meter('timeout') : null can also be of type array or string; however, Symfony\Component\Process\Process::setTimeout() does only seem to accept integer|double|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
151
152
        if ($this->hasParameter('output')) {
153
            $append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w';
154
            $stream = fopen($this->getParameter('output'), $append);
155
            $output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true);
156
        }
157
158
        $output->writeln(
159
            $debugFormatter->start(
160
                spl_object_hash($process),
161
                $process->getCommandLine()
162
            )
163
        );
164
165
        $process->start();
166
167
        return $process;
168
    }
169
170
    /**
171
     * @return array|Process[]
172
     *
173
     * @throws \Bldr\Exception\ParameterNotFoundException
174
     * @throws \Bldr\Exception\RequiredParameterException
175
     */
176
    private function resolveCommands()
177
    {
178
        $commands = [];
179
        foreach ($this->getParameter('commands') as $cmd) {
0 ignored issues
show
Bug introduced by
The expression $this->getParameter('commands') of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
180
            $commands[] = is_array($cmd) ? (new ProcessBuilder($cmd))->getProcess() : new Process($cmd);
181
        }
182
183
        return $commands;
184
    }
185
186
    /**
187
     * @param array|Process[] $processes
188
     */
189
    private function waitForCommandsToFinish(array $processes)
190
    {
191
        while (true) {
192
            foreach ($processes as $process) {
193
                if ($process->isRunning()) {
194
                    continue 2;
195
                }
196
            }
197
            break;
198
        }
199
    }
200
}
201