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 ( 38eb10...d581fd )
by Anton
02:47
created

SshClient   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 90
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 55
dl 0
loc 90
rs 10
c 0
b 0
f 0
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 71 10
A __construct() 0 5 1
A parseExitStatus() 0 4 1
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\Component\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
class SshClient
23
{
24
    private OutputInterface $output;
25
    private Printer $pop;
26
    private Logger $logger;
27
28
    public function __construct(OutputInterface $output, Printer $pop, Logger $logger)
29
    {
30
        $this->output = $output;
31
        $this->pop = $pop;
32
        $this->logger = $logger;
33
    }
34
35
    public function run(Host $host, string $command, array $config = []): string
36
    {
37
        $defaults = [
38
            'timeout' => $host->get('default_timeout', 300),
39
            'idle_timeout' => null,
40
            'real_time_output' => false,
41
            'no_throw' => false,
42
        ];
43
        $config = array_merge($defaults, $config);
44
45
        $shellId = 'id$' . bin2hex(random_bytes(10));
46
        $shellCommand = $host->getShell();
47
        if ($host->has('become') && !empty($host->get('become'))) {
48
            $shellCommand = "sudo -H -u {$host->get('become')} " . $shellCommand;
49
        }
50
51
        $ssh = array_merge(['ssh'], $host->connectionOptionsArray(), [$host->connectionString(), ": $shellId; $shellCommand"]);
52
53
        // -vvv for ssh command
54
        if ($this->output->isDebug()) {
55
            $sshString = $ssh[0];
56
            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...
57
                $sshString .= ' ' . escapeshellarg((string) $ssh[$i]);
58
            }
59
            $this->output->writeln("[$host] $sshString");
60
        }
61
62
        $this->pop->command($host, 'run', $command);
63
        $this->logger->log("[{$host->getAlias()}] run $command");
64
65
        $command = str_replace('%secret%', strval($config['secret'] ?? ''), $command);
66
        $command = str_replace('%sudo_pass%', strval($config['sudo_pass'] ?? ''), $command);
67
68
        $process = new Process($ssh);
69
        $process
70
            ->setInput($command)
71
            ->setTimeout((null === $config['timeout']) ? null : (float) $config['timeout'])
72
            ->setIdleTimeout((null === $config['idle_timeout']) ? null : (float) $config['idle_timeout']);
73
74
        $callback = function ($type, $buffer) use ($config, $host) {
75
            $this->logger->printBuffer($host, $type, $buffer);
76
            $this->pop->callback($host, boolval($config['real_time_output']))($type, $buffer);
77
        };
78
79
        try {
80
            $process->run($callback);
81
        } catch (ProcessTimedOutException $exception) {
82
            // Let's try to kill all processes started by this command.
83
            $pid = $this->run($host, "ps x | grep $shellId | grep -v grep | awk '{print \$1}'");
84
            // Minus before pid means all processes in this group.
85
            $this->run($host, "kill -9 -$pid");
86
            throw new TimeoutException(
87
                $command,
88
                $exception->getExceededTimeout(),
89
            );
90
        }
91
92
        $output = $process->getOutput();
93
        $exitCode = $process->getExitCode();
94
95
        if ($exitCode !== 0 && !$config['no_throw']) {
96
            throw new RunException(
97
                $host,
98
                $command,
99
                $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

99
                /** @scrutinizer ignore-type */ $exitCode,
Loading history...
100
                $output,
101
                $process->getErrorOutput(),
102
            );
103
        }
104
105
        return $output;
106
    }
107
108
    private function parseExitStatus(Process $process): int
109
    {
110
        preg_match('/\[exit_code:(\d*)]/', $process->getOutput(), $match);
111
        return (int) ($match[1] ?? -1);
112
    }
113
}
114