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.
Passed
Push — master ( 21abfc...40d55e )
by Anton
02:41
created

SshClient::run()   C

Complexity

Conditions 12
Paths 96

Size

Total Lines 76
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 46
nc 96
nop 3
dl 0
loc 76
rs 6.9666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/* (c) Anton Medvedev <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Deployer\Ssh;
12
13
use Deployer\ProcessRunner\Printer;
14
use Deployer\Exception\RunException;
15
use Deployer\Exception\TimeoutException;
16
use Deployer\Host\Host;
17
use Deployer\Logger\Logger;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Process\Exception\ProcessTimedOutException;
20
use Symfony\Component\Process\Process;
21
22
use function Deployer\Support\env_stringify;
23
24
class SshClient
25
{
26
    private OutputInterface $output;
27
    private Printer $pop;
28
    private Logger $logger;
29
30
    public function __construct(OutputInterface $output, Printer $pop, Logger $logger)
31
    {
32
        $this->output = $output;
33
        $this->pop = $pop;
34
        $this->logger = $logger;
35
    }
36
37
    public function run(Host $host, string $command, RunParams $params): string
38
    {
39
        $shellId = 'id$' . bin2hex(random_bytes(10));
40
        $shellCommand = $host->getShell();
41
        if ($host->has('become') && !empty($host->get('become'))) {
42
            $shellCommand = "sudo -H -u {$host->get('become')} " . $shellCommand;
43
        }
44
45
        $ssh = array_merge(['ssh'], $host->connectionOptionsArray(), [$host->connectionString(), ": $shellId; $shellCommand"]);
46
47
        // -vvv for ssh command
48
        if ($this->output->isDebug()) {
49
            $sshString = $ssh[0];
50
            for ($i = 1; $i < count($ssh); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
51
                $sshString .= ' ' . escapeshellarg((string) $ssh[$i]);
52
            }
53
            $this->output->writeln("[$host] $sshString");
54
        }
55
56
        if (!empty($params->cwd)) {
57
            $command = "cd $params->cwd && ($command)";
58
        }
59
60
        if (!empty($params->env)) {
61
            $env = env_stringify($params->env);
62
            $command = "export $env; $command";
63
        }
64
65
        if (!empty($params->secrets)) {
66
            foreach ($params->secrets as $key => $value) {
67
                $command = str_replace('%' . $key . '%', strval($value), $command);
68
            }
69
        }
70
71
        $this->pop->command($host, 'run', $command);
72
        $this->logger->log("[{$host->getAlias()}] run $command");
73
74
75
        $process = new Process($ssh);
76
        $process
77
            ->setInput($command)
78
            ->setTimeout($params->timeout)
79
            ->setIdleTimeout($params->idleTimeout);
80
81
        $callback = function ($type, $buffer) use ($params, $host) {
82
            $this->logger->printBuffer($host, $type, $buffer);
83
            $this->pop->callback($host, $params->forceOutput)($type, $buffer);
84
        };
85
86
        try {
87
            $process->run($callback);
88
        } catch (ProcessTimedOutException $exception) {
89
            // Let's try to kill all processes started by this command.
90
            $pid = $this->run($host, "ps x | grep $shellId | grep -v grep | awk '{print \$1}'", $params->with(timeout: 10));
91
            // Minus before pid means all processes in this group.
92
            $this->run($host, "kill -9 -$pid", $params->with(timeout: 20));
93
            throw new TimeoutException(
94
                $command,
95
                $exception->getExceededTimeout(),
96
            );
97
        }
98
99
        $output = $process->getOutput();
100
        $exitCode = $process->getExitCode();
101
102
        if ($exitCode !== 0 && !$params->nothrow) {
103
            throw new RunException(
104
                $host,
105
                $command,
106
                $exitCode,
0 ignored issues
show
Bug introduced by
It seems like $exitCode can also be of type null; however, parameter $exitCode of Deployer\Exception\RunException::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

106
                /** @scrutinizer ignore-type */ $exitCode,
Loading history...
107
                $output,
108
                $process->getErrorOutput(),
109
            );
110
        }
111
112
        return $output;
113
    }
114
}
115