Completed
Branch master (8850d0)
by George
23:15 queued 10:15
created

ConsoleObserver::sendEmailResults()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 43
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 1
Metric Value
c 6
b 1
f 1
dl 0
loc 43
rs 8.439
cc 6
eloc 29
nc 15
nop 1
1
<?php
2
3
namespace SiteChecker;
4
5
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Log\LoggerInterface;
8
9
/**
10
 * Class ConsoleObserver
11
 * @package SiteChecker
12
 */
13
class ConsoleObserver implements SiteCheckObserver
14
{
15
16
    /**
17
     * @var LoggerInterface
18
     */
19
    protected $logger;
20
21
    /**
22
     * @var Config
23
     */
24
    protected $config;
25
26
    /**
27
     * @param Config $config
28
     */
29
    public function setConfig($config)
30
    {
31
        $this->config = $config;
32
    }
33
34
    /**
35
     * SiteChecker constructor.
36
     * @param \Psr\Log\LoggerInterface|null $logger
37
     */
38
    public function __construct(LoggerInterface $logger = null)
39
    {
40
        $this->logger = $logger;
41
    }
42
43
    /**
44
     * No additional checks here for now.
45
     *
46
     * @param \SiteChecker\Asset $url
47
     * @return bool
48
     */
49
    public function pageToCheck(Asset $url)
50
    {
51
        return true;
52
    }
53
54
55
    /**
56
     * Log page to console.
57
     *
58
     * @param \SiteChecker\Asset $asset
59
     * @param $response
60
     * @return mixed
61
     */
62
    public function pageChecked(
63
        Asset $asset,
64
        ResponseInterface $response = null
65
    ) {
66
        $this->logResult($asset);
67
    }
68
69
70
    /**
71
     * Show results.
72
     *
73
     * @param Asset[] $assets
74
     */
75
    public function receiveResults(array $assets)
76
    {
77
        $this->showResults($assets);
78
        if (!empty($this->config->reportEmail)) {
79
            $this->sendEmailResults($assets);
80
        }
81
    }
82
83
    /**
84
     * Show results.
85
     *
86
     * @param Asset[] $assets
87
     */
88
    protected function sendEmailResults($assets)
89
    {
90
        $countFailed = 0;
91
        $messages = [];
92
        $assets = array_filter(
93
            $assets,
94
            function(Asset $asset) {
95
                return $asset->isError();
96
            }
97
        );
98
        /** @var Asset $asset */
99
        foreach ($assets as $asset) {
100
            $countFailed++;
101
            $message = ' * '. $asset->getURL();
102
            if ($asset->getParentPage() instanceof Asset) {
103
                $message .= ' on ' . $asset->getParentPage()->getURL();
104
            }
105
            $messages[] = $message;
106
107
        }
108
        if (empty($messages)) {
109
            return;
110
        }
111
112
        $mail = new \PHPMailer();
113
        $mailFrom = $this->config->getMailFrom();
114
        $mail->setFrom($mailFrom, 'Site Checker');
115
        $addresses = $this->config->getReportEmailAddresses();
116
        foreach ($addresses as $emailAddress) {
117
            $mail->addAddress($emailAddress);
118
        }
119
120
        $mail->Subject = 'SiteChecker report';
121
        $mail->Body = "Hi, here are some broken links on your website:\n\n";
122
        $mail->Body .= implode(PHP_EOL, $messages);
123
124
        if (!$mail->send()) {
125
            $this->logger->error('Message could not be sent.');
126
            $this->logger->error('Mailer Error: ' . $mail->ErrorInfo);
127
        } else {
128
            $this->logger->info('Message has been sent');
129
        }
130
    }
131
132
    /**
133
     * Called when the checker has checked the given page.
134
     *
135
     * @param Asset $asset
136
     */
137
    public function logResult($asset)
138
    {
139
        $code = ($asset instanceof Asset) ? $asset->getResponseCode() : Asset::CODE_ERROR;
140
        $messageParts = ['Checking'];
141
        $messageParts[] = 'asset: ' . $asset->getURL();
142
        if ($parent = $asset->getParentPage()) {
143
            $messageParts[] = 'on a page: ' . $parent->getURL() . '.';
144
        }
145
        if ($this->config->showFullTags && $html = $asset->getFullHtml()) {
146
            $messageParts[] = 'Full html of it is: ' . $html . '.';
147
        }
148
        $messageParts[] = 'Received code: ' . $code;
149
        $message = implode(' ', $messageParts);
150
151
        if ($asset->isError()) {
152
            $this->logger->error($message);
153
        } elseif ($asset->isWarning()) {
154
            $this->logger->warning($message);
155
        } else {
156
            $this->logger->info($message);
157
        }
158
    }
159
160
    /**
161
     * Called when the check was ended.
162
     *
163
     * @param Asset[] $assets
164
     */
165
    public function showResults(array $assets)
166
    {
167
        $this->logger->info("Check is finished. Here are the results:");
168
        $successCount = 0;
169
        $failedCount = 0;
170
171
        foreach ($assets as $asset) {
172
            if ($asset->isSuccessful()) {
173
                $successCount++;
174
            } else {
175
                $failedCount++;
176
            }
177
        }
178
        if ($successCount) {
179
            $this->logger->info('Successful: ' . $successCount);
180
        }
181
        if ($failedCount) {
182
            $this->logger->error('Failed: ' . $failedCount);
183
        }
184
    }
185
}
186