Completed
Push — feature/refactor-app-design ( b18d21...84977e )
by Avtandil
02:45
created

Logger::isUpdateLogActive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot;
12
13
use Longman\TelegramBot\Exception\TelegramLogException;
14
use Monolog\Formatter\LineFormatter;
15
use Monolog\Handler\StreamHandler;
16
use Monolog\Logger as MonologLogger;
17
18
class Logger
19
{
20
    /**
21
     * Monolog instance
22
     *
23
     * @var \Monolog\Logger
24
     */
25
    static protected $monolog;
26
27
    /**
28
     * Monolog instance for update
29
     *
30
     * @var \Monolog\Logger
31
     */
32
    static protected $monolog_update;
33
34
    /**
35
     * Path for error log
36
     *
37
     * @var string
38
     */
39
    static protected $error_log_path;
40
41
    /**
42
     * Path for debug log
43
     *
44
     * @var string
45
     */
46
    static protected $debug_log_path;
47
48
    /**
49
     * Path for update log
50
     *
51
     * @var string
52
     */
53
    static protected $update_log_path;
54
55
    /**
56
     * Temporary stream handle for debug log
57
     *
58
     * @var resource|null
59
     */
60
    static protected $debug_log_temp_stream_handle;
61
62
    /**
63
     * Initialize Monolog Logger instance, optionally passing an existing one
64
     *
65
     * @param \Monolog\Logger
66
     *
67
     * @return \Monolog\Logger
68
     */
69 3
    public static function initialize(MonologLogger $external_monolog = null)
70
    {
71 3
        if (self::$monolog === null) {
72 3
            if ($external_monolog !== null) {
73 1
                self::$monolog = $external_monolog;
74
75 1
                foreach (self::$monolog->getHandlers() as $handler) {
76 1
                    if (method_exists($handler, 'getLevel') && $handler->getLevel() === 400) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Monolog\Handler\HandlerInterface as the method getLevel() does only exist in the following implementations of said interface: Monolog\Handler\AbstractHandler, Monolog\Handler\AbstractProcessingHandler, Monolog\Handler\AbstractSyslogHandler, Monolog\Handler\AmqpHandler, Monolog\Handler\BrowserConsoleHandler, Monolog\Handler\BufferHandler, Monolog\Handler\ChromePHPHandler, Monolog\Handler\CouchDBHandler, Monolog\Handler\CubeHandler, Monolog\Handler\DeduplicationHandler, Monolog\Handler\DoctrineCouchDBHandler, Monolog\Handler\DynamoDbHandler, Monolog\Handler\ElasticSearchHandler, Monolog\Handler\ErrorLogHandler, Monolog\Handler\ExceptionTestHandler, Monolog\Handler\FilterHandler, Monolog\Handler\FingersCrossedHandler, Monolog\Handler\FirePHPHandler, Monolog\Handler\FleepHookHandler, Monolog\Handler\FlowdockHandler, Monolog\Handler\GelfHandler, Monolog\Handler\GroupHandler, Monolog\Handler\HipChatHandler, Monolog\Handler\IFTTTHandler, Monolog\Handler\LogEntriesHandler, Monolog\Handler\LogglyHandler, Monolog\Handler\MailHandler, Monolog\Handler\MandrillHandler, Monolog\Handler\MongoDBHandler, Monolog\Handler\NativeMailerHandler, Monolog\Handler\NewRelicHandler, Monolog\Handler\NullHandler, Monolog\Handler\PHPConsoleHandler, Monolog\Handler\PsrHandler, Monolog\Handler\PushoverHandler, Monolog\Handler\RavenHandler, Monolog\Handler\RedisHandler, Monolog\Handler\RollbarHandler, Monolog\Handler\RotatingFileHandler, Monolog\Handler\SamplingHandler, Monolog\Handler\SlackHandler, Monolog\Handler\SlackWebhookHandler, Monolog\Handler\SlackbotHandler, Monolog\Handler\SocketHandler, Monolog\Handler\StreamHandler, Monolog\Handler\StubNewRelicHandler, Monolog\Handler\StubNewR...HandlerWithoutExtension, Monolog\Handler\SwiftMailerHandler, Monolog\Handler\SyslogHandler, Monolog\Handler\SyslogUdpHandler, Monolog\Handler\TestChromePHPHandler, Monolog\Handler\TestFirePHPHandler, Monolog\Handler\TestHandler, Monolog\Handler\WhatFailureGroupHandler, Monolog\Handler\ZendMonitorHandler.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
77 1
                        self::$error_log_path = 'true';
78
                    }
79 1
                    if (method_exists($handler, 'getLevel') && $handler->getLevel() === 100) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Monolog\Handler\HandlerInterface as the method getLevel() does only exist in the following implementations of said interface: Monolog\Handler\AbstractHandler, Monolog\Handler\AbstractProcessingHandler, Monolog\Handler\AbstractSyslogHandler, Monolog\Handler\AmqpHandler, Monolog\Handler\BrowserConsoleHandler, Monolog\Handler\BufferHandler, Monolog\Handler\ChromePHPHandler, Monolog\Handler\CouchDBHandler, Monolog\Handler\CubeHandler, Monolog\Handler\DeduplicationHandler, Monolog\Handler\DoctrineCouchDBHandler, Monolog\Handler\DynamoDbHandler, Monolog\Handler\ElasticSearchHandler, Monolog\Handler\ErrorLogHandler, Monolog\Handler\ExceptionTestHandler, Monolog\Handler\FilterHandler, Monolog\Handler\FingersCrossedHandler, Monolog\Handler\FirePHPHandler, Monolog\Handler\FleepHookHandler, Monolog\Handler\FlowdockHandler, Monolog\Handler\GelfHandler, Monolog\Handler\GroupHandler, Monolog\Handler\HipChatHandler, Monolog\Handler\IFTTTHandler, Monolog\Handler\LogEntriesHandler, Monolog\Handler\LogglyHandler, Monolog\Handler\MailHandler, Monolog\Handler\MandrillHandler, Monolog\Handler\MongoDBHandler, Monolog\Handler\NativeMailerHandler, Monolog\Handler\NewRelicHandler, Monolog\Handler\NullHandler, Monolog\Handler\PHPConsoleHandler, Monolog\Handler\PsrHandler, Monolog\Handler\PushoverHandler, Monolog\Handler\RavenHandler, Monolog\Handler\RedisHandler, Monolog\Handler\RollbarHandler, Monolog\Handler\RotatingFileHandler, Monolog\Handler\SamplingHandler, Monolog\Handler\SlackHandler, Monolog\Handler\SlackWebhookHandler, Monolog\Handler\SlackbotHandler, Monolog\Handler\SocketHandler, Monolog\Handler\StreamHandler, Monolog\Handler\StubNewRelicHandler, Monolog\Handler\StubNewR...HandlerWithoutExtension, Monolog\Handler\SwiftMailerHandler, Monolog\Handler\SyslogHandler, Monolog\Handler\SyslogUdpHandler, Monolog\Handler\TestChromePHPHandler, Monolog\Handler\TestFirePHPHandler, Monolog\Handler\TestHandler, Monolog\Handler\WhatFailureGroupHandler, Monolog\Handler\ZendMonitorHandler.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
80 1
                        self::$debug_log_path = 'true';
81
                    }
82
                }
83
            } else {
84 2
                self::$monolog = new MonologLogger('bot_log');
85
            }
86
        }
87
88 3
        return self::$monolog;
89
    }
90
91
    /**
92
     * Initialize error log
93
     *
94
     * @param string $path
95
     *
96
     * @return \Monolog\Logger
97
     * @throws \Longman\TelegramBot\Exception\TelegramLogException
98
     * @throws \InvalidArgumentException
99
     * @throws \Exception
100
     */
101 2 View Code Duplication
    public static function initErrorLog($path)
102
    {
103 2
        if ($path === null || $path === '') {
104 1
            throw new TelegramLogException('Empty path for error log');
105
        }
106 1
        self::initialize();
107 1
        self::$error_log_path = $path;
108
109 1
        return self::$monolog->pushHandler(
110 1
            (new StreamHandler(self::$error_log_path, MonologLogger::ERROR))
111 1
                ->setFormatter(new LineFormatter(null, null, true))
112
        );
113
    }
114
115
    /**
116
     * Initialize debug log
117
     *
118
     * @param string $path
119
     *
120
     * @return \Monolog\Logger
121
     * @throws \Longman\TelegramBot\Exception\TelegramLogException
122
     * @throws \InvalidArgumentException
123
     * @throws \Exception
124
     */
125 2 View Code Duplication
    public static function initDebugLog($path)
126
    {
127 2
        if ($path === null || $path === '') {
128 1
            throw new TelegramLogException('Empty path for debug log');
129
        }
130 1
        self::initialize();
131 1
        self::$debug_log_path = $path;
132
133 1
        return self::$monolog->pushHandler(
134 1
            (new StreamHandler(self::$debug_log_path, MonologLogger::DEBUG))
135 1
                ->setFormatter(new LineFormatter(null, null, true))
136
        );
137
    }
138
139
    /**
140
     * Get the stream handle of the temporary debug output
141
     *
142
     * @return mixed The stream if debug is active, else false
143
     */
144
    public static function getDebugLogTempStream()
145
    {
146
        if (self::$debug_log_temp_stream_handle === null) {
147
            if (!self::isDebugLogActive()) {
148
                return false;
149
            }
150
            self::$debug_log_temp_stream_handle = fopen('php://temp', 'w+b');
151
        }
152
153
        return self::$debug_log_temp_stream_handle;
154
    }
155
156
    /**
157
     * Write the temporary debug stream to log and close the stream handle
158
     *
159
     * @param string $message Message (with placeholder) to write to the debug log
160
     */
161
    public static function endDebugLogTempStream($message = '%s')
162
    {
163
        if (is_resource(self::$debug_log_temp_stream_handle)) {
164
            rewind(self::$debug_log_temp_stream_handle);
165
            self::debug($message, stream_get_contents(self::$debug_log_temp_stream_handle));
166
            fclose(self::$debug_log_temp_stream_handle);
167
            self::$debug_log_temp_stream_handle = null;
168
        }
169
    }
170
171
    /**
172
     * Initialize update log
173
     *
174
     * @param string $path
175
     *
176
     * @return \Monolog\Logger
177
     * @throws \Longman\TelegramBot\Exception\TelegramLogException
178
     * @throws \InvalidArgumentException
179
     * @throws \Exception
180
     */
181 2
    public static function initUpdateLog($path)
182
    {
183 2
        if ($path === null || $path === '') {
184 1
            throw new TelegramLogException('Empty path for update log');
185
        }
186 1
        self::$update_log_path = $path;
187
188 1
        if (self::$monolog_update === null) {
189 1
            self::$monolog_update = new MonologLogger('bot_update_log');
190
191 1
            self::$monolog_update->pushHandler(
192 1
                (new StreamHandler(self::$update_log_path, MonologLogger::INFO))
193 1
                    ->setFormatter(new LineFormatter('%message%' . PHP_EOL))
194
            );
195
        }
196
197 1
        return self::$monolog_update;
198
    }
199
200
    /**
201
     * Is error log active
202
     *
203
     * @return bool
204
     */
205 4
    public static function isErrorLogActive()
206
    {
207 4
        return self::$error_log_path !== null;
208
    }
209
210
    /**
211
     * Is debug log active
212
     *
213
     * @return bool
214
     */
215 2
    public static function isDebugLogActive()
216
    {
217 2
        return self::$debug_log_path !== null;
218
    }
219
220
    /**
221
     * Is update log active
222
     *
223
     * @return bool
224
     */
225 1
    public static function isUpdateLogActive()
226
    {
227 1
        return self::$update_log_path !== null;
228
    }
229
230
    /**
231
     * Report error log
232
     *
233
     * @param string $text
234
     */
235 4
    public static function error($text)
236
    {
237 4
        if (self::isErrorLogActive()) {
238 4
            $text = self::getLogText($text, func_get_args());
239 4
            self::$monolog->error($text);
240
        }
241 4
    }
242
243
    /**
244
     * Report debug log
245
     *
246
     * @param string $text
247
     */
248 2
    public static function debug($text)
249
    {
250 2
        if (self::isDebugLogActive()) {
251 2
            $text = self::getLogText($text, func_get_args());
252 2
            self::$monolog->debug($text);
253
        }
254 2
    }
255
256
    /**
257
     * Report update log
258
     *
259
     * @param string $text
260
     */
261 1
    public static function update($text)
262
    {
263 1
        if (self::isUpdateLogActive()) {
264 1
            $text = self::getLogText($text, func_get_args());
265 1
            self::$monolog_update->info($text);
266
        }
267 1
    }
268
269
    /**
270
     * Applies vsprintf to the text if placeholder replacements are passed along.
271
     *
272
     * @param string $text
273
     * @param array  $args
274
     *
275
     * @return string
276
     */
277 6
    protected static function getLogText($text, array $args = [])
278
    {
279
        // Pop the $text off the array, as it gets passed via func_get_args().
280 6
        array_shift($args);
281
282
        // If no placeholders have been passed, don't parse the text.
283 6
        if (empty($args)) {
284 4
            return $text;
285
        }
286
287 6
        return vsprintf($text, $args);
288
    }
289
}
290