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:02
created

CrawlLogger::crawlFailed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 3
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
    const REDIRECT = 'Redirect';
15
16
    /**
17
     * @var \Symfony\Component\Console\Output\OutputInterface
18
     */
19
    protected $consoleOutput;
20
21
    /**
22
     * @var array
23
     */
24
    protected $crawledUrls = [];
25
26
    /**
27
     * @var string|null
28
     */
29
    protected $outputFile = null;
30
31
    /**
32
     * @param \Symfony\Component\Console\Output\OutputInterface $consoleOutput
33
     */
34
    public function __construct(OutputInterface $consoleOutput)
35
    {
36
        $this->consoleOutput = $consoleOutput;
37
    }
38
39
    /**
40
     * Called when the crawl will crawl the url.
41
     *
42
     * @param \Psr\Http\Message\UriInterface $url
43
     */
44
    public function willCrawl(UriInterface $url)
45
    {
46
    }
47
48
    /**
49
     * Called when the crawl has ended.
50
     */
51
    public function finishedCrawling()
52
    {
53
        $this->consoleOutput->writeln('');
54
        $this->consoleOutput->writeln('Crawling summary');
55
        $this->consoleOutput->writeln('----------------');
56
57
        ksort($this->crawledUrls);
58
59
        foreach ($this->crawledUrls as $statusCode => $urls) {
60
            $colorTag = $this->getColorTagForStatusCode($statusCode);
61
62
            $count = count($urls);
63
64
            if (is_numeric($statusCode)) {
65
                $this->consoleOutput->writeln("<{$colorTag}>Crawled {$count} url(s) with statuscode {$statusCode}</{$colorTag}>");
66
            }
67
68
            if ($statusCode == static::UNRESPONSIVE_HOST) {
69
                $this->consoleOutput->writeln("<{$colorTag}>{$count} url(s) did have unresponsive host(s)</{$colorTag}>");
70
            }
71
        }
72
73
        $this->consoleOutput->writeln('');
74
    }
75
76
    protected function getColorTagForStatusCode(string $code): string
77
    {
78
        if ($this->startsWith($code, '2')) {
79
            return 'info';
80
        }
81
82
        if ($this->startsWith($code, '3')) {
83
            return 'comment';
84
        }
85
86
        return 'error';
87
    }
88
89
    /**
90
     * @param string|null $haystack
91
     * @param string|array $needles
92
     *
93
     * @return bool
94
     */
95
    public function startsWith($haystack, $needles): bool
96
    {
97
        foreach ((array) $needles as $needle) {
98
            if ($needle != '' && substr($haystack, 0, strlen($needle)) === (string) $needle) {
99
                return true;
100
            }
101
        }
102
103
        return false;
104
    }
105
106
    /**
107
     * Set the filename to write the output log.
108
     *
109
     * @param string $filename
110
     */
111
    public function setOutputFile($filename)
112
    {
113
        $this->outputFile = $filename;
114
    }
115
116
    public function crawled(
117
        UriInterface $url,
118
        ResponseInterface $response,
119
        ?UriInterface $foundOnUrl = null
120
    ) {
121
122
        if($this->addRedirectedResult($url, $response, $foundOnUrl)){
123
            return;
124
        }
125
126
        // response wasnt a redirect so lets add it as a standard result
127
        $this->addResult(
128
            (string) $url,
129
            (string) $foundOnUrl,
130
            $response->getStatusCode(),
131
            $response->getReasonPhrase()
132
        );
133
    }
134
135
    public function crawlFailed(
136
        UriInterface $url,
137
        RequestException $requestException,
138
        ?UriInterface $foundOnUrl = null
139
    ) {
140
        if ($response = $requestException->getResponse()) {
141
            $this->crawled($url, $response, $foundOnUrl);
142
        } else {
143
            $this->addResult((string) $url, (string) $foundOnUrl, '---', self::UNRESPONSIVE_HOST);
144
        }
145
    }
146
147
    public function addResult($url, $foundOnUrl, $statusCode, $reason)
148
    {
149
        /*
150
        * don't display duplicate results
151
        * this happens if a redirect is followed to an existing page
152
        */
153
        if (isset($this->crawledUrls[$statusCode]) && in_array($url, $this->crawledUrls[$statusCode])) {
154
            return;
155
        }
156
157
        $colorTag = $this->getColorTagForStatusCode($statusCode);
158
159
        $timestamp = date('Y-m-d H:i:s');
160
161
        $message = "{$statusCode} {$reason} - ".(string) $url;
162
163
        if ($foundOnUrl && $colorTag === 'error') {
164
            $message .= " (found on {$foundOnUrl})";
165
        }
166
167
        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...
168
            file_put_contents($this->outputFile, $message.PHP_EOL, FILE_APPEND);
169
        }
170
171
        $this->consoleOutput->writeln("<{$colorTag}>[{$timestamp}] {$message}</{$colorTag}>");
172
173
        $this->crawledUrls[$statusCode][] = $url;
174
    }
175
176
    /*
177
    * https://github.com/guzzle/guzzle/blob/master/docs/faq.rst#how-can-i-track-redirected-requests
178
    */
179
    public function addRedirectedResult(
180
        UriInterface $url,
181
        ResponseInterface $response,
182
        ?UriInterface $foundOnUrl = null
183
    ){
184
        // if its not a redirect the return false
185
        if (!$response->getHeader('X-Guzzle-Redirect-History')) {
186
            return false;
187
        }
188
189
        // retrieve Redirect URI history
190
        $redirectUriHistory = $response->getHeader('X-Guzzle-Redirect-History');
191
192
        // retrieve Redirect HTTP Status history
193
        $redirectCodeHistory = $response->getHeader('X-Guzzle-Redirect-Status-History');
194
195
        // Add the initial URI requested to the (beginning of) URI history
196
        array_unshift($redirectUriHistory, (string) $url);
197
198
        // Add the final HTTP status code to the end of HTTP response history
199
        array_push($redirectCodeHistory, $response->getStatusCode());
200
201
        // Combine the items of each array into a single result set
202
        $fullRedirectReport = [];
203
        foreach ($redirectUriHistory as $key => $value) {
204
            $fullRedirectReport[$key] = ['location' => $value, 'code' => $redirectCodeHistory[$key]];
205
        }
206
207
        // Add the redirects and final URL as results
208
        foreach ($fullRedirectReport as $k=>$redirect) {
209
            $this->addResult(
210
                (string) $redirect['location'],
211
                (string) $foundOnUrl,
212
                $redirect['code'],
213
                $k + 1 == count($fullRedirectReport) ? $response->getReasonPhrase() : self::REDIRECT
214
            );
215
        }
216
217
        return true;
218
    }
219
220
}
221