Completed
Push — master ( bccdd5...4cd793 )
by Alessandro
04:51
created

SensiolabHelper::printResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 10
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 10
loc 10
rs 9.4286
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Alessandro
5
 * Date: 02/12/2015
6
 * Time: 13:47
7
 */
8
9
namespace Padosoft\Composer;
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
    public function __construct(Client $objguzzle, Command $objcommand)
29
    {
30
        $this->guzzle = $objguzzle;
31
        $this->command = $objcommand;
32
    }
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
    public function getSensiolabVulnerabilties($fileLock)
44
    {
45
        $this->addVerboseLog('Send request to sensiolab: <info>'.$fileLock.'</info>');
46
47
        $debug = false;//set to true to log into console output
48
        $headers = [
49
            //OPTIONS
50
            'allow_redirects' => [
51
                'max'             => 3,        // allow at most 10 redirects.
52
                'strict'          => true,      // use "strict" RFC compliant redirects.
53
                'referer'         => true,      // add a Referer header
54
                'protocols'       => ['http', 'https'], // only allow http and https URLs
55
                'track_redirects' => false
56
            ],
57
            'connect_timeout' => 20,//Use 0 to wait connection indefinitely
58
            'timeout' => 30, //Use 0 to wait response indefinitely
59
            'debug' => $debug,
60
            //HEADERS
61
            'headers'  => [
62
                'Accept' => 'application/json'
63
            ],
64
            //UPLOAD FORM FILE
65
            'multipart' => [
66
                [
67
                    'name' => 'lock',
68
                    'contents' => fopen($fileLock, 'r')
69
                ]
70
            ]
71
        ];
72
        $response = null;
73
74
        try {
75
            $iResponse = $this->guzzle->request('POST', 'https://security.sensiolabs.org/check_lock', $headers);
76
            $responseBody = $iResponse->getBody()->getContents();
77
            $response = json_decode($responseBody, true);
78
        } catch (\GuzzleHttp\Exception\ClientException $e) {
79
            $this->command->error("ClientException!\nMessage: ".$e->getMessage());
80
            $colorTag = $this->getColorTagForStatusCode($e->getResponse()->getStatusCode());
81
            $this->command->line("HTTP StatusCode: <{$colorTag}>".$e->getResponse()->getStatusCode()."<{$colorTag}>");
82
            $this->printMessage($e->getResponse());
83
            $this->printMessage($e->getRequest());
84
        } catch (\GuzzleHttp\Exception\RequestException $e) {
85
            $this->command->error("RequestException!\nMessage: ".$e->getMessage());
86
            $this->printMessage($e->getRequest());
87
            if ($e->hasResponse()) {
88
                $colorTag = $this->getColorTagForStatusCode($e->getResponse()->getStatusCode());
89
                $this->command->line("HTTP StatusCode: <{$colorTag}>".$e->getResponse()->getStatusCode()."<{$colorTag}>");
90
                $this->printMessage($e->getResponse());
91
            }
92
        }
93
        return $response;
94
    }
95
96
    /**
97
     * @param $name
98
     * @param $vulnerability
99
     */
100
    public function parseVulnerability($name, $vulnerability)
101
    {
102
        $data = [
103
            'name' => $name,
104
            'version' => $vulnerability['version'],
105
            'advisories' => array_values($vulnerability['advisories'])
106
        ];
107
        unset($this->tableVulnerabilities);
108
        foreach ($data['advisories'] as $key2 => $advisory) {
109
            $data2 = [
110
                'title' => $advisory['title'],
111
                'link' => $advisory['link'],
112
                'cve' => $advisory['cve']
113
            ];
114
115
            $dataTable = [
116
                'name' => $data['name'],
117
                'version' => $data['version'],
118
                'advisories' => $data2["title"]
119
            ];
120
121
            $this->addVerboseLog($data['name'] . " " . $data['version'] . " " . $data2["title"], true);
122
            $this->tableVulnerabilities[] =$dataTable;
123
        }
124
125
        return $this->tableVulnerabilities;
126
    }
127
128
    /**
129
     * @param            $msg
130
     * @param bool|false $error
131
     */
132
    private function addVerboseLog($msg, $error = false)
133
    {
134
        $verbose = $this->command->option('verbose');
135
        if ($verbose) {
136
            if ($error) {
137
                $this->command->error($msg);
138
            } else {
139
                $this->command->line($msg);
140
            }
141
        }
142
    }
143
144
    /**
145
     * @param \Psr\Http\Message\MessageInterface $message
146
     */
147
    private function printMessage(\Psr\Http\Message\MessageInterface $message)
148
    {
149
        if(is_a($message,'\Psr\Http\Message\RequestInterface')) {
150
            $type='REQUEST';
151
        } else if(is_a($message,'\Psr\Http\Message\ResponseInterface')) {
152
            $type='RESPONSE';
153
        }
154
        $this->command->info("$type:");
0 ignored issues
show
Bug introduced by
The variable $type 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...
155
        $headers='';
156
        foreach ($message->getHeaders() as $name => $values) {
157
            $headers .= $name . ': ' . implode(', ', $values) . "\r\n";
158
        }
159
        $this->command->comment($headers);
160
        if($type=='REQUEST') {
161
            $this->command->comment($message->getBody());
162
        } else if($type=='RESPONSE') {
163
            $this->command->comment($message->getBody()->getContents());
164
        }
165
    }
166
167
168
    /**
169
     * Get the color tag for the given status code.
170
     *
171
     * @param string $code
172
     *
173
     * @return string
174
     *
175
     * @see https://github.com/spatie/http-status-check/blob/master/src/CrawlLogger.php#L96
176
     */
177
    protected function getColorTagForStatusCode($code)
178
    {
179
        if (starts_with($code, '2')) {
180
            return 'info';
181
        }
182
        if (starts_with($code, '3')) {
183
            return 'comment';
184
        }
185
        return 'error';
186
    }
187
}