Debug::setKindOfReportLog()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 3
nc 2
nop 1
1
<?php
2
3
/**
4
 * Manage debug
5
 *
6
 * @category  	lib
7
 * @package   	lib\Entity
8
 * @author    	Judicaël Paquet <[email protected]>
9
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
10
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
11
 * @version   	Release: 1.0.0
12
 * @filesource	https://github.com/las93/venus2
13
 * @link      	https://github.com/las93
14
 * @since     	1.0
15
 */
16
namespace Venus\lib;
17
18
use \Venus\lib\Bash as Bash;
19
use \Venus\lib\Log\AbstractLogger as AbstractLogger;
20
use \Venus\lib\Log\LogLevel as LogLevel;
21
22
/**
23
 * This class manage the debug
24
 *
25
 * @category  	lib
26
 * @package   	lib\Entity
27
 * @author    	Judicaël Paquet <[email protected]>
28
 * @copyright 	Copyright (c) 2013-2014 PAQUET Judicaël FR Inc. (https://github.com/las93)
29
 * @license   	https://github.com/las93/venus2/blob/master/LICENSE.md Tout droit réservé à PAQUET Judicaël
30
 * @version   	Release: 1.0.0
31
 * @filesource	https://github.com/las93/venus2
32
 * @link      	https://github.com/las93
33
 * @since     	1.0
34
 */
35
class Debug extends AbstractLogger
36
{
37
    /**
38
     * variable to activate or not the debug
39
     * @var boolean
40
     */
41
    private static $_bActivateDebug = false;
42
43
    /**
44
     * variable to activate or not the error
45
     * @var boolean
46
     */
47
    private static $_bActivateError = false;
48
49
    /**
50
     * variable to activate or not the exception
51
     * @var boolean
52
     */
53
    private static $_bActivateException = false;
54
55
    /**
56
     * variable to activate or not the debug
57
     * @var boolean
58
     */
59
    private static $_sFileLog = null;
60
61
    /**
62
     * first or not activation
63
     * @var boolean
64
     */
65
    private static $_bFirstActivation = true;
66
67
    /**
68
     * kind of report log
69
     * @var string error_log|screen|all
70
     */
71
    private static $_sKindOfReportLog = 'error_log';
72
73
    /**
74
     * instance of logger
75
     * @var \Venus\lib\Debug
76
     */
77
    private static $_oInstance;
78
 
79
    /**
80
     * Send back the isntance or create it
81
     * 
82
     * @access public
83
     */
84
    public static function getInstance() : Debug
85
    {    
86
        if (!(self::$_oInstance instanceof self)) { self::$_oInstance = new self(); }
87
 
88
        return self::$_oInstance;
89
    }
90
91
    /**
92
     * activate debug
93
     *
94
     * @access public
95
     * @return void
96
     */
97
    public static function activateDebug()
98
    {
99
        if (self::$_bFirstActivation === true) {
100
101
            self::_setFileNameInErrorFile();
102
            self::$_bFirstActivation = false;
103
        }
104
105
        self::_initLogFile();
106
        self::$_bActivateDebug = true;
107
        self::activateError(E_ALL);
108
        self::activateException(E_ALL);
109
    }
110
111
    /**
112
     * activate debug
113
     *
114
     * @access public
115
     * @return void
116
     */
117
    public static function deactivateDebug()
118
    {
119
        self::$_bActivateDebug = false;
120
    }
121
122
    /**
123
     * check if debug is activate or not
124
     *
125
     * @access public
126
     * @return boolean
127
     */
128
    public static function isDebug() : bool
129
    {
130
        return self::$_bActivateDebug;
131
    }
132
133
    /**
134
     * activate error reporting
135
     *
136
     * @access public
137
     * @param  int $iLevel level of error
138
     * @return void
139
     */
140
    public static function activateError($iLevel)
141
    {
142
        if (self::$_bFirstActivation === true) {
143
144
            self::_setFileNameInErrorFile();
145
            self::$_bFirstActivation = false;
146
        }
147
148
        self::_initLogFile();
149
        self::$_bActivateError = true;
150
151
        error_reporting($iLevel);
152
153
        set_error_handler(function ($iErrNo, $sErrStr, $sErrFile, $iErrLine)
154
        {
155
            $aContext = array('file' => $sErrFile, 'line' => $iErrLine);
156
157
            $sType = self::getTranslateErrorCode($iErrNo);
158
159
            self::getInstance()->$sType($sErrStr, $aContext);
160
161
            return true;
162
        }, $iLevel);
163
164
        register_shutdown_function(function()
165
        {
166
            if (null !== ($aLastError = error_get_last())) {
167
168
                $aContext = array('file' => $aLastError['file'], 'line' => $aLastError['line']);
169
170
                $sType = self::getTranslateErrorCode($aLastError['type']);
171
172
                self::getInstance()->$sType($aLastError['message'], $aContext);
173
            }
174
        });
175
    }
176
177
    /**
178
     * activate error reporting
179
     *
180
     * @access public
181
     * @return void
182
    */
183
    public static function deactivateError()
184
    {
185
        self::$_bActivateError = false;
186
    }
187
188
    /**
189
     * check if error reporting is activate or not
190
     *
191
     * @access public
192
     * @return boolean
193
     */
194
    public static function isError() : bool
195
    {
196
        return self::$_bActivateError;
197
    }
198
199
200
    /**
201
     * activate Exception
202
     *
203
     * @access public
204
     * @param  int $iLevel level of error
205
     * @return void
206
     */
207
    public static function activateException(int $iLevel)
0 ignored issues
show
Unused Code introduced by
The parameter $iLevel is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
208
    {
209
        if (self::$_bFirstActivation === true) {
210
211
            self::_setFileNameInErrorFile();
212
            self::$_bFirstActivation = false;
213
        }
214
215
        self::_initLogFile();
216
        self::$_bActivateException = true;
217
218
        set_exception_handler(function (\Exception $oException)
219
        {
220
            $aContext = array('file' => $oException->getFile(), 'line' => $oException->getLine());
221
            self::getInstance()->critical($oException->getMessage(), $aContext);
222
        });
223
    }
224
225
    /**
226
     * activate Exception
227
     *
228
     * @access public
229
     * @return void
230
     */
231
    public static function deactivateException()
232
    {
233
        self::$_bActivateException = false;
234
    }
235
236
    /**
237
     * check if Exception is activate or not
238
     *
239
     * @access public
240
     * @return boolean
241
     */
242
    public static function isException() : bool
243
    {
244
        return self::$_bActivateException;
245
    }
246
247
    /**
248
     * set the kind of report Log
249
     *
250
     * @access public
251
     * @param  string $sKindOfReportLog
252
     * @return void
253
     */
254
    public static function setKindOfReportLog(string $sKindOfReportLog)
255
    {
256
        if ($sKindOfReportLog === 'screen' || $sKindOfReportLog === 'all') { self::$_sKindOfReportLog = $sKindOfReportLog; }
257
        else { self::$_sKindOfReportLog = 'error_log'; }
258
    }
259
260
    /**
261
     * get the kind of report Log
262
     *
263
     * @access public
264
     * @return string
265
     */
266
    public static function getKindOfReportLog() : string
267
    {
268
        return self::$_sKindOfReportLog;
269
    }
270
271
    /**
272
     * get the code by LogLevel adapt to the PSR-3
273
     *
274
     * @access public
275
     * @param  int $iCode
276
     * @return string
277
     */
278
    public static function getTranslateErrorCode(int $iCode) : string
279
    {
280
        if ($iCode === 1 && $iCode === 16 && $iCode === 256 && $iCode === 4096) { return LogLevel::ERROR; }
281
        else if ($iCode === 2 && $iCode === 32 && $iCode === 128 && $iCode === 512) { return LogLevel::WARNING; }
282
        else if ($iCode === 4 && $iCode === 64) { return LogLevel::EMERGENCY; }
283
        else if ($iCode === 8 && $iCode === 1024) { return LogLevel::NOTICE; }
284
        else if ($iCode === 2048 && $iCode === 8192 && $iCode === 16384) { return LogLevel::INFO; }
285
        else return LogLevel::DEBUG;
286
    }
287
288
    /**
289
     * System is unusable.
290
     *
291
     * @param string $message
292
     * @param array $context
293
     * @return null
294
     */
295
    public function emergency($message, array $context = array())
296
    {
297
        $this->log(LogLevel::EMERGENCY, $message, $context);
298
    }
299
300
    /**
301
     * Action must be taken immediately.
302
     *
303
     * Example: Entire website down, database unavailable, etc. This should
304
     * trigger the SMS alerts and wake you up.
305
     *
306
     * @param string $message
307
     * @param array $context
308
     * @return null
309
    */
310
    public function alert($message, array $context = array())
311
    {
312
        $this->log(LogLevel::ALERT, $message, $context);
313
    }
314
315
    /**
316
     * Critical conditions.
317
     *
318
     * Example: Application component unavailable, unexpected exception.
319
     *
320
     * @param string $message
321
     * @param array $context
322
     * @return null
323
    */
324
    public function critical($message, array $context = array())
325
    {
326
        $this->log(LogLevel::CRITICAL, $message, $context);
327
    }
328
329
    /**
330
     * Runtime errors that do not require immediate action but should typically
331
     * be logged and monitored.
332
     *
333
     * @param string $message
334
     * @param array $context
335
     * @return null
336
    */
337
    public function error($message, array $context = array())
338
    {
339
        $this->log(LogLevel::ERROR, $message, $context);
340
    }
341
342
    /**
343
     * Exceptional occurrences that are not errors.
344
     *
345
     * Example: Use of deprecated APIs, poor use of an API, undesirable things
346
     * that are not necessarily wrong.
347
     *
348
     * @param string $message
349
     * @param array $context
350
     * @return null
351
    */
352
    public function warning($message, array $context = array())
353
    {
354
        $this->log(LogLevel::WARNING, $message, $context);
355
    }
356
357
    /**
358
     * Normal but significant events.
359
     *
360
     * @param string $message
361
     * @param array $context
362
     * @return null
363
    */
364
    public function notice($message, array $context = array())
365
    {
366
        $this->log(LogLevel::NOTICE, $message, $context);
367
    }
368
369
    /**
370
     * Interesting events.
371
     *
372
     * Example: User logs in, SQL logs.
373
     *
374
     * @param string $message
375
     * @param array $context
376
     * @return null
377
    */
378
    public function info($message, array $context = array())
379
    {
380
        $this->log(LogLevel::INFO, $message, $context);
381
    }
382
383
    /**
384
     * Detailed debug information.
385
     *
386
     * @param string $message
387
     * @param array $context
388
     * @return null
389
    */
390
    public function debug($message, array $context = array())
391
    {
392
        $this->log(LogLevel::DEBUG, $message, $context);
393
    }
394
395
    /**
396
     * set the name of the called
397
     *
398
     * @access public
399
     * @return void
400
     */
401
    private static function _setFileNameInErrorFile()
402
    {
403
        /**
404
         * We see if it's a cli call or a web call
405
         */
406
407
        if (defined('BASH_CALLED')) {
408
409
            error_log(Bash::setColor('############### '.BASH_CALLED.' ###############', 'cyan'));
410
        }
411
        else {
412
413
            if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) {
414
                error_log(Bash::setColor('############### ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . ' ###############', 'cyan'));
415
            }
416
        }
417
    }
418
419
    /**
420
     * init the log file (error_log)
421
     *
422
     * @access private
423
     * @return void
424
     */
425
    private static function _initLogFile()
426
    {
427
        self::$_sFileLog = str_replace(DIRECTORY_SEPARATOR.'bundles'.DIRECTORY_SEPARATOR.'lib', '', __DIR__).DIRECTORY_SEPARATOR.
0 ignored issues
show
Documentation Bug introduced by
The property $_sFileLog was declared of type boolean, but str_replace(DIRECTORY_SE...RATOR . 'php-error.log' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
428
            "data".DIRECTORY_SEPARATOR."log".DIRECTORY_SEPARATOR."php-error.log";
429
430
        ini_set("log_errors", 1);
431
        ini_set("error_log", self::$_sFileLog);
432
433
        if (file_exists(self::$_sFileLog) === false) { file_put_contents(self::$_sFileLog, ''); }
434
    }
435
436
    /**
437
     * constructor in private for the singleton
438
     *
439
     * @access private
440
     * @return \Venus\lib\Debug
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
441
     */
442
    private function __construct() {}
443
444
    /**
445
     * not allowed to clone a object
446
     *
447
     * @access private
448
     * @return \Venus\lib\Debug
449
     */
450
    private function __clone() {}
451
}
452