Completed
Push — master ( cdf584...500099 )
by Brent
12s
created

LogBrokenLinks::formatLogMessage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 11
nc 2
nop 3
1
<?php
2
3
namespace Spatie\LinkChecker\Reporters;
4
5
use GuzzleHttp\Exception\RequestException;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\UriInterface;
8
use Psr\Log\LoggerInterface;
9
10
class LogBrokenLinks extends BaseReporter
11
{
12
    protected $log;
13
14
    public function __construct(LoggerInterface $log)
15
    {
16
        $this->log = $log;
17
    }
18
19
    /**
20
     * Called when the crawl has ended.
21
     */
22
    public function finishedCrawling()
23
    {
24
        $this->log->info('link checker summary');
25
26
        collect($this->urlsGroupedByStatusCode)
27
            ->each(function ($urls, $statusCode) {
28
                if ($this->isSuccessOrRedirect($statusCode)) {
29
                    return;
30
                }
31
32
                $count = count($urls);
33
34
                if ($statusCode == static::UNRESPONSIVE_HOST) {
35
                    $this->log->warning("{$count} url(s) did have unresponsive host(s)");
36
37
                    return;
38
                }
39
40
                $this->log->warning("Crawled {$count} url(s) with statuscode {$statusCode}");
41
42
            });
43
    }
44
45
    /**
46
     * Called when the crawler had a problem crawling the given url.
47
     *
48
     * @param \Psr\Http\Message\UriInterface         $url
49
     * @param \GuzzleHttp\Exception\RequestException $requestException
50
     * @param \Psr\Http\Message\UriInterface|null    $foundOnUrl
51
     */
52
    public function crawlFailed(
53
        UriInterface $url,
54
        RequestException $requestException,
55
        ?UriInterface $foundOnUrl = null
56
    ) {
57
        parent::crawlFailed($url, $requestException, $foundOnUrl);
58
59
        $statusCode = $requestException->getCode();
60
61
        if ($this->isExcludedStatusCode($statusCode)) {
62
            return;
63
        }
64
65
        $this->log->warning(
66
            $this->formatLogMessage($url, $requestException, $foundOnUrl)
67
        );
68
    }
69
70
    protected function formatLogMessage(
71
        UriInterface $url,
72
        RequestException $requestException,
73
        ?UriInterface $foundOnUrl = null
74
    ): string {
75
        $statusCode = $requestException->getCode();
76
77
        $reason = $requestException->getMessage();
78
79
        $logMessage = "{$statusCode} {$reason} - {$url}";
80
81
        if ($foundOnUrl) {
82
            $logMessage .= " (found on {$foundOnUrl}";
83
        }
84
85
        return $logMessage;
86
    }
87
}
88