Completed
Push — master ( 42a65f...494029 )
by Lorenzo
07:08
created

SensiolabHelper::getSensiolabVulnerabilties()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 54
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 38
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 38
cts 38
cp 1
rs 8.7449
c 0
b 0
f 0
cc 6
eloc 39
nc 10
nop 1
crap 6

How to fix   Long Method   

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
 * Created by PhpStorm.
4
 * User: Alessandro
5
 * Date: 02/12/2015
6
 * Time: 13:47
7
 */
8
9
namespace Padosoft\LaravelComposerSecurity;
10
11
use Illuminate\Console\Command;
12
use GuzzleHttp\Client;
13
14
class SensiolabHelper
15
{
16
17
    protected $guzzle;
18
19
    protected $command;
20
21
    protected $tableVulnerabilities = [];
22
23
    /**
24
     * SensiolabHelper constructor.
25
     * @param Client $objguzzle
26
     * @param Command $objcommand
27
     */
28 26
    public function __construct(Client $objguzzle, Command $objcommand)
29
    {
30 26
        $this->guzzle = $objguzzle;
31 26
        $this->command = $objcommand;
32 26
    }
33
34
    /**
35
     *
36
     * Send Request to sensiolab and return array of sensiolab vulnerabilities.
37
     * Empty array if here is no vulnerabilities.
38
     *
39
     * @param $fileLock path to composer.lock file.
40
     *
41
     * @return array
42
     */
43 24
    public function getSensiolabVulnerabilties($fileLock)
44
    {
45 24
        $this->addVerboseLog('Send request to sensiolab: <info>' . $fileLock . '</info>');
46
47 24
        $debug = false;//set to true to log into console output
48
        $headers = [
49
            //OPTIONS
50
            'allow_redirects' => [
51 24
                'max' => 3,        // allow at most 10 redirects.
52 24
                'strict' => true,      // use "strict" RFC compliant redirects.
53 24
                'referer' => true,      // add a Referer header
54 24
                'protocols' => ['http', 'https'], // only allow http and https URLs
55
                'track_redirects' => false
56 24
            ],
57 24
            'connect_timeout' => 20,//Use 0 to wait connection indefinitely
58 24
            'timeout' => 30, //Use 0 to wait response indefinitely
59 24
            'debug' => $debug,
60
            //HEADERS
61
            'headers' => [
62
                'Accept' => 'application/json'
63 24
            ],
64
            //UPLOAD FORM FILE
65
            'multipart' => [
66
                [
67 24
                    'name' => 'lock',
68 24
                    'contents' => fopen($fileLock, 'r')
69 24
                ]
70 24
            ]
71 24
        ];
72 24
        $response = null;
73
74
        try {
75 24
            $iResponse = $this->guzzle->request('POST', 'https://security.sensiolabs.org/check_lock', $headers);
76 18
            $responseBody = $iResponse->getBody()->getContents();
77 18
            $response = json_decode($responseBody, true);
78 24
        } catch (\GuzzleHttp\Exception\ClientException $e) {
79 4
            $this->command->error("ClientException!\nMessage: " . $e->getMessage());
80 4
            $colorTag = $this->getColorTagForStatusCode($e->getResponse()->getStatusCode());
81 4
            $this->command->line("HTTP StatusCode: <{$colorTag}>" . $e->getResponse()->getStatusCode() . "<{$colorTag}>");
82 4
            $resp = $e->getResponse();
83 4
            $this->printMessage($resp === null ? '' : $resp);
0 ignored issues
show
Bug introduced by
It seems like $resp === null ? '' : $resp can also be of type string; however, Padosoft\LaravelComposer...bHelper::printMessage() does only seem to accept object<Psr\Http\Message\MessageInterface>, 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...
84 4
            $this->printMessage($e->getRequest());
85 6
        } catch (\GuzzleHttp\Exception\RequestException $e) {
86 4
            $this->command->error("RequestException!\nMessage: " . $e->getMessage());
87 4
            $this->printMessage($e->getRequest());
88 4
            if ($e->hasResponse()) {
89 2
                $colorTag = $this->getColorTagForStatusCode($e->getResponse()->getStatusCode());
90 2
                $this->command->line("HTTP StatusCode: <{$colorTag}>" . $e->getResponse()->getStatusCode() . "<{$colorTag}>");
91 2
                $resp = $e->getResponse();
92 2
                $this->printMessage($resp === null ? '' : $resp);
0 ignored issues
show
Bug introduced by
It seems like $resp === null ? '' : $resp can also be of type string; however, Padosoft\LaravelComposer...bHelper::printMessage() does only seem to accept object<Psr\Http\Message\MessageInterface>, 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...
93 2
            }
94
        }
95 24
        return $response;
96
    }
97
98
    /**
99
     * @param $name
100
     * @param $vulnerability
101
     * @return array
102
     */
103 12
    public function parseVulnerability($name, $vulnerability)
104
    {
105
        $data = [
106 12
            'name' => $name,
107 12
            'version' => $vulnerability['version'],
108 12
            'advisories' => array_values($vulnerability['advisories'])
109 12
        ];
110 12
        unset($this->tableVulnerabilities);
111 12
        foreach ($data['advisories'] as $key2 => $advisory) {
112
            $data2 = [
113 12
                'title' => $advisory['title'],
114 12
                'link' => $advisory['link'],
115 12
                'cve' => $advisory['cve']
116 12
            ];
117
118
            $dataTable = [
119 12
                'name' => $data['name'],
120 12
                'version' => $data['version'],
121 12
                'advisories' => $data2["title"]
122 12
            ];
123
124 12
            $this->addVerboseLog($data['name'] . " " . $data['version'] . " " . $data2["title"], true);
125 12
            $this->tableVulnerabilities[] = $dataTable;
126 12
        }
127
128 12
        return $this->tableVulnerabilities;
129
    }
130
131
    /**
132
     * @param $key
133
     * @param $vulnerability
134
     * @param $tuttoOk
135
     * @return array
136
     */
137 10
    public function checkResponse($key, $vulnerability, $tuttoOk)
138
    {
139 10
        $tableVulnerabilities = array();
140
141 10
        foreach ($this->parseVulnerability($key, $vulnerability) as $vul) {
142 10
            $tableVulnerabilities[] = array_merge($vul, array('isOk' => $tuttoOk));
143 10
        }
144
145 10
        return $tableVulnerabilities;
146
    }
147
148
    /**
149
     * @param            $msg
150
     * @param bool|false $error
151
     */
152 26
    private function addVerboseLog($msg, $error = false)
153
    {
154 26
        $verbose = $this->command->option('verbose');
155 26
        if ($verbose) {
156 10
            if ($error) {
157 2
                $this->command->error($msg);
158 2
            } else {
159 8
                $this->command->line($msg);
160
            }
161 10
        }
162 26
    }
163
164
    /**
165
     * @param \Psr\Http\Message\MessageInterface $message
166
     *
167
     * @throws \RuntimeException
168
     */
169 6
    private function printMessage(\Psr\Http\Message\MessageInterface $message)
170
    {
171 6
        $type = '';
172 6
        if (is_a($message, '\Psr\Http\Message\RequestInterface')) {
173 6
            $type = 'REQUEST';
174 6
            $body = $message->getBody();
175 6
        } else {
176 6
            if (is_a($message, '\Psr\Http\Message\ResponseInterface')) {
177 6
                $type = 'RESPONSE';
178 6
                $body = $message->getBody()->getContents();
179 6
            }
180
        }
181 6
        $this->command->info("$type:");
182 6
        $headers = '';
183 6
        foreach ($message->getHeaders() as $name => $values) {
184
            $headers .= $name . ': ' . implode(', ', $values) . "\r\n";
185 6
        }
186 6
        $this->command->comment($headers);
187 6
        if ($type == 'REQUEST') {
188 6
            $this->command->comment($body);
0 ignored issues
show
Bug introduced by
The variable $body does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
189 6
        } else {
190 6
            if ($type == 'RESPONSE') {
191 6
                $this->command->comment($body);
192 6
            }
193
        }
194 6
    }
195
196
197
    /**
198
     * Get the color tag for the given status code.
199
     *
200
     * @param string $code
201
     *
202
     * @return string
203
     *
204
     * @see https://github.com/spatie/http-status-check/blob/master/src/CrawlLogger.php#L96
205
     */
206 6
    protected function getColorTagForStatusCode($code)
207
    {
208 6
        if (starts_with($code, '2')) {
209 2
            return 'info';
210
        }
211 4
        if (starts_with($code, '3')) {
212
            return 'comment';
213
        }
214 4
        return 'error';
215
    }
216
}
217