AbstractLogger::getLevelCode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
ccs 7
cts 7
cp 1
rs 9.9
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * This file is part of the Apix Project.
5
 *
6
 * (c) Franck Cassedanne <franck at ouarz.net>
7
 *
8
 * @license http://opensource.org/licenses/BSD-3-Clause  New BSD License
9
 */
10
11
namespace Apix\Log\Logger;
12
13
use Psr\Log\AbstractLogger as PsrAbstractLogger;
14
use Psr\Log\InvalidArgumentException;
15
use Apix\Log\LogEntry;
16
use Apix\Log\LogFormatter;
17
18
/**
19
 * Abstratc class.
20
 *
21
 * @author Franck Cassedanne <franck at ouarz.net>
22
 */
23
abstract class AbstractLogger extends PsrAbstractLogger
24
{
25
    /**
26
     * The PSR-3 logging levels.
27
     * @var array
28
     */
29
    protected static $levels = array(
30
        'emergency',
31
        'alert',
32
        'critical',
33
        'error',
34
        'warning',
35
        'notice',
36
        'info',
37
        'debug'
38
    );
39
40
    /**
41
     * Holds the minimal level index supported by this logger.
42
     * @var int
43
     */
44
    protected $min_level = 7;
45
46
    /**
47
     * Whether this logger will cascade downstream.
48
     * @var bool
49
     */
50
    protected $cascading = true;
51
52
    /**
53
     * Whether this logger will be deferred (push the logs at destruct time).
54
     * @var bool
55
     */
56
    protected $deferred = false;
57
58
    /**
59
     * Holds the deferred logs.
60
     * @var array
61
     */
62
    protected $deferred_logs = array();
63
64
    /**
65
     * Holds the log formatter.
66
     * @var LogFormatter|null
67
     */
68
    protected $log_formatter = null;
69
70
    /**
71
     * Holds the logger options (useful to set default options).
72
     * @var array
73
     */
74
    protected $options = array();
75
76
    /**
77
     * Gets the named level code.
78
     *
79
     * @param  string $level_name The name of a PSR-3 level.
80
     * @return int
81
     * @throws InvalidArgumentException
82
     */
83 740
    public static function getLevelCode($level_name)
84
    {
85 740
        $level_code = array_search($level_name, static::$levels);
86 740
        if (false === $level_code) {
87 20
            throw new InvalidArgumentException(
88 20
                sprintf('Invalid log level "%s"', $level_name)
89 5
            );
90
        }
91
92 720
        return $level_code;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98 728
    public function log($level, $message, array $context = array())
99
    {
100 728
        $entry = new LogEntry($level, $message, $context);
101 712
        $entry->setFormatter($this->getLogFormatter());
0 ignored issues
show
Bug introduced by
It seems like $this->getLogFormatter() can be null; however, setFormatter() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
102 712
        $this->process($entry);
103 177
    }
104
105
    /**
106
     * Processes the given log.
107
     *
108
     * @param  LogEntry $log The log entry to process.
109
     * @return bool Wether this logger cascade downstream.
110
     */
111 700
    public function process(LogEntry $log)
112
    {
113 700
        if ($this->deferred) {
114 12
            $this->deferred_logs[] = $log;
115 3
        } else {
116 700
            $this->write($log);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Apix\Log\Logger\AbstractLogger as the method write() does only exist in the following sub-classes of Apix\Log\Logger\AbstractLogger: Apix\Log\Logger\ErrorLog, Apix\Log\Logger\File, Apix\Log\Logger\Mail, Apix\Log\Logger\Nil, Apix\Log\Logger\Runtime, Apix\Log\Logger\Sapi, Apix\Log\Logger\Stream. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
117
        }
118
119 696
        return $this->cascading;
120
    }
121
122
    /**
123
     * Checks whether the given level code is handled by this logger.
124
     *
125
     * @param  int $level_code
126
     * @return bool
127
     */
128 36
    public function isHandling($level_code)
129
    {
130 36
        return $this->min_level >= $level_code;
131
    }
132
133
    /**
134
     * Sets the minimal level at which this logger will be triggered.
135
     *
136
     * @param  string    $name
137
     * @param  bool|true $cascading Should the logs continue pass that level.
138
     * @return self
139
     */
140 36
    public function setMinLevel($name, $cascading = true)
141
    {
142 36
        $this->min_level = self::getLevelCode(strtolower($name));
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getLevelCode(strtolower($name)) can also be of type string. However, the property $min_level is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
143 36
        $this->cascading = (boolean) $cascading;
144
145 36
        return $this;
146
    }
147
148
    /**
149
     * Alias to self::setMinLevel().
150
     *
151
     * @param  string    $name
152
     * @param  bool|false $blocking Should the logs continue pass that level.
153
     * @return self
154
     */
155 4
    public function interceptAt($name, $blocking = false)
156
    {
157 4
        return $this->setMinLevel($name, !$blocking);
158
    }
159
160
    /**
161
     * Returns the minimal level at which this logger will be triggered.
162
     *
163
     * @return int
164
     */
165 28
    public function getMinLevel()
166
    {
167 28
        return $this->min_level;
168
    }
169
170
    /**
171
     * Sets wether to enable/disable cascading.
172
     *
173
     * @param  bool $bool
174
     * @return self
175
     */
176 12
    public function setCascading($bool)
177
    {
178 12
        $this->cascading = (boolean) $bool;
179
180 12
        return $this;
181
    }
182
183
    /**
184
     * Sets wether to enable/disable log deferring.
185
     *
186
     * @param  bool $bool
187
     * @return self
188
     */
189 16
    public function setDeferred($bool)
190
    {
191 16
        $this->deferred = (boolean) $bool;
192
193 16
        return $this;
194
    }
195
196
    /**
197
     * Returns all the deferred logs.
198
     *
199
     * @return array
200
     */
201 8
    public function getDeferredLogs()
202
    {
203 8
        return $this->deferred_logs;
204
    }
205
206
    /**
207
     * Process any accumulated deferred log if there are any.
208
     */
209 796
    final public function __destruct()
210
    {
211 796
        if ($this->deferred && !empty($this->deferred_logs)) {
212
213 8
            $messages = array_map(
214 8
                function ($log) {
215 8
                    return (string) $log;
216 8
                },
217 8
                $this->deferred_logs
218 2
            );
219
            
220 8
            $formatter = $this->getLogFormatter();
221
            
222 8
            $messages = implode($formatter->separator, $messages);
223
224 8
            $entries = new LogEntry('notice', $messages);
225 8
            $entries->setFormatter( $formatter );
226 8
            $this->write($entries);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Apix\Log\Logger\AbstractLogger as the method write() does only exist in the following sub-classes of Apix\Log\Logger\AbstractLogger: Apix\Log\Logger\ErrorLog, Apix\Log\Logger\File, Apix\Log\Logger\Mail, Apix\Log\Logger\Nil, Apix\Log\Logger\Runtime, Apix\Log\Logger\Sapi, Apix\Log\Logger\Stream. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
227
228
            // return $this->formatter->format($this);
229 2
        }
230
231 796
        $this->close();
232 199
    }
233
234
    /**
235
     * Closes the logger ~ acts as the last resort garbage collector.
236
     *
237
     * This method is called last at __destruct() time.
238
     */
239 154
    public function close()
240
    {
241
        // empty
242 154
    }
243
244
    /**
245
     * Sets a log formatter.
246
     *
247
     * @param LogFormatter $formatter
248
     */
249 724
    public function setLogFormatter(LogFormatter $formatter)
250
    {
251 724
        $this->log_formatter = $formatter;
252 181
    }
253
254
    /**
255
     * Returns the current log formatter.
256
     *
257
     * @return LogFormatter
258
     */
259 724
    public function getLogFormatter()
260
    {    
261 724
        if(!$this->log_formatter) {
262 716
            $this->setLogFormatter(new LogFormatter);
263 179
        }
264
265 724
        return $this->log_formatter;
266
    }
267
268
    /**
269
     * Sets and merges the options for this logger, overriding any default.
270
     *
271
     * @param array|null $options
272
     */
273
    public function setOptions(array $options=null)
274
    {
275
        if (null !== $options) {
276
            $this->options = $options+$this->options;
277
        }
278
    }
279
280
}