Completed
Push — master ( be0fcc...497120 )
by Ehsan
03:14
created

LoggerUtility::log()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 7
cts 8
cp 0.875
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 3
crap 3.0175
1
<?php
2
3
namespace Botonomous\utility;
4
5
use Monolog\Handler\StreamHandler;
6
use Monolog\Logger;
7
use Psr\Log\LoggerInterface;
8
9
/**
10
 * Class LoggerUtility.
11
 */
12
class LoggerUtility extends AbstractUtility
13
{
14
    const DATE_FORMAT = 'Y-m-d H:i:s';
15
    const TEMP_FOLDER = 'tmp';
16
17
    const DEBUG = 'debug';
18
    const INFO = 'info';
19
    const NOTICE = 'notice';
20
    const WARNING = 'warning';
21
    const ERROR = 'error';
22
    const CRITICAL = 'critical';
23
    const ALERT = 'alert';
24
    const EMERGENCY = 'emergency';
25
26
    public static $levels = [
27
        self::DEBUG,
28
        self::INFO,
29
        self::NOTICE,
30
        self::WARNING,
31
        self::ERROR,
32
        self::CRITICAL,
33
        self::ALERT,
34
        self::EMERGENCY,
35
    ];
36
37
    private $logger;
38
39
    /**
40
     * LoggerUtility constructor.
41
     *
42
     * @param null $config
43
     */
44 13
    public function __construct($config = null)
45
    {
46 13
        parent::__construct($config);
47
48 13
        $this->initLogger();
49 13
    }
50
51
    /**
52
     * Init the logger.
53
     */
54 13
    private function initLogger()
55
    {
56 13
        $monologConfig = $this->getMonologConfig();
57
58 13
        if (empty($monologConfig)) {
59
            return;
60
        }
61
62 13
        $logger = new Logger($monologConfig['channel']);
63
64 13
        foreach (array_keys($monologConfig['handlers']) as $value) {
65 13
            $logger = $this->pushMonologHandler($logger, $value);
66
        }
67
68 13
        $this->setLogger($logger);
69 13
    }
70
71
    /**
72
     * @return mixed
73
     */
74 13
    private function getMonologConfig()
75
    {
76 13
        $loggerConfig = $this->getConfig()->get('logger');
77
78 13
        return !empty($loggerConfig['monolog']) ? $loggerConfig['monolog'] : false;
79
    }
80
81
    /**
82
     * @param Logger $logger
83
     * @param        $handlerKey
84
     *
85
     * @return Logger
86
     */
87 13
    private function pushMonologHandler(Logger $logger, $handlerKey)
88
    {
89 13
        $activeHandlers = [];
90
91
        switch ($handlerKey) {
92 13
            case 'file':
93 13
                $activeHandlers[] = new StreamHandler($this->getLogFilePath());
0 ignored issues
show
Security Bug introduced by
It seems like $this->getLogFilePath() targeting Botonomous\utility\LoggerUtility::getLogFilePath() can also be of type false; however, Monolog\Handler\StreamHandler::__construct() does only seem to accept resource|string, did you maybe forget to handle an error condition?
Loading history...
94 13
                break;
95
        }
96
97 13
        if (!empty($activeHandlers)) {
98 13
            foreach ($activeHandlers as $activeHandler) {
99 13
                $logger->pushHandler($activeHandler);
100
            }
101
        }
102
103 13
        return $logger;
104
    }
105
106
    /**
107
     * @return bool|string
108
     */
109 13
    public function getLogFilePath()
110
    {
111 13
        $monologConfig = $this->getMonologConfig();
112
113 13
        if (!isset($monologConfig['handlers']['file']['fileName'])) {
114
            return false;
115
        }
116
117 13
        return $this->getTempDir().DIRECTORY_SEPARATOR.$monologConfig['handlers']['file']['fileName'];
118
    }
119
120
    /**
121
     * @return LoggerInterface
122
     */
123 11
    private function getLogger()
124
    {
125 11
        return $this->logger;
126
    }
127
128
    /**
129
     * @param LoggerInterface $logger
130
     */
131 13
    private function setLogger(LoggerInterface $logger)
132
    {
133 13
        $this->logger = $logger;
134 13
    }
135
136
    /**
137
     * @param string $function
138
     * @param string $message
139
     * @param string $channel
140
     *
141
     * @throws \Exception
142
     *
143
     * @return bool
144
     */
145 11
    public function logChat($function, $message = '', $channel = '')
146
    {
147
        try {
148 11
            return $this->logInfo('Log Chat', [
149 11
                'function' => $function,
150 11
                'message'  => $message,
151 11
                'channel'  => $channel,
152
            ]);
153
        } catch (\Exception $e) {
154
            throw new \Exception($e->getMessage());
155
        }
156
    }
157
158
    /**
159
     * @throws \Exception
160
     *
161
     * @return bool
162
     */
163 13
    private function canLog()
164
    {
165 13
        $loggerConfig = $this->getConfig()->get('logger');
166
167 13
        return empty($loggerConfig['enabled']) ? false : true;
168
    }
169
170
    /**
171
     * @throws \Exception
172
     *
173
     * @return string
174
     */
175 13
    public function getTempDir()
176
    {
177 13
        return dirname(__DIR__).DIRECTORY_SEPARATOR.self::TEMP_FOLDER;
178
    }
179
180
    /**
181
     * @param $function
182
     * @param string $message
183
     * @param $channel
184
     *
185
     * @return string
186
     */
187
    public function getLogContent($function, $message, $channel)
188
    {
189
        return "{$function}|{$message}|{$channel}";
190
    }
191
192
    /**
193
     * @param       $message
194
     * @param array $context
195
     *
196
     * @return bool
197
     */
198
    public function logDebug($message, array $context = [])
199
    {
200
        return $this->log(self::DEBUG, $message, $context);
201
    }
202
203
    /**
204
     * @param       $message
205
     * @param array $context
206
     *
207
     * @return bool
208
     */
209 13
    public function logInfo($message, array $context = [])
210
    {
211 13
        return $this->log(self::INFO, $message, $context);
212
    }
213
214
    /**
215
     * @param       $message
216
     * @param array $context
217
     *
218
     * @return bool
219
     */
220
    public function logNotice($message, array $context = [])
221
    {
222
        return $this->log(self::NOTICE, $message, $context);
223
    }
224
225
    /**
226
     * @param       $message
227
     * @param array $context
228
     *
229
     * @return bool
230
     */
231
    public function logWarning($message, array $context = [])
232
    {
233
        return $this->log(self::WARNING, $message, $context);
234
    }
235
236
    /**
237
     * @param       $message
238
     * @param array $context
239
     *
240
     * @return bool
241
     */
242
    public function logError($message, array $context = [])
243
    {
244
        return $this->log(self::ERROR, $message, $context);
245
    }
246
247
    /**
248
     * @param       $message
249
     * @param array $context
250
     *
251
     * @return bool
252
     */
253
    public function logCritical($message, array $context = [])
254
    {
255
        return $this->log(self::CRITICAL, $message, $context);
256
    }
257
258
    /**
259
     * @param       $message
260
     * @param array $context
261
     *
262
     * @return bool
263
     */
264
    public function logAlert($message, array $context = [])
265
    {
266
        return $this->log(self::ALERT, $message, $context);
267
    }
268
269
    /**
270
     * @param       $message
271
     * @param array $context
272
     *
273
     * @return bool
274
     */
275
    public function logEmergency($message, array $context = [])
276
    {
277
        return $this->log(self::EMERGENCY, $message, $context);
278
    }
279
280
    /**
281
     * @param $level
282
     * @param $message
283
     * @param array $context
284
     *
285
     * @throws \Exception
286
     *
287
     * @return bool
288
     */
289 13
    private function log($level, $message, $context = [])
290
    {
291 13
        if ($this->canLog() !== true) {
292 2
            return false;
293
        }
294
295 11
        $logger = $this->getLogger();
296
297 11
        if (!in_array($level, self::$levels)) {
298
            throw new \Exception("'{$level}' is invalid log level");
299
        }
300
301 11
        $logger->$level($message, $context);
302
303 11
        return true;
304
    }
305
}
306