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.
Completed
Pull Request — master (#66)
by
unknown
01:00
created

CrawlLogger   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 4
dl 0
loc 176
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A willCrawl() 0 3 1
A finishedCrawling() 0 24 4
A getColorTagForStatusCode() 0 12 3
A startsWith() 0 10 4
A setOutputFile() 0 4 1
A crawled() 0 38 4
A crawlFailed() 0 11 2
A addResult() 0 20 5
1
<?php
2
3
namespace Spatie\HttpStatusCheck;
4
5
use GuzzleHttp\Exception\RequestException;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\UriInterface;
8
use Spatie\Crawler\CrawlObserver;
9
use Symfony\Component\Console\Output\OutputInterface;
10
11
class CrawlLogger extends CrawlObserver
12
{
13
    const UNRESPONSIVE_HOST = 'Host did not respond';
14
15
    /**
16
     * @var \Symfony\Component\Console\Output\OutputInterface
17
     */
18
    protected $consoleOutput;
19
20
    /**
21
     * @var array
22
     */
23
    protected $crawledUrls = [];
24
25
    /**
26
     * @var string|null
27
     */
28
    protected $outputFile = null;
29
30
    /**
31
     * @param \Symfony\Component\Console\Output\OutputInterface $consoleOutput
32
     */
33
    public function __construct(OutputInterface $consoleOutput)
34
    {
35
        $this->consoleOutput = $consoleOutput;
36
    }
37
38
    /**
39
     * Called when the crawl will crawl the url.
40
     *
41
     * @param \Psr\Http\Message\UriInterface $url
42
     */
43
    public function willCrawl(UriInterface $url)
44
    {
45
    }
46
47
    /**
48
     * Called when the crawl has ended.
49
     */
50
    public function finishedCrawling()
51
    {
52
        $this->consoleOutput->writeln('');
53
        $this->consoleOutput->writeln('Crawling summary');
54
        $this->consoleOutput->writeln('----------------');
55
56
        ksort($this->crawledUrls);
57
58
        foreach ($this->crawledUrls as $statusCode => $urls) {
59
            $colorTag = $this->getColorTagForStatusCode($statusCode);
60
61
            $count = count($urls);
62
63
            if (is_numeric($statusCode)) {
64
                $this->consoleOutput->writeln("<{$colorTag}>Crawled {$count} url(s) with statuscode {$statusCode}</{$colorTag}>");
65
            }
66
67
            if ($statusCode == static::UNRESPONSIVE_HOST) {
68
                $this->consoleOutput->writeln("<{$colorTag}>{$count} url(s) did have unresponsive host(s)</{$colorTag}>");
69
            }
70
        }
71
72
        $this->consoleOutput->writeln('');
73
    }
74
75
    protected function getColorTagForStatusCode(string $code): string
76
    {
77
        if ($this->startsWith($code, '2')) {
78
            return 'info';
79
        }
80
81
        if ($this->startsWith($code, '3')) {
82
            return 'comment';
83
        }
84
85
        return 'error';
86
    }
87
88
    /**
89
     * @param string|null $haystack
90
     * @param string|array $needles
91
     *
92
     * @return bool
93
     */
94
    public function startsWith($haystack, $needles): bool
95
    {
96
        foreach ((array) $needles as $needle) {
97
            if ($needle != '' && substr($haystack, 0, strlen($needle)) === (string) $needle) {
98
                return true;
99
            }
100
        }
101
102
        return false;
103
    }
104
105
    /**
106
     * Set the filename to write the output log.
107
     *
108
     * @param string $filename
109
     */
110
    public function setOutputFile($filename)
111
    {
112
        $this->outputFile = $filename;
113
    }
114
115
    public function crawled(
116
        UriInterface $url,
117
        ResponseInterface $response,
118
        ?UriInterface $foundOnUrl = null
119
    ) {
120
        // https://github.com/guzzle/guzzle/blob/master/docs/faq.rst#how-can-i-track-redirected-requests
121
        if ($response->getHeader('X-Guzzle-Redirect-History')) {
122
            // Retrieve both Redirect History headers
123
            $fullRedirectReport = [];
0 ignored issues
show
Unused Code introduced by
$fullRedirectReport is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
124
            // Retrieve both Redirect History headers
125
            $redirectUriHistory = $response->getHeader('X-Guzzle-Redirect-History'); // retrieve Redirect URI history
126
            $redirectCodeHistory = $response->getHeader('X-Guzzle-Redirect-Status-History'); // retrieve Redirect HTTP Status history
127
            // Add the initial URI requested to the (beginning of) URI history
128
            array_unshift($redirectUriHistory, (string) $url);
129
            // Add the final HTTP status code to the end of HTTP response history
130
            array_push($redirectCodeHistory, $response->getStatusCode());
131
            $fullRedirectReport = [];
132
            foreach ($redirectUriHistory as $key => $value) {
133
                $fullRedirectReport[$key] = ['location' => $value, 'code' => $redirectCodeHistory[$key]];
134
            }
135
136
            foreach ($fullRedirectReport as $k=>$redirect) {
137
                $this->addResult(
138
                    (string) $redirect['location'],
139
                    (string) $foundOnUrl,
140
                    $redirect['code'],
141
                    $response->getReasonPhrase()
142
                );
143
            }
144
        } else {
145
            $this->addResult(
146
                (string) $url,
147
                (string) $foundOnUrl,
148
                $response->getStatusCode(),
149
                $response->getReasonPhrase()
150
            );
151
        }
152
    }
153
154
    public function crawlFailed(
155
        UriInterface $url,
156
        RequestException $requestException,
157
        ?UriInterface $foundOnUrl = null
158
    ) {
159
        if ($response = $requestException->getResponse()) {
160
            $this->crawled($url, $response, $foundOnUrl);
161
        } else {
162
            $this->addResult((string) $url, (string) $foundOnUrl, '---', self::UNRESPONSIVE_HOST);
163
        }
164
    }
165
166
    public function addResult($url, $foundOnUrl, $statusCode, $reason)
167
    {
168
        $colorTag = $this->getColorTagForStatusCode($statusCode);
169
170
        $timestamp = date('Y-m-d H:i:s');
171
172
        $message = "{$statusCode} {$reason} - ".(string) $url;
173
174
        if ($foundOnUrl && $colorTag === 'error') {
175
            $message .= " (found on {$foundOnUrl})";
176
        }
177
178
        if ($this->outputFile && $colorTag === 'error') {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->outputFile of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
179
            file_put_contents($this->outputFile, $message.PHP_EOL, FILE_APPEND);
180
        }
181
182
        $this->consoleOutput->writeln("<{$colorTag}>[{$timestamp}] {$message}</{$colorTag}>");
183
184
        $this->crawledUrls[$statusCode][] = $url;
185
    }
186
}
187