Completed
Push — master ( 6219d6...964648 )
by Iurii
01:04
created

ErrorNotifier::getEmailErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
/**
4
 * @package Error Notifier
5
 * @author Iurii Makukh <[email protected]>
6
 * @copyright Copyright (c) 2017, Iurii Makukh <[email protected]>
7
 * @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL-3.0+
8
 */
9
10
namespace gplcart\modules\error_notifier;
11
12
use gplcart\core\Module;
13
14
/**
15
 * Main class for Error Notifier module
16
 */
17
class ErrorNotifier extends Module
18
{
19
20
    /**
21
     * Constructor
22
     */
23
    public function __construct()
24
    {
25
        parent::__construct();
26
    }
27
28
    /**
29
     * Implements hook "route.list"
30
     * @param array $routes
31
     */
32
    public function hookRouteList(array &$routes)
33
    {
34
        $routes['admin/module/settings/error_notifier'] = array(
35
            'access' => 'module_edit',
36
            'handlers' => array(
37
                'controller' => array('gplcart\\modules\\error_notifier\\controllers\\Settings', 'editSettings')
38
            )
39
        );
40
    }
41
42
    /**
43
     * Implements hook "cron"
44
     * @param \gplcart\core\Controller $controller
45
     */
46
    public function hookCron($controller)
47
    {
48
        $this->setEmailReport($controller);
49
    }
50
51
    /**
52
     * Implements hook "template.output"
53
     * @param string $template
54
     * @param array $data
55
     * @param \gplcart\core\Controller $controller
56
     */
57
    public function hookTemplate($template, array &$data, $controller)
58
    {
59
        $limit = 'layout/body';
60
61
        if (substr($template, -strlen($limit)) === $limit) {
62
            $this->setLiveReport($data, $controller);
63
        }
64
    }
65
66
    /**
67
     * Sends last PHP errors via Email
68
     * @param \gplcart\core\Controller $controller
69
     */
70
    protected function setEmailReport($controller)
71
    {
72
        $settings = $this->config->module('error_notifier');
73
74
        if (!empty($settings['email']) && !empty($settings['recipient'])) {
75
            $messages = $this->getEmailErrors($settings, $controller);
76
            if (!empty($messages)) {
77
                $this->sendEmail($settings, $messages, $controller);
78
            }
79
        }
80
    }
81
82
    /**
83
     * Sends an E-mail
84
     * @param array $settings
85
     * @param array $messages
86
     * @param \gplcart\core\Controller $controller
87
     */
88
    protected function sendEmail(array $settings, array $messages, $controller)
89
    {
90
        /* @var $mailer \gplcart\core\models\Mail */
91
        $mailer = $this->getInstance('gplcart\\core\\models\Mail');
92
93
        $subject = 'Last PHP errors';
94
        $body = implode("\r\n", $messages);
95
        $from = $controller->getStore('data.email.0');
96
97
        $mailer->send($settings['recipient'], $subject, $body, $from);
98
    }
99
100
    /**
101
     * Returns an array of PHP errors to send via Email
102
     * @param array $settings
103
     * @param \gplcart\core\Controller $controller
104
     * @return array
105
     */
106
    protected function getEmailErrors(array $settings, $controller)
107
    {
108
        if (empty($settings['email_limit'])) {
109
            $settings['email_limit'] = null; // Unlimited
110
        }
111
112
        /* @var $logger \gplcart\core\Logger */
113
        $logger = $this->getInstance('gplcart\\core\\Logger');
114
        $errors = $logger->selectPhpErrors($settings['email_limit']);
115
116
        return $this->getFormattedErrors($errors, $controller);
117
    }
118
119
    /**
120
     * Sets live error reporting
121
     * @param array $data
122
     * @param \gplcart\core\Controller $controller
123
     */
124
    protected function setLiveReport(array &$data, $controller)
125
    {
126
        $settings = $this->config->module('error_notifier');
127
        $messages = $this->getLiveErrors($settings, $controller);
128
129
        if (empty($messages)) {
130
            return null;
131
        }
132
133
        $this->prepareMessages($messages, $settings, $controller);
134
135
        foreach ($messages as $message) {
136
            $data['_messages']['warning'][] = $message;
137
        }
138
    }
139
140
    /**
141
     * Prepare an array of messages
142
     * @param array $messages
143
     * @param array $settings
144
     * @param \gplcart\core\Controller $controller
145
     */
146
    protected function prepareMessages(&$messages, $settings, $controller)
147
    {
148
        if ($controller->path('^admin/report/events$')) {
149
            $messages = array(); // Suppress errors on admin/report/events page
150
            return null;
151
        }
152
153
        $remaining = count($messages) - $settings['live_limit'];
154
155
        if (!empty($settings['live_limit']) && $remaining > 0) {
156
            $messages = array_slice($messages, 0, $settings['live_limit']);
157
            $messages[] = $controller->text('...and @remaining more', array('@remaining' => $remaining));
158
        }
159
160
        if ($controller->access('report_events')) {
161
            $message = $controller->text('<a href="@href">see saved errors</a>', array('@href' => $controller->url('admin/report/events', array('type' => 'php_error'))));
162
            if ($settings['live'] == 2) {
163
                $vars = array('@href' => $controller->url('admin/report/events', array('clear' => true, 'target' => $controller->path())));
164
                $message .= ' | ' . $controller->text('<a href="@href">clear all saved errors</a>', $vars);
165
            }
166
167
            $messages[] = $message;
168
        }
169
    }
170
171
    /**
172
     * Returns an array of PHP errors for live reporting
173
     * @param array $settings
174
     * @param \gplcart\core\Controller $controller
175
     * @return array
176
     */
177
    protected function getLiveErrors(array $settings, $controller)
178
    {
179
        if (empty($settings['live'])) {
180
            return array();
181
        }
182
183
        /* @var $logger \gplcart\core\Logger */
184
        $logger = $this->getInstance('gplcart\\core\\Logger');
185
186
        $errors = array();
187
        if ($settings['live'] == 1) {
188
            $errors = $logger->getPhpErrors(false);
189
        } else if ($settings['live'] == 2) {
190
            $errors = $logger->selectPhpErrors();
191
        }
192
193
        return $this->getFormattedErrors($errors, $controller);
194
    }
195
196
    /**
197
     * Returns an array of formatted error messages
198
     * @param array $errors
199
     * @param \gplcart\core\Controller $controller
200
     * @return array
201
     */
202
    protected function getFormattedErrors(array $errors, $controller)
203
    {
204
        $messages = array();
205
        foreach ($errors as $error) {
206
            $vars = array(
207
                '@line' => $error['line'],
208
                '@message' => $error['message'],
209
                '@file' => gplcart_relative_path($error['file'])
210
            );
211
            $messages[] = $controller->text('@message on line @line in @file', $vars);
212
        }
213
214
        return $messages;
215
    }
216
217
}
218