Completed
Pull Request — master (#2)
by Mathieu
05:06 queued 01:16
created

Logger   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 14.29%

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 69
ccs 3
cts 21
cp 0.1429
rs 10
c 0
b 0
f 0
wmc 12

7 Methods

Rating   Name   Duplication   Size   Complexity  
A debug() 0 3 1
A info() 0 3 1
A warn() 0 3 1
A fatal() 0 3 1
A error() 0 3 1
A log() 0 14 6
A __construct() 0 3 1
1
<?php declare(strict_types=1);
2
namespace Suricate;
3
4
/**
5
 * Logger extension for Suricate
6
 *
7
 * @package Suricate\Cache
8
 * @author  Mathieu LESNIAK <[email protected]>
9
 *
10
 * @property string $logfile
11
 * @property boolean $enabled
12
 * @property int $level
13
 * @property boolean $timestamp
14
 */
15
class Logger extends Service
16
{
17
    const LOGLEVEL_FATAL    = 0;
18
    const LOGLEVEL_ERROR    = 1;
19
    const LOGLEVEL_WARN     = 2;
20
    const LOGLEVEL_INFO     = 3;
21
    const LOGLEVEL_DEBUG    = 4;
22
23
    protected $parametersList = [
24
        'logfile',
25
        'enabled',
26
        'level',
27
        'timestamp'
28
    ];
29
30
    private $resource;
31
32
    protected $levels = [
33
        self::LOGLEVEL_FATAL    => 'FATAL',
34
        self::LOGLEVEL_ERROR    => 'ERROR',
35
        self::LOGLEVEL_WARN     => 'WARN',
36
        self::LOGLEVEL_INFO     => 'INFO',
37
        self::LOGLEVEL_DEBUG    => 'DEBUG'
38
    ];
39
40 8
    public function __construct()
41
    {
42 8
        parent::__construct();
43 8
    }
44
45
    public function log($message, $level)
46
    {
47
        if ($this->resource == null && $this->logfile !== null) {
48
            $this->resource = fopen($this->logfile, 'a+');
49
        }
50
51
        if ($level <= $this->level && $this->enabled) {
52
            if ($this->timestamp) {
53
                $message = "[" . date('M d H:i:s') . "] " . $message;
54
            }
55
            fputs($this->resource, '[' . $this->levels[$level] . '] '. (string) $message . PHP_EOL);
56
        }
57
58
        return $this;
59
    }
60
61
    public function fatal($message)
62
    {
63
        return $this->log($message, self::LOGLEVEL_FATAL);
64
    }
65
66
    public function error($message)
67
    {
68
        return $this->log($message, self::LOGLEVEL_ERROR);
69
    }
70
71
    public function warn($message)
72
    {
73
        return $this->log($message, self::LOGLEVEL_WARN);
74
    }
75
76
    public function info($message)
77
    {
78
        return $this->log($message, self::LOGLEVEL_INFO);
79
    }
80
81
    public function debug($message)
82
    {
83
        return $this->log($message, self::LOGLEVEL_DEBUG);
84
    }
85
}
86