Completed
Push — master ( 32191e...8fb922 )
by Nate
03:04 queued 11s
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
 * @property services\Identity identity
30
 * @property services\Route route
31
 *
32
 * @method SettingsModel getSettings()
33
 */
34
class Jwt extends Plugin
35
{
36
    /**
37
     * The plugin category
38
     *
39
     * @var string
40
     */
41
    public static $category = 'jwt';
42
43
    /**
44
     * @inheritdoc
45
     */
46
    public function init()
47
    {
48
        parent::init();
49
50
        // Components
51
        $this->setComponents([
52
            'identity' => services\Identity::class,
53
            'route' => services\Route::class
54
        ]);
55
56
        // Template variables
57
        Event::on(
58
            CraftVariable::class,
59
            CraftVariable::EVENT_INIT,
60
            function (Event $event) {
61
                /** @var CraftVariable $variable */
62
                $variable = $event->sender;
63
                $variable->set('jwt', self::getInstance());
64
            }
65
        );
66
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71
    public function createSettingsModel(): SettingsModel
72
    {
73
        return new SettingsModel();
74
    }
75
76
    /*******************************************
77
     * SERVICES
78
     *******************************************/
79
80
    /**
81
     * @noinspection PhpDocMissingThrowsInspection
82
     * @return services\Identity
83
     */
84
    public function getIdentity(): services\Identity
85
    {
86
        /** @noinspection PhpUnhandledExceptionInspection */
87
        /** @noinspection PhpIncompatibleReturnTypeInspection */
88
        return $this->get('identity');
89
    }
90
91
    /**
92
     * @noinspection PhpDocMissingThrowsInspection
93
     * @return services\Route
94
     */
95
    public function getRoute(): services\Route
96
    {
97
        /** @noinspection PhpUnhandledExceptionInspection */
98
        /** @noinspection PhpIncompatibleReturnTypeInspection */
99
        return $this->get('route');
100
    }
101
102
    /**
103
     * @deprecated
104
     */
105
    public function getSelfConsumable(): services\Identity
106
    {
107
        Craft::$app->getDeprecator()->log(
108
            self::class . '::getSelfConsumable',
109
            self::class . '::getSelfConsumable() has been deprecated. Use getIdentity() instead.'
110
        );
111
        return $this->getIdentity();
112
    }
113
114
    /*******************************************
115
     * JWT
116
     *******************************************/
117
118
    /**
119
     * @param Encoder|null $encoder
120
     * @param ClaimFactory|null $claimFactory
121
     *
122
     * @see [[Lcobucci\JWT\Builder::__construct()]]
123
     * @return Builder
124
     */
125
    public function getBuilder(Encoder $encoder = null, ClaimFactory $claimFactory = null): Builder
126
    {
127
        return new Builder($encoder, $claimFactory);
128
    }
129
130
    /**
131
     * @param Decoder|null $decoder
132
     * @param ClaimFactory|null $claimFactory
133
     *
134
     * @see [[Lcobucci\JWT\Parser::__construct()]]
135
     * @return Parser
136
     */
137
    public function getParser(Decoder $decoder = null, ClaimFactory $claimFactory = null): Parser
138
    {
139
        return new Parser($decoder, $claimFactory);
140
    }
141
142
    /**
143
     * @param int|null $currentTime
144
     *
145
     * @see [[Lcobucci\JWT\ValidationData::__construct()]]
146
     * @return ValidationData
147
     */
148
    public function getValidationData(int $currentTime = null): ValidationData
149
    {
150
        return new ValidationData($currentTime);
151
    }
152
153
    /**
154
     * @param Token $token
155
     * @param int|null $currentTime
156
     * @return bool
157
     */
158
    public function validateToken(Token $token, int $currentTime = null): bool
159
    {
160
        return $token->validate(
161
            $this->getValidationData($currentTime)
162
        );
163
    }
164
165
166
    /*******************************************
167
     * LOGGING
168
     *******************************************/
169
170
    /**
171
     * The log categories
172
     *
173
     * @param string|null $category
174
     * @param bool $audit flag as an audit message.
175
     * @return string
176
     */
177
    protected static function loggerCategory(string $category = null, bool $audit = false): string
178
    {
179
        /** @noinspection PhpUndefinedFieldInspection */
180
        $prefix = static::$category ? (static::$category . ($audit ? ':audit' : '')) : '';
181
182
        if (empty($category)) {
183
            return $prefix;
184
        }
185
186
        return ($prefix ? $prefix . ':' : '') . $category;
187
    }
188
189
    /**
190
     * Logs a debug message.
191
     * Trace messages are logged mainly for development purpose to see
192
     * the execution work flow of some code. This method will only log
193
     * a message when the application is in debug mode.
194
     * @param string|array $message the message to be logged. This can be a simple string or a more
195
     * complex data structure, such as array.
196
     * @param string $category the category of the message.
197
     * @param bool $audit flag as an audit message.
198
     * @since 2.0.0
199
     */
200
    public static function debug($message, $category = 'general', bool $audit = false)
201
    {
202
        Craft::getLogger()->log($message, Logger::LEVEL_TRACE, static::loggerCategory($category, $audit));
203
    }
204
205
    /**
206
     * Logs an error message.
207
     * An error message is typically logged when an unrecoverable error occurs
208
     * during the execution of an application.
209
     * @param string|array $message the message to be logged. This can be a simple string or a more
210
     * complex data structure, such as array.
211
     * @param string $category the category of the message.
212
     * @param bool $audit flag as an audit message.
213
     * @since 2.0.0
214
     */
215
    public static function error($message, $category = 'general', bool $audit = false)
216
    {
217
        Craft::getLogger()->log($message, Logger::LEVEL_ERROR, static::loggerCategory($category, $audit));
218
    }
219
220
    /**
221
     * Logs a warning message.
222
     * A warning message is typically logged when an error occurs while the execution
223
     * can still continue.
224
     * @param string|array $message the message to be logged. This can be a simple string or a more
225
     * complex data structure, such as array.
226
     * @param string $category the category of the message.
227
     * @param bool $audit flag as an audit message.
228
     * @since 2.0.0
229
     */
230
    public static function warning($message, $category = 'general', bool $audit = false)
231
    {
232
        Craft::getLogger()->log($message, Logger::LEVEL_WARNING, static::loggerCategory($category, $audit));
233
    }
234
235
    /**
236
     * Logs an informative message.
237
     * An informative message is typically logged by an application to keep record of
238
     * something important (e.g. an administrator logs in).
239
     * @param string|array $message the message to be logged. This can be a simple string or a more
240
     * complex data structure, such as array.
241
     * @param string $category the category of the message.
242
     * @param bool $audit flag as an audit message.
243
     * @since 2.0.0
244
     */
245
    public static function info($message, $category = 'general', bool $audit = false)
246
    {
247
        Craft::getLogger()->log($message, Logger::LEVEL_INFO, static::loggerCategory($category, $audit));
248
    }
249
}
250