Test Setup Failed
Push — master ( eaed60...415c39 )
by Fran
04:34
created

Logger   B

Complexity

Total Complexity 41

Size/Duplication

Total Lines 258
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 10

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 258
ccs 88
cts 88
cp 1
rs 8.2769
c 0
b 0
f 0
wmc 41
lcom 2
cbo 10

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A __destruct() 0 4 1
A defaultLog() 0 4 1
A infoLog() 0 4 1
A debugLog() 0 4 2
A errorLog() 0 4 1
A warningLog() 0 4 1
A addPushLogger() 0 17 4
B setup() 0 15 6
A setLoggerName() 0 7 2
A cleanLoggerName() 0 7 1
A createLoggerPath() 0 8 1
C log() 0 27 8
A addDefaultStreamHandler() 0 12 2
B addMinimalContext() 0 9 7
A getLogUid() 0 3 1
A getUid() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Logger often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Logger, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 19 and the first side effect is on line 18.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
namespace PSFS\base;
4
5
use Monolog\Formatter\LineFormatter;
6
use Monolog\Handler\FirePHPHandler;
7
use Monolog\Handler\StreamHandler;
8
use Monolog\Logger as Monolog;
9
use Monolog\Processor\MemoryUsageProcessor;
10
use Monolog\Processor\UidProcessor;
11
use PSFS\base\config\Config;
12
use PSFS\base\types\helpers\GeneratorHelper;
13
use PSFS\base\types\helpers\Inspector;
14
use PSFS\base\types\traits\SingletonTrait;
15
16
17
if (!defined('LOG_DIR')) {
18
    GeneratorHelper::createDir(BASE_DIR . DIRECTORY_SEPARATOR . 'logs');
19
    define('LOG_DIR', BASE_DIR . DIRECTORY_SEPARATOR . 'logs');
20
}
21
22
/**
23
 * Class Logger
24
 * @package PSFS\base
25
 * Servicio de log
26
 */
27
class Logger
28
{
29
    const DEFAULT_NAMESPACE = 'PSFS';
30
    use SingletonTrait;
31
    /**
32
     * @var \Monolog\Logger
33
     */
34
    protected $logger;
35
    /**
36
     * @var resource
37
     */
38
    private $stream;
39
    /**
40
     * @var UidProcessor
41
     */
42
    private $uuid;
43
    /**
44
     * @var string
45
     */
46
    protected $log_level;
47
48 2
    /**
49
     * Logger constructor.
50 2
     * @throws exception\GeneratorException
51 2
     */
52 2
    public function __construct()
53 2
    {
54 2
        $config = Config::getInstance();
55 2
        $args = func_get_args();
56 2
        list($logger, $debug, $path) = $this->setup($config, $args);
57
        $this->stream = fopen($path . DIRECTORY_SEPARATOR . date('Ymd') . '.log', 'a+');
58 1
        $this->addPushLogger($logger, $debug, $config);
59
        $this->log_level = Config::getParam('log.level', 'info');
60 1
    }
61 1
62
    public function __destruct()
63
    {
64
        fclose($this->stream);
65
    }
66
67
    /**
68 1
     * @param string $msg
69
     * @param array $context
70 1
     * @return bool
71
     */
72
    public function defaultLog($msg = '', array $context = [])
73
    {
74
        return $this->logger->addNotice($msg, $this->addMinimalContext($context));
75
    }
76
77
    /**
78
     * @param string $msg
79 4
     * @param array $context
80
     *
81 4
     * @return bool
82
     */
83
    public function infoLog($msg = '', array $context = [])
84
    {
85
        return $this->logger->addInfo($msg, $this->addMinimalContext($context));
86
    }
87
88
    /**
89
     * @param string $msg
90 22
     * @param array $context
91
     *
92 22
     * @return bool
93
     */
94
    public function debugLog($msg = '', array $context = [])
95
    {
96
        return ($this->log_level === 'debug') ? $this->logger->addDebug($msg, $this->addMinimalContext($context)) : null;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
97
    }
98
99
    /**
100
     * @param $msg
101 4
     * @param array $context
102
     *
103 4
     * @return bool
104
     */
105
    public function errorLog($msg, array $context = [])
106
    {
107
        return $this->logger->addError($msg, $this->addMinimalContext($context));
108
    }
109
110
    /**
111 3
     * @param $msg
112
     * @param array $context
113 3
     * @return bool
114
     */
115
    public function warningLog($msg, array $context = [])
116
    {
117
        return $this->logger->addWarning($msg, $this->addMinimalContext($context));
118
    }
119
120
    /**
121 2
     * @param string $logger
122
     * @param boolean $debug
123 2
     * @param Config $config
124 2
     * @throws \Exception
125 2
     */
126 1
    private function addPushLogger($logger, $debug, Config $config)
127 1
    {
128 1
        $this->logger = new Monolog(strtoupper($logger));
129
        $this->logger->pushHandler($this->addDefaultStreamHandler($debug));
130 1
        if ($debug) {
131 1
            $phpFireLog = $config->get('logger.phpFire');
132 1
            if (!empty($phpFireLog)) {
133
                $this->logger->pushHandler(new FirePHPHandler());
134
            }
135 2
            $memoryLog = $config->get('logger.memory');
136 2
            if (!empty($memoryLog)) {
137
                $this->logger->pushProcessor(new MemoryUsageProcessor());
138
            }
139
        }
140
        $this->uuid = new UidProcessor();
141
        $this->logger->pushProcessor($this->uuid);
142
    }
143
144 2
    /**
145
     * @param Config $config
146 2
     * @param array $args
147 2
     * @return array
148 2
     * @throws exception\GeneratorException
149 2
     */
150 1
    private function setup(Config $config, array $args = array())
151
    {
152 2
        $debug = $config->getDebugMode();
153 1
        $namespace = self::DEFAULT_NAMESPACE;
154
        if (0 !== count($args)) {
155
            if (array_key_exists(0, $args) && array_key_exists(0, $args[0])) {
156 2
                $namespace = $args[0][0];
157 2
            }
158
            if (array_key_exists(0, $args) && array_key_exists(1, $args[0])) {
159
                $debug = $args[0][1];
160
            }
161
        }
162
        $path = $this->createLoggerPath($config);
163
        return array($this->cleanLoggerName($namespace), $debug, $path);
164
    }
165 2
166
    /**
167 2
     * @param Config $config
168 2
     *
169
     * @return string
170 2
     */
171
    private function setLoggerName(Config $config)
172
    {
173
        $logger = $config->get('platform_name') ?: self::DEFAULT_NAMESPACE;
174
        $logger = $this->cleanLoggerName($logger);
175
176
        return $logger;
177
    }
178 2
179
    /**
180 2
     * @param $logger
181 2
     *
182
     * @return mixed
183 2
     */
184
    private function cleanLoggerName($logger)
185
    {
186
        $logger = str_replace(' ', '', $logger);
187
        $logger = preg_replace('/\\\/', ".", $logger);
188
189
        return $logger;
190
    }
191 2
192
    /**
193 2
     * @param Config $config
194 2
     * @return string
195 2
     * @throws exception\GeneratorException
196
     */
197 2
    private function createLoggerPath(Config $config)
198
    {
199
        $logger = $this->setLoggerName($config);
200
        $path = LOG_DIR . DIRECTORY_SEPARATOR . $logger . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
201
        GeneratorHelper::createDir($path);
202
203
        return $path;
204
    }
205 23
206
    /**
207 23
     * @param string $msg
208 23
     * @param int $type
209
     * @param array $context
0 ignored issues
show
Documentation introduced by
Should the type for parameter $context not be null|array? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
210 23
     */
211 1
    public static function log($msg, $type = LOG_DEBUG, array $context = null)
212
    {
213
        if(null === $context) {
214 23
            $context = [];
215 22
        }
216 22
        if(Config::getParam('profiling.enable')) {
217 8
            Inspector::stats($msg);
218 3
        }
219 3
        switch ($type) {
220 7
            case LOG_DEBUG:
221 7
                self::getInstance()->debugLog($msg, $context);
222 4
                break;
223 4
            case LOG_WARNING:
224 4
                self::getInstance()->warningLog($msg, $context);
225 4
                break;
226 4
            case LOG_CRIT:
227
            case LOG_ERR:
228 1
                self::getInstance()->errorLog($msg, $context);
229 1
                break;
230
            case LOG_INFO:
231 23
                self::getInstance()->infoLog($msg, $context);
232
                break;
233
            default:
234
                self::getInstance()->defaultLog($msg, $context);
235
                break;
236
        }
237 2
    }
238
239
    /**
240 2
     * @param bool $debug
241
     * @return StreamHandler
242 2
     * @throws \Exception
243
     */
244 2
    private function addDefaultStreamHandler($debug = false)
245 2
    {
246 2
        // the default date format is "Y-m-d H:i:s"
247 2
        $dateFormat = 'Y-m-d H:i:s.u';
248
        // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
249
        $output = "[%datetime%] [%channel%:%level_name%]\t%message%\t%context%\t%extra%\n";
250
        // finally, create a formatter
251
        $formatter = new LineFormatter($output, $dateFormat);
252
        $stream = new StreamHandler($this->stream, $debug ? Monolog::DEBUG : Monolog::WARNING);
253
        $stream->setFormatter($formatter);
254 8
        return $stream;
255
    }
256 8
257 8
    /**
258 8
     * @param array $context
259
     * @return array
260
     */
261
    private function addMinimalContext(array $context = [])
0 ignored issues
show
Coding Style introduced by
addMinimalContext uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
262
    {
263
        $context['uri'] = null !== $_SERVER && array_key_exists('REQUEST_URI', $_SERVER) ? $_SERVER['REQUEST_URI'] : 'Unknow';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
264
        $context['method'] = null !== $_SERVER && array_key_exists('REQUEST_METHOD', $_SERVER) ? $_SERVER['REQUEST_METHOD'] : 'Unknow';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
265
        if(null !== $_SERVER && array_key_exists('HTTP_X_PSFS_UID', $_SERVER)) {
266
            $context['uid'] = $_SERVER['HTTP_X_PSFS_UID'];
267
        }
268
        return $context;
269
    }
270
271
    /**
272
     * @return string
273
     */
274
    public function getLogUid() {
275
        return $this->uuid->getUid();
276
    }
277
278
    /**
279
     * @return string
280
     */
281
    public static function getUid() {
282
        return self::getInstance()->getLogUid();
283
    }
284
}
285