Completed
Push — develop ( 112c74...31322a )
by Nate
10:28
created

Jwt::loggerCategory()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 8
cp 0
rs 9.6111
c 0
b 0
f 0
cc 5
nc 12
nop 2
crap 30
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/jwt/license
6
 * @link       https://www.flipboxfactory.com/jwt/organization/
7
 */
8
9
namespace flipbox\craft\jwt;
10
11
use Craft;
12
use craft\base\Plugin;
13
use craft\web\twig\variables\CraftVariable;
14
use flipbox\craft\jwt\models\Settings as SettingsModel;
15
use Lcobucci\JWT\Builder;
16
use Lcobucci\JWT\Claim\Factory as ClaimFactory;
17
use Lcobucci\JWT\Parser;
18
use Lcobucci\JWT\Parsing\Decoder;
19
use Lcobucci\JWT\Parsing\Encoder;
20
use Lcobucci\JWT\Token;
21
use Lcobucci\JWT\ValidationData;
22
use yii\base\Event;
23
use yii\log\Logger;
24
25
/**
26
 * @author Flipbox Factory <[email protected]>
27
 * @since 1.0.0
28
 *
29
 * @method SettingsModel getSettings()
30
 */
31
class Jwt extends Plugin
32
{
33
    /**
34
     * The plugin category
35
     *
36
     * @var string
37
     */
38
    public static $category = 'jwt';
39
40
    /**
41
     * @inheritdoc
42
     */
43
    public function init()
44
    {
45
        parent::init();
46
47
        // Components
48
        $this->setComponents([
49
            'identity' => services\Identity::class,
50
            'route' => services\Route::class
51
        ]);
52
53
        // Template variables
54
        Event::on(
55
            CraftVariable::class,
56
            CraftVariable::EVENT_INIT,
57
            function (Event $event) {
58
                /** @var CraftVariable $variable */
59
                $variable = $event->sender;
60
                $variable->set('jwt', self::getInstance());
61
            }
62
        );
63
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68
    public function createSettingsModel(): SettingsModel
69
    {
70
        return new SettingsModel();
71
    }
72
73
    /*******************************************
74
     * SERVICES
75
     *******************************************/
76
77
    /**
78
     * @noinspection PhpDocMissingThrowsInspection
79
     * @return services\Identity
80
     */
81
    public function getIdentity(): services\Identity
82
    {
83
        /** @noinspection PhpUnhandledExceptionInspection */
84
        /** @noinspection PhpIncompatibleReturnTypeInspection */
85
        return $this->get('identity');
86
    }
87
88
    /**
89
     * @noinspection PhpDocMissingThrowsInspection
90
     * @return services\Route
91
     */
92
    public function getRoute(): services\Route
93
    {
94
        /** @noinspection PhpUnhandledExceptionInspection */
95
        /** @noinspection PhpIncompatibleReturnTypeInspection */
96
        return $this->get('route');
97
    }
98
99
    /**
100
     * @deprecated
101
     */
102
    public function getSelfConsumable(): services\Identity
103
    {
104
        return $this->getIdentity();
105
    }
106
107
    /*******************************************
108
     * JWT
109
     *******************************************/
110
111
    /**
112
     * @param Encoder|null $encoder
113
     * @param ClaimFactory|null $claimFactory
114
     *
115
     * @see [[Lcobucci\JWT\Builder::__construct()]]
116
     * @return Builder
117
     */
118
    public function getBuilder(Encoder $encoder = null, ClaimFactory $claimFactory = null): Builder
119
    {
120
        return new Builder($encoder, $claimFactory);
121
    }
122
123
    /**
124
     * @param Decoder|null $decoder
125
     * @param ClaimFactory|null $claimFactory
126
     *
127
     * @see [[Lcobucci\JWT\Parser::__construct()]]
128
     * @return Parser
129
     */
130
    public function getParser(Decoder $decoder = null, ClaimFactory $claimFactory = null): Parser
131
    {
132
        return new Parser($decoder, $claimFactory);
133
    }
134
135
    /**
136
     * @param int|null $currentTime
137
     *
138
     * @see [[Lcobucci\JWT\ValidationData::__construct()]]
139
     * @return ValidationData
140
     */
141
    public function getValidationData(int $currentTime = null): ValidationData
142
    {
143
        return new ValidationData($currentTime);
144
    }
145
146
    /**
147
     * @param Token $token
148
     * @param int|null $currentTime
149
     * @return bool
150
     */
151
    public function validateToken(Token $token, int $currentTime = null): bool
152
    {
153
        return $token->validate(
154
            $this->getValidationData($currentTime)
155
        );
156
    }
157
158
159
    /*******************************************
160
     * LOGGING
161
     *******************************************/
162
163
    /**
164
     * The log categories
165
     *
166
     * @param string|null $category
167
     * @param bool $audit flag as an audit message.
168
     * @return string
169
     */
170
    protected static function loggerCategory(string $category = null, bool $audit = false): string
171
    {
172
        /** @noinspection PhpUndefinedFieldInspection */
173
        $prefix = static::$category ? (static::$category . ($audit ? ':audit' : '')) : '';
174
175
        if (empty($category)) {
176
            return $prefix;
177
        }
178
179
        return ($prefix ? $prefix . ':' : '') . $category;
180
    }
181
182
    /**
183
     * Logs a debug message.
184
     * Trace messages are logged mainly for development purpose to see
185
     * the execution work flow of some code. This method will only log
186
     * a message when the application is in debug mode.
187
     * @param string|array $message the message to be logged. This can be a simple string or a more
188
     * complex data structure, such as array.
189
     * @param string $category the category of the message.
190
     * @param bool $audit flag as an audit message.
191
     * @since 2.0.0
192
     */
193
    public static function debug($message, $category = 'general', bool $audit = false)
194
    {
195
        Craft::getLogger()->log($message, Logger::LEVEL_TRACE, static::loggerCategory($category, $audit));
196
    }
197
198
    /**
199
     * Logs an error message.
200
     * An error message is typically logged when an unrecoverable error occurs
201
     * during the execution of an application.
202
     * @param string|array $message the message to be logged. This can be a simple string or a more
203
     * complex data structure, such as array.
204
     * @param string $category the category of the message.
205
     * @param bool $audit flag as an audit message.
206
     * @since 2.0.0
207
     */
208
    public static function error($message, $category = 'general', bool $audit = false)
209
    {
210
        Craft::getLogger()->log($message, Logger::LEVEL_ERROR, static::loggerCategory($category, $audit));
211
    }
212
213
    /**
214
     * Logs a warning message.
215
     * A warning message is typically logged when an error occurs while the execution
216
     * can still continue.
217
     * @param string|array $message the message to be logged. This can be a simple string or a more
218
     * complex data structure, such as array.
219
     * @param string $category the category of the message.
220
     * @param bool $audit flag as an audit message.
221
     * @since 2.0.0
222
     */
223
    public static function warning($message, $category = 'general', bool $audit = false)
224
    {
225
        Craft::getLogger()->log($message, Logger::LEVEL_WARNING, static::loggerCategory($category, $audit));
226
    }
227
228
    /**
229
     * Logs an informative message.
230
     * An informative message is typically logged by an application to keep record of
231
     * something important (e.g. an administrator logs in).
232
     * @param string|array $message the message to be logged. This can be a simple string or a more
233
     * complex data structure, such as array.
234
     * @param string $category the category of the message.
235
     * @param bool $audit flag as an audit message.
236
     * @since 2.0.0
237
     */
238
    public static function info($message, $category = 'general', bool $audit = false)
239
    {
240
        Craft::getLogger()->log($message, Logger::LEVEL_INFO, static::loggerCategory($category, $audit));
241
    }
242
}
243