Passed
Branch master (776013)
by payever
03:51
created

FileLogger::getTimestamp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * PHP version 5.4 and 7
4
 *
5
 * @package   Payever\Core
6
 * @author    Hennadii.Shymanskyi <[email protected]>
7
 * @copyright 2017-2019 payever GmbH
8
 * @license   MIT <https://opensource.org/licenses/MIT>
9
 */
10
11
namespace Payever\ExternalIntegration\Core\Logger;
12
13
use Psr\Log\AbstractLogger;
14
use Psr\Log\LogLevel;
15
16
/**
17
 * Class FileLogger
18
 *
19
 * Simple PSR-3 compatible Logger class.
20
 * Recommended for use when there's no advanced logger (e.g. Monolog) provided in user's system.
21
 *
22
 * @package   Payever\Core
23
 * @author    Hennadii.Shymanskyi <[email protected]>
24
 * @copyright 2017-2019 payever GmbH
25
 * @license   MIT <https://opensource.org/licenses/MIT>
26
 */
27
class FileLogger extends AbstractLogger
28
{
29
    /** @var string */
30
    protected $logFilePath;
31
32
    /** @var resource  */
33
    protected $logFileHandle;
34
35
    /** @var string */
36
    protected $channelName;
37
38
    /** @var int */
39
    protected $logLevelInt;
40
41
    /** @var int */
42
    protected $bufferSize;
43
44
    /** @var array */
45
    protected $buffer = array();
46
47
    /** @var bool */
48
    protected $shutdownRegistered = false;
49
50
    /**
51
     * Log Levels
52
     * @var array
53
     */
54
    protected $logLevels = array(
55
        LogLevel::EMERGENCY => 0,
56
        LogLevel::ALERT     => 1,
57
        LogLevel::CRITICAL  => 2,
58
        LogLevel::ERROR     => 3,
59
        LogLevel::WARNING   => 4,
60
        LogLevel::NOTICE    => 5,
61
        LogLevel::INFO      => 6,
62
        LogLevel::DEBUG     => 7
63
    );
64
65
    /**
66
     * FileLogger constructor.
67
     *
68
     * @param string $logFilePath
69
     * @param string $logLevel
70
     * @param string $channelName
71
     * @param int    $bufferSize
72
     */
73
    public function __construct($logFilePath, $logLevel, $channelName = 'payever', $bufferSize = 50)
74
    {
75
        if (!isset($this->logLevels[$logLevel])) {
76
            throw new \InvalidArgumentException(
77
                sprintf("Log level must be one of Psr\Log\LogLevel constants, %s given", $logLevel)
78
            );
79
        }
80
81
        if (!is_readable(dirname($logFilePath))) {
82
            throw new \UnexpectedValueException(
83
                sprintf("The directory of log file is not readable: %s", $logFilePath)
84
            );
85
        }
86
87
        $bufferSize = (int) $bufferSize;
88
89
        if ($bufferSize < 1) {
90
            throw new \InvalidArgumentException(sprintf('Buffer size must be > 0, %d given', $bufferSize));
91
        }
92
93
        if (!file_exists($logFilePath)) {
94
            touch($logFilePath);
95
        }
96
97
        if (!($this->logFileHandle = fopen($logFilePath, 'a'))) {
0 ignored issues
show
Documentation Bug introduced by
It seems like fopen($logFilePath, 'a') can also be of type false. However, the property $logFileHandle is declared as type resource. 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...
98
            throw new \UnexpectedValueException(
99
                sprintf("Can't open file for writing: %s", $logFilePath)
100
            );
101
        }
102
103
        $this->logFilePath = $logFilePath;
104
        $this->logLevelInt = $this->logLevels[$logLevel];
105
        $this->channelName = $channelName;
106
        $this->bufferSize = $bufferSize;
107
    }
108
109
    /**
110
     * @param string $level
111
     * @param string $message
112
     * @param array  $context
113
     */
114
    public function log($level, $message, array $context = array())
115
    {
116
        if ($this->logLevels[$level] > $this->logLevelInt) {
117
            return;
118
        }
119
120
        if (!$this->shutdownRegistered) {
121
            $this->shutdownRegistered = true;
122
            /** __destruct doesn't get called on fatal errors */
123
            register_shutdown_function(array($this, 'close'));
124
        }
125
126
        $this->buffer[] = $this->formatMessage($level, $message, $context);
127
128
        if (count($this->buffer) === $this->bufferSize) {
129
            $this->flush();
130
        }
131
    }
132
133
    /**
134
     * register_shutdown_function handler
135
     */
136
    public function close()
137
    {
138
        $this->flush();
139
140
        fclose($this->logFileHandle);
141
    }
142
143
    /**
144
     * Actually writes collected messages into file
145
     */
146
    protected function flush()
147
    {
148
        foreach ($this->buffer as $message) {
149
            fwrite($this->logFileHandle, $message);
150
        }
151
152
        $this->buffer = array();
153
    }
154
155
    /**
156
     * @param string $level
157
     * @param string $message
158
     * @param array  $context
159
     *
160
     * @return string
161
     */
162
    protected function formatMessage($level, $message, array $context)
163
    {
164
        $level = strtoupper($level);
165
166
        return "[{$this->getTimestamp()}] {$this->channelName}.{$level} {$message}\t{$this->serializeContext($context)}\n";
167
    }
168
169
    /**
170
     * @param array $context
171
     *
172
     * @return string
173
     */
174
    protected function serializeContext(array $context)
175
    {
176
        return json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
177
    }
178
179
    /**
180
     * @return string
181
     */
182
    protected function getTimestamp()
183
    {
184
        return date('Y-m-d H:i:s.' . microtime(true));
185
    }
186
}
187