Passed
Push — master ( 49600b...32b362 )
by Ehsan
03:58
created

LoggerUtility::getMonologConfigFileName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 5
cp 0.8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2.032
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
     * @throws \Exception
45
     */
46 23
    public function __construct($config = null)
47
    {
48 23
        parent::__construct($config);
49
50
        try {
51 23
            $this->initLogger();
52 1
        } catch (\Exception $e) {
53 1
            throw $e;
54
        }
55 22
    }
56
57
    /**
58
     * Init the logger.
59
     */
60 23
    private function initLogger()
61
    {
62 23
        $monologConfig = $this->getMonologConfig();
63
64 23
        if (empty($monologConfig)) {
65 1
            throw new \Exception('Monolog config is missing');
66
        }
67
68 22
        $logger = new Logger($monologConfig['channel']);
69
70 22
        foreach (array_keys($monologConfig['handlers']) as $value) {
71 22
            $logger = $this->pushMonologHandler($logger, $value);
72
        }
73
74 22
        $this->setLogger($logger);
75 22
    }
76
77
    /**
78
     * @return mixed
79
     */
80 23
    private function getMonologConfig()
81
    {
82 23
        $loggerConfig = $this->getConfig()->get('logger');
83
84 23
        return !empty($loggerConfig['monolog']) ? $loggerConfig['monolog'] : false;
85
    }
86
87
    /**
88
     * @param Logger $logger
89
     * @param        $handlerKey
90
     *
91
     * @return Logger
92
     */
93 22
    private function pushMonologHandler(Logger $logger, $handlerKey)
94
    {
95 22
        $activeHandlers = [];
96
97
        switch ($handlerKey) {
98 22
            case 'file':
99 22
                $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...
100 22
                break;
101
        }
102
103 22
        if (!empty($activeHandlers)) {
104 22
            foreach ($activeHandlers as $activeHandler) {
105 22
                $logger->pushHandler($activeHandler);
106
            }
107
        }
108
109 22
        return $logger;
110
    }
111
112
    /**
113
     * @return false|string
114
     */
115 22
    public function getLogFilePath()
116
    {
117 22
        $monologConfigFileName = $this->getMonologConfigFileName();
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $monologConfigFileName exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
118 22
        if (empty($monologConfigFileName)) {
119
            return false;
120
        }
121
122 22
        return $this->getTempDir().DIRECTORY_SEPARATOR.$monologConfigFileName;
123
    }
124
125
    /**
126
     * @return mixed
127
     */
128 22
    private function getMonologConfigFileName()
129
    {
130 22
        $monologConfig = $this->getMonologConfig();
131
132 22
        if (isset($monologConfig['handlers']['file']['fileName'])) {
133 22
            return $monologConfig['handlers']['file']['fileName'];
134
        }
135
136
        return;
137
    }
138
139
    /**
140
     * @return LoggerInterface
141
     */
142 19
    private function getLogger()
143
    {
144 19
        return $this->logger;
145
    }
146
147
    /**
148
     * @param LoggerInterface $logger
149
     */
150 22
    private function setLogger(LoggerInterface $logger)
151
    {
152 22
        $this->logger = $logger;
153 22
    }
154
155
    /**
156
     * @param string $function
157
     * @param string $message
158
     * @param string $channel
159
     *
160
     * @throws \Exception
161
     *
162
     * @return bool
163
     */
164 11
    public function logChat($function, $message = '', $channel = '')
165
    {
166
        try {
167 11
            return $this->logInfo('Log Chat', [
168 11
                'function' => $function,
169 11
                'message'  => $message,
170 11
                'channel'  => $channel,
171
            ]);
172
        } catch (\Exception $e) {
173
            throw new \Exception($e->getMessage());
174
        }
175
    }
176
177
    /**
178
     * @throws \Exception
179
     *
180
     * @return bool
181
     */
182 21
    private function canLog()
183
    {
184 21
        $loggerConfig = $this->getConfig()->get('logger');
185
186 21
        return empty($loggerConfig['enabled']) ? false : true;
187
    }
188
189
    /**
190
     * @throws \Exception
191
     *
192
     * @return string
193
     */
194 22
    public function getTempDir()
195
    {
196 22
        return dirname(__DIR__).DIRECTORY_SEPARATOR.self::TEMP_FOLDER;
197
    }
198
199
    /**
200
     * @param $function
201
     * @param string $message
202
     * @param $channel
203
     *
204
     * @return string
205
     */
206 1
    public function getLogContent($function, $message, $channel)
207
    {
208 1
        return "{$function}|{$message}|{$channel}";
209
    }
210
211
    /**
212
     * @param       $message
213
     * @param array $context
214
     *
215
     * @return bool
216
     */
217 1
    public function logDebug($message, array $context = [])
218
    {
219 1
        return $this->log(self::DEBUG, $message, $context);
220
    }
221
222
    /**
223
     * @param string $message
224
     * @param array  $context
225
     *
226
     * @return bool
227
     */
228 13
    public function logInfo($message, array $context = [])
229
    {
230 13
        return $this->log(self::INFO, $message, $context);
231
    }
232
233
    /**
234
     * @param       $message
235
     * @param array $context
236
     *
237
     * @return bool
238
     */
239 1
    public function logNotice($message, array $context = [])
240
    {
241 1
        return $this->log(self::NOTICE, $message, $context);
242
    }
243
244
    /**
245
     * @param       $message
246
     * @param array $context
247
     *
248
     * @return bool
249
     */
250 1
    public function logWarning($message, array $context = [])
251
    {
252 1
        return $this->log(self::WARNING, $message, $context);
253
    }
254
255
    /**
256
     * @param       $message
257
     * @param array $context
258
     *
259
     * @return bool
260
     */
261 1
    public function logError($message, array $context = [])
262
    {
263 1
        return $this->log(self::ERROR, $message, $context);
264
    }
265
266
    /**
267
     * @param       $message
268
     * @param array $context
269
     *
270
     * @return bool
271
     */
272 1
    public function logCritical($message, array $context = [])
273
    {
274 1
        return $this->log(self::CRITICAL, $message, $context);
275
    }
276
277
    /**
278
     * @param       $message
279
     * @param array $context
280
     *
281
     * @return bool
282
     */
283 1
    public function logAlert($message, array $context = [])
284
    {
285 1
        return $this->log(self::ALERT, $message, $context);
286
    }
287
288
    /**
289
     * @param       $message
290
     * @param array $context
291
     *
292
     * @return bool
293
     */
294 1
    public function logEmergency($message, array $context = [])
295
    {
296 1
        return $this->log(self::EMERGENCY, $message, $context);
297
    }
298
299
    /**
300
     * @param string $level
301
     * @param $message
302
     * @param array $context
303
     *
304
     * @throws \Exception
305
     *
306
     * @return bool
307
     */
308 21
    public function log($level, $message, $context = [])
309
    {
310 21
        if ($this->canLog() !== true) {
311 2
            return false;
312
        }
313
314 19
        $logger = $this->getLogger();
315
316 19
        if (!in_array($level, self::$levels)) {
317 1
            throw new \Exception("'{$level}' is an invalid log level");
318
        }
319
320 18
        $logger->$level($message, $context);
321
322 18
        return true;
323
    }
324
}
325