Completed
Push — master ( a2c5ed...11971b )
by Nate
01:35
created

LoggerTrait::getLogCategories()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember
7
 */
8
9
namespace flipbox\ember\modules;
10
11
use Craft;
12
use craft\helpers\StringHelper;
13
use craft\log\FileTarget;
14
use yii\log\Logger;
15
16
/**
17
 * This trait will create and attach a separate log dispatcher / logger.  It allows modules to log to a separate
18
 * log file, while still supporting the use of categories.
19
 *
20
 * @author Flipbox Factory <[email protected]>
21
 * @since 1.0.2
22
 */
23
trait LoggerTrait
24
{
25
    private static $logTargetSet = false;
26
27
    /**
28
     * The log file name
29
     *
30
     * @return string
31
     */
32
    abstract protected static function getLogFileName(): string;
33
34
    /**
35
     * @inheritdoc
36
     */
37
    protected static function isDebugModeEnabled()
38
    {
39
        return false;
40
    }
41
42
    /**
43
     * The log categories
44
     *
45
     * @return string
46
     */
47
    protected static function getLogId(): string
48
    {
49
        return static::getLogFileName();
50
    }
51
52
    /**
53
     * The log categories
54
     *
55
     * @return array
56
     */
57
    protected static function getLogCategories(): array
58
    {
59
        $fileName = static::getLogId();
60
        return [$fileName, $fileName . ':*'];
61
    }
62
63
    /**
64
     * @return string
65
     */
66
    public static function getLogFile(): string
67
    {
68
        return '@storage/logs/' . self::prepLogFileName(static::getLogFileName());
69
    }
70
71
    /**
72
     * @return Logger
73
     */
74
    public static function getLogger(): Logger
75
    {
76
        if (static::$logTargetSet !== true) {
0 ignored issues
show
Bug introduced by
Since $logTargetSet is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $logTargetSet to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
77
            static::addLoggerFileTarget();
78
79
            static::$logTargetSet = true;
0 ignored issues
show
Bug introduced by
Since $logTargetSet is declared private, accessing it with static will lead to errors in possible sub-classes; consider using self, or increasing the visibility of $logTargetSet to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return static::$someVariable;
    }
}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass { }

YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class SomeClass
{
    private static $someVariable;

    public static function getSomeVariable()
    {
        return self::$someVariable; // self works fine with private.
    }
}
Loading history...
80
        }
81
82
        return Craft::getLogger();
83
    }
84
85
    /**
86
     * @noinspection PhpDocMissingThrowsInspection
87
     * @return FileTarget
88
     */
89
    protected static function createLoggerFileTarget(): FileTarget
90
    {
91
        /** @noinspection PhpIncompatibleReturnTypeInspection */
92
        /** @noinspection PhpUnhandledExceptionInspection */
93
        return Craft::createObject(
94
            static::loggerFileTarget()
95
        );
96
    }
97
98
    /**
99
     * Adds the file target logger
100
     */
101
    protected static function addLoggerFileTarget()
102
    {
103
        Craft::getLogger()->dispatcher->targets[static::getLogId()] = static::createLoggerFileTarget();
104
    }
105
106
    /**
107
     * @return array
108
     */
109
    protected static function loggerFileTarget()
110
    {
111
        $generalConfig = Craft::$app->getConfig()->getGeneral();
112
113
        return [
114
            'class' => FileTarget::class,
115
            'fileMode' => $generalConfig->defaultFileMode,
116
            'dirMode' => $generalConfig->defaultDirMode,
117
            'logVars' => [],
118
            'categories' => static::getLogCategories(),
119
            'levels' => array_merge(
120
                ['error', 'warning'],
121
                (static::isDebugModeEnabled() || YII_DEBUG) ? ['trace', 'info'] : []
122
            ),
123
            'logFile' => static::getLogFile()
124
        ];
125
    }
126
127
    /**
128
     * @param string $fileName
129
     * @return string
130
     */
131
    private static function prepLogFileName(string $fileName): string
132
    {
133
        return StringHelper::toKebabCase(
134
            StringHelper::removeRight($fileName, '.log')
135
        ) . '.log';
136
    }
137
138
    /**
139
     * Logs a debug message.
140
     * Trace messages are logged mainly for development purpose to see
141
     * the execution work flow of some code. This method will only log
142
     * a message when the application is in debug mode.
143
     * @param string|array $message the message to be logged. This can be a simple string or a more
144
     * complex data structure, such as array.
145
     * @param string $category the category of the message.
146
     * @since 2.0.14
147
     */
148
    public static function debug($message, $category = 'general')
149
    {
150
        static::getLogger()->log($message, Logger::LEVEL_TRACE, static::getLogId() . ':' . $category);
151
    }
152
153
    /**
154
     * Logs an error message.
155
     * An error message is typically logged when an unrecoverable error occurs
156
     * during the execution of an application.
157
     * @param string|array $message the message to be logged. This can be a simple string or a more
158
     * complex data structure, such as array.
159
     * @param string $category the category of the message.
160
     */
161
    public static function error($message, $category = 'general')
162
    {
163
        static::getLogger()->log($message, Logger::LEVEL_ERROR, static::getLogId() . ':' . $category);
164
    }
165
166
    /**
167
     * Logs a warning message.
168
     * A warning message is typically logged when an error occurs while the execution
169
     * can still continue.
170
     * @param string|array $message the message to be logged. This can be a simple string or a more
171
     * complex data structure, such as array.
172
     * @param string $category the category of the message.
173
     */
174
    public static function warning($message, $category = 'general')
175
    {
176
        static::getLogger()->log($message, Logger::LEVEL_WARNING, static::getLogId() . ':' . $category);
177
    }
178
179
    /**
180
     * Logs an informative message.
181
     * An informative message is typically logged by an application to keep record of
182
     * something important (e.g. an administrator logs in).
183
     * @param string|array $message the message to be logged. This can be a simple string or a more
184
     * complex data structure, such as array.
185
     * @param string $category the category of the message.
186
     */
187
    public static function info($message, $category = 'general')
188
    {
189
        static::getLogger()->log($message, Logger::LEVEL_INFO, static::getLogId() . ':' . $category);
190
    }
191
}
192