Passed
Push — master ( c90257...44ef80 )
by Ehsan
04:01
created

LoggerUtility::logChat()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0932

Importance

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