GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Test Failed
Push — master ( 44f5f8...8d9d8e )
by Anton
02:15
created

Master   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 256
Duplicated Lines 4.69 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
dl 12
loc 256
ccs 100
cts 120
cp 0.8333
rs 7.92
c 0
b 0
f 0
wmc 51
lcom 1
cbo 11

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
F run() 0 77 24
A connect() 6 27 5
B runTask() 6 48 8
A createProcess() 0 13 3
A areRunning() 0 9 3
A gatherOutput() 0 14 4
A cumulativeExitCode() 0 9 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Master often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Master, and based on these observations, apply Extract Interface, too.

1
<?php declare(strict_types=1);
2
/* (c) Anton Medvedev <[email protected]>
3
 *
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
namespace Deployer\Executor;
9
10
use Deployer\Component\Ssh\Client;
11
use Deployer\Configuration\Configuration;
12
use Deployer\Deployer;
13
use Deployer\Host\Host;
14
use Deployer\Host\Localhost;
15
use Deployer\Selector\Selector;
16
use Deployer\Task\Task;
17
use Symfony\Component\Console\Input\InputInterface;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Process\Process;
20
21 1
const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
22
23
function spinner($message = '')
24
{
25 1
    $frame = FRAMES[(int)(microtime(true) * 10) % count(FRAMES)];
26 1
    return "  $frame $message\r";
27
}
28
29
class Master
30
{
31
    private $input;
32
    private $output;
33
    private $server;
34
    private $messenger;
35
    private $client;
36
    private $config;
37
38 10
    public function __construct(
39
        InputInterface $input,
40
        OutputInterface $output,
41
        Server $server,
42
        Messenger $messenger,
43
        Client $client,
44
        Configuration $config
45
    )
46
    {
47 10
        $this->input = $input;
48 10
        $this->output = $output;
49 10
        $this->server = $server;
50 10
        $this->messenger = $messenger;
51 10
        $this->client = $client;
52 10
        $this->config = $config;
53 10
    }
54
55
    /**
56
     * @param Task[] $tasks
57
     * @param Host[] $hosts
58
     * @param Planner|null $plan
59
     * @return int
60
     */
61 10
    public function run(array $tasks, array $hosts, $plan = null): int
62
    {
63 10
        $plan || $this->server->start();
64 10
        $plan || $this->connect($hosts);
65
66 10
        $globalLimit = (int)$this->input->getOption('limit') ?: count($hosts);
67
68 10
        foreach ($tasks as $task) {
69 10
            $plan || $this->messenger->startTask($task);
70
71 10
            $plannedHosts = $hosts;
72
73 10
            $limit = min($globalLimit, $task->getLimit() ?? $globalLimit);
74
75 10
            if ($task->isOnce()) {
76 4
                $plannedHosts = [];
77 4
                foreach ($hosts as $currentHost) {
78 4
                    if (Selector::apply($task->getSelector(), $currentHost)) {
79 4
                        $plannedHosts[] = $currentHost;
80 4
                        break;
81
                    }
82
                }
83
            }
84
85 10
            if ($task->isLocal()) {
86
                $plannedHosts = [new Localhost('localhost')];
87
            }
88
89 10
            if ($limit === 1 || count($plannedHosts) === 1) {
90 10
                foreach ($plannedHosts as $currentHost) {
91 10
                    if (!Selector::apply($task->getSelector(), $currentHost)) {
92
                        if ($plan) {
93
                            $plan->commit([], $task);
94
                        }
95
                        continue;
96
                    }
97
98 10
                    if ($plan) {
99
                        $plan->commit([$currentHost], $task);
100
                        continue;
101
                    }
102
103 10
                    $exitCode = $this->runTask($task, [$currentHost]);
104 10
                    if ($exitCode !== 0) {
105 2
                        return $exitCode;
106
                    }
107
                }
108
            } else {
109 2
                foreach (array_chunk($hosts, $limit) as $chunk) {
110 2
                    $selector = $task->getSelector();
111 2
                    $selectedHosts = [];
112 2
                    foreach ($chunk as $currentHost) {
113 2
                        if ($selector === null || Selector::apply($selector, $currentHost)) {
114 2
                            $selectedHosts[] = $currentHost;
115
                        }
116
                    }
117
118
119 2
                    if ($plan) {
120
                        $plan->commit($selectedHosts, $task);
121
                        continue;
122
                    }
123
124 2
                    $exitCode = $this->runTask($task, $selectedHosts);
125 2
                    if ($exitCode !== 0) {
126
                        return $exitCode;
127
                    }
128
                }
129
            }
130
131 10
            if (!$plan) {
132 10
                $this->messenger->endTask($task);
133
            }
134
        }
135
136 10
        return 0;
137
    }
138
139
    /**
140
     * @param Host[] $hosts
141
     */
142 10
    private function connect(array $hosts)
143
    {
144 View Code Duplication
        $callback = function (string $output) {
145
            $output = preg_replace('/\n$/', '', $output);
146
            if (strlen($output) !== 0) {
147
                $this->output->writeln($output);
148
            }
149 10
        };
150
151
        // Connect to each host sequentially, to prevent getting locked.
152 10
        foreach ($hosts as $host) {
153 10
            if ($host instanceof Localhost) {
154 10
                continue;
155
            }
156
            $process = $this->createProcess($host, new Task('connect'));
157
            $process->start();
158
159
            while ($process->isRunning()) {
160
                $this->gatherOutput([$process], $callback);
161
                $this->output->write(spinner(str_pad("connect {$host->getTag()}", intval(getenv('COLUMNS')) - 1)));
162
                usleep(1000);
163
            }
164
        }
165
166
        // Clear spinner.
167 10
        $this->output->write(str_repeat(' ', intval(getenv('COLUMNS')) - 1) . "\r");
168 10
    }
169
170
    /**
171
     * @param Task $task
172
     * @param Host[] $hosts
173
     * @return int
174
     */
175 10
    private function runTask(Task $task, array $hosts): int
176
    {
177 10
        if (getenv('DEPLOYER_LOCAL_WORKER') === 'true') {
178
            // This allows to code coverage all recipe,
179
            // as well as speedup tests by not spawning
180
            // lots of processes. Also there is a few tests
181
            // what runs with workers for tests subprocess
182
            // communications.
183 9
            foreach ($hosts as $host) {
184 9
                $worker = new Worker(Deployer::get());
185 9
                $exitCode = $worker->execute($task, $host);
186 9
                if ($exitCode !== 0) {
187 2
                    return $exitCode;
188
                }
189
            }
190 9
            return 0;
191
        }
192
193 1
        $processes = [];
194 1
        foreach ($hosts as $host) {
195 1
            $processes[] = $this->createProcess($host, $task);
196
        }
197
198 1
        foreach ($processes as $process) {
199 1
            $process->start();
200
        }
201
202 View Code Duplication
        $callback = function (string $output) {
203 1
            $output = preg_replace('/\n$/', '', $output);
204 1
            if (strlen($output) !== 0) {
205 1
                $this->output->writeln($output);
206
            }
207 1
        };
208
209
        $this->server->addPeriodicTimer(0.03, function () use ($processes, $callback) {
210 1
            $this->gatherOutput($processes, $callback);
211 1
            $this->output->write(spinner());
212 1
            if (!$this->areRunning($processes)) {
213 1
                $this->server->stop();
214
            }
215 1
        });
216 1
        $this->server->run();
217
218 1
        $this->output->write("    \r"); // clear spinner
219 1
        $this->gatherOutput($processes, $callback);
220
221 1
        return $this->cumulativeExitCode($processes);
222
    }
223
224 1
    protected function createProcess(Host $host, Task $task): Process
225
    {
226 1
        $dep = PHP_BINARY . ' ' . DEPLOYER_BIN;
227 1
        $configDirectory = $host->get('config_directory');
228 1
        $decorated = $this->output->isDecorated() ? '--decorated' : '';
229 1
        $command = "$dep worker $task {$host->getAlias()} $configDirectory {$this->server->getPort()} {$this->input} $decorated";
230
231 1
        if ($this->output->isDebug()) {
232
            $this->output->writeln("[{$host->getTag()}] $command");
233
        }
234
235 1
        return Process::fromShellCommandline($command);
236
    }
237
238
    /**
239
     * @param Process[] $processes
240
     * @return bool
241
     */
242 1
    protected function areRunning(array $processes): bool
243
    {
244 1
        foreach ($processes as $process) {
245 1
            if ($process->isRunning()) {
246 1
                return true;
247
            }
248
        }
249 1
        return false;
250
    }
251
252
    /**
253
     * @param Process[] $processes
254
     * @param callable $callback
255
     */
256 1
    protected function gatherOutput(array $processes, callable $callback)
257
    {
258 1
        foreach ($processes as $process) {
259 1
            $output = $process->getIncrementalOutput();
260 1
            if (strlen($output) !== 0) {
261 1
                $callback($output);
262
            }
263
264 1
            $errorOutput = $process->getIncrementalErrorOutput();
265 1
            if (strlen($errorOutput) !== 0) {
266 1
                $callback($errorOutput);
267
            }
268
        }
269 1
    }
270
271
    /**
272
     * @param Process[] $processes
273
     * @return int
274
     */
275 1
    protected function cumulativeExitCode(array $processes): int
276
    {
277 1
        foreach ($processes as $process) {
278 1
            if ($process->getExitCode() > 0) {
279
                return $process->getExitCode();
280
            }
281
        }
282 1
        return 0;
283
    }
284
}
285