Patron::getLogFileName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/patron/license
6
 * @link       https://www.flipboxfactory.com/software/patron/
7
 */
8
9
namespace flipbox\patron;
10
11
use Craft;
12
use craft\base\Plugin;
13
use craft\events\RegisterUrlRulesEvent;
14
use craft\helpers\ArrayHelper;
15
use craft\helpers\Json;
16
use craft\helpers\UrlHelper;
17
use craft\services\ProjectConfig;
18
use craft\web\twig\variables\CraftVariable;
19
use craft\web\UrlManager;
20
use flipbox\craft\ember\helpers\ObjectHelper;
21
use flipbox\craft\ember\helpers\QueryHelper;
22
use flipbox\craft\ember\modules\LoggerTrait;
23
use flipbox\patron\events\handlers\ProjectConfigHandler;
24
use flipbox\patron\events\RegisterProviderSettings;
25
use flipbox\patron\models\Settings as SettingsModel;
26
use flipbox\patron\queries\ProviderQuery;
27
use flipbox\patron\queries\TokenQuery;
28
use flipbox\patron\records\Provider;
29
use flipbox\patron\records\Token;
30
use flipbox\patron\settings\BaseSettings;
31
use flipbox\patron\settings\SettingsInterface;
32
use yii\base\Event;
33
34
/**
35
 * @author Flipbox Factory <[email protected]>
36
 * @since 1.0.0
37
 *
38
 * @method SettingsModel getSettings()
39
 *
40
 * @property services\Session $session
41
 */
42
class Patron extends Plugin
43
{
44
    use LoggerTrait;
45
46
    /**
47
     * @var string
48
     */
49
    public static $category = 'patron';
50
51
    /**
52
     * The before persist token event name
53
     */
54
    const EVENT_BEFORE_PERSIST_TOKEN = 'beforePersistToken';
55
56
    /**
57 3
     *  The after persist token event name
58
     */
59 3
    const EVENT_AFTER_PERSIST_TOKEN = 'afterPersistToken';
60
61
    /**
62 3
     * @return string
63 3
     */
64
    protected static function getLogFileName(): string
65
    {
66
        return 'patron';
67 3
    }
68 3
69
    /**
70
     * @inheritdoc
71
     */
72 3
    public function init()
73 3
    {
74 3
        parent::init();
75 2
76
        // Components
77
        $this->setComponents([
78
            'session' => services\Session::class
79 3
        ]);
80
81
        // Modules
82
        $this->setModules([
83 3
            'cp' => cp\Cp::class
84 3
        ]);
85 3
86 3
87
        // Project config
88
        $this->registerProjectConfigEvents();
89
90 3
91 3
        // Template variables
92 3
        Event::on(
93 2
            CraftVariable::class,
94
            CraftVariable::EVENT_INIT,
95
            function (Event $event) {
96
                /** @var CraftVariable $variable */
97
                $variable = $event->sender;
98
                $variable->set('patron', self::getInstance());
99
            }
100 3
        );
101
102
        // CP routes
103
        Event::on(
104 3
            UrlManager::class,
105 3
            UrlManager::EVENT_REGISTER_CP_URL_RULES,
106 3
            [self::class, 'onRegisterCpUrlRules']
107 3
        );
108 3
109
        // Register our site routes
110 3
        Event::on(
111
            UrlManager::class,
112
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
113
            function (RegisterUrlRulesEvent $event) {
114
                if ($callbackUrlRule = $this->getSettings()->getCallbackUrlRule()) {
115
                    $event->rules = array_merge(
116
                        $event->rules,
117 3
                        $callbackUrlRule
118 3
                    );
119 3
                }
120 3
            }
121
        );
122 3
    }
123
124
    /**
125
     * Register project config events, if we're able to
126
     */
127 3
    protected function registerProjectConfigEvents()
128
    {
129
        if (!version_compare(Craft::$app->getVersion(), '3.1', '>=')) {
130
            return;
131
        }
132
133
        // Project Config
134
        Craft::$app->projectConfig
135
            ->onAdd(
136
                'plugins.patron.providers.{uid}',
137
                [
138
                    ProjectConfigHandler::class,
139
                    'handleChangedProvider'
140
                ]
141
            )
142
            ->onUpdate(
143
                'plugins.patron.providers.{uid}',
144
                [ProjectConfigHandler::class,
145
                    'handleChangedProvider'
146
                ]
147
            )
148
            ->onRemove(
149
                'plugins.patron.providers.{uid}',
150
                [ProjectConfigHandler::class,
151
                    'handleDeletedProvider'
152
                ]
153
            )
154
            ->onAdd(
155
                'plugins.patron.tokens.{uid}',
156
                [ProjectConfigHandler::class,
157
                    'handleChangedToken'
158
                ]
159
            )
160
            ->onUpdate(
161
                'plugins.patron.tokens.{uid}',
162
                [ProjectConfigHandler::class,
163
                    'handleChangedToken'
164
                ]
165 3
            )
166
            ->onRemove(
167 3
                'plugins.patron.tokens.{uid}',
168
                [ProjectConfigHandler::class,
169
                    'handleDeletedToken'
170
                ]
171
            );
172
173
        /**
174
         * Rebuilding project configs was introduce in 3.1.20
175
         */
176
        if (version_compare(Craft::$app->getVersion(), '3.1.20', '>=')) {
177
            Event::on(
178
                ProjectConfig::class,
179
                ProjectConfig::EVENT_REBUILD,
180
                [
181
                    events\handlers\ProjectConfigHandler::class,
182
                    'rebuild'
183
                ]
184
            );
185
        }
186
187
        Event::on(
188
            Provider::class,
189
            Provider::EVENT_AFTER_INSERT,
190
            [
191
                events\ManageProviderProjectConfig::class,
192
                'save'
193
            ]
194
        );
195
196
        Event::on(
197
            Provider::class,
198
            Provider::EVENT_AFTER_UPDATE,
199
            [
200
                events\ManageProviderProjectConfig::class,
201
                'save'
202
            ]
203
        );
204
205
        Event::on(
206
            Provider::class,
207
            Provider::EVENT_AFTER_DELETE,
208
            [
209
                events\ManageProviderProjectConfig::class,
210
                'delete'
211
            ]
212
        );
213
214
        Event::on(
215
            Token::class,
216
            Token::EVENT_AFTER_INSERT,
217
            [
218
                events\ManageTokenProjectConfig::class,
219
                'save'
220
            ]
221
        );
222
223
        Event::on(
224
            Token::class,
225
            Token::EVENT_AFTER_UPDATE,
226
            [
227
                events\ManageTokenProjectConfig::class,
228 3
                'save'
229
            ]
230
        );
231
232 3
        Event::on(
233
            Token::class,
234
            Token::EVENT_AFTER_DELETE,
235
            [
236
                events\ManageTokenProjectConfig::class,
237
                'delete'
238
            ]
239
        );
240
    }
241
242
243
    /*******************************************
244
     * NAV
245
     *******************************************/
246
247
    /**
248
     * @inheritdoc
249
     */
250
    public function getCpNavItem()
251
    {
252
        return array_merge(
253
            parent::getCpNavItem(),
254
            [
255
                'subnav' => [
256
                    'patron.providers' => [
257
                        'label' => Craft::t('patron', 'Providers'),
258
                        'url' => 'patron/providers',
259
                    ],
260
                    'patron.settings' => [
261
                        'label' => Craft::t('patron', 'Settings'),
262
                        'url' => 'patron/settings',
263
                    ]
264
                ]
265
            ]
266
        );
267
    }
268
269
270
    /*******************************************
271
     * SETTINGS
272
     *******************************************/
273
274
    /**
275
     * @inheritdoc
276
     * @return SettingsModel
277
     */
278
    public function createSettingsModel()
279
    {
280
        return new SettingsModel();
281
    }
282
283
    /**
284
     * @inheritdoc
285
     * @throws \yii\base\ExitException
286
     */
287
    public function getSettingsResponse()
288
    {
289
        Craft::$app->getResponse()->redirect(
290
            UrlHelper::cpUrl('patron/settings')
291
        );
292
293
        Craft::$app->end();
294
    }
295
296
    /*******************************************
297
     * QUERIES
298
     *******************************************/
299
300
    /**
301
     * @param array $config
302
     * @return ProviderQuery
303
     */
304
    public function getProviders(array $config = []): ProviderQuery
305
    {
306
        $query = new ProviderQuery();
307
308
        QueryHelper::configure(
309
            $query,
310
            $config
311
        );
312
313
        return $query;
314
    }
315
316
    /**
317
     * @param array $config
318
     * @return TokenQuery
319
     */
320
    public function getTokens(array $config = []): TokenQuery
321
    {
322
        $query = new TokenQuery();
323
324
        QueryHelper::configure(
325
            $query,
326
            $config
327
        );
328
329
        return $query;
330
    }
331
332
333
    /*******************************************
334
     * SERVICES
335
     *******************************************/
336
337
    /**
338
     * @noinspection PhpDocMissingThrowsInspection
339
     * @return services\Session
340
     */
341
    public function getSession(): services\Session
342
    {
343
        /** @noinspection PhpUnhandledExceptionInspection */
344
        /** @noinspection PhpIncompatibleReturnTypeInspection */
345
        return $this->get('session');
346
    }
347
348
349
    /*******************************************
350
     * MODULES
351
     *******************************************/
352
353
    /**
354
     * @noinspection PhpDocMissingThrowsInspection
355
     * @return cp\Cp
356
     */
357
    public function getCp(): cp\Cp
358
    {
359
        /** @noinspection PhpUnhandledExceptionInspection */
360
        /** @noinspection PhpIncompatibleReturnTypeInspection */
361
        return $this->getModule('cp');
362
    }
363
364
365
    /*******************************************
366
     * PROVIDER SETTINGS
367
     *******************************************/
368
369
    /**
370
     * @param string|null $class
371
     * @param array $settings
372
     * @return SettingsInterface
373
     * @throws \yii\base\InvalidConfigException
374
     */
375
    public function providerSettings(string $class = null, $settings = []): SettingsInterface
376
    {
377
        if (null === $class) {
378
            return new BaseSettings();
379
        }
380
381
        $event = new RegisterProviderSettings();
382
383
        RegisterProviderSettings::trigger(
384
            $class,
385
            RegisterProviderSettings::REGISTER_SETTINGS,
386
            $event
387
        );
388
389
        if (is_string($settings)) {
390
            $settings = Json::decodeIfJson($settings);
391
        }
392
393
        if (!is_array($settings)) {
394
            $settings = ArrayHelper::toArray($settings, []);
395
        }
396
397
        $settings['class'] = $event->class;
398
399
        /** @noinspection PhpIncompatibleReturnTypeInspection */
400
        return ObjectHelper::create($settings, SettingsInterface::class);
401
    }
402
403
404
    /*******************************************
405
     * EVENTS
406
     *******************************************/
407
408
    /**
409
     * @param RegisterUrlRulesEvent $event
410
     */
411
    public static function onRegisterCpUrlRules(RegisterUrlRulesEvent $event)
412
    {
413
        $event->rules = array_merge(
414
            $event->rules,
415
            [
416
                // SETTINGS
417
                'patron/settings' => 'patron/cp/view/settings/index',
418
419
                // BASE
420
                'patron' =>
421
                    'patron/cp/view/general/index',
422
423
                // PROVIDERS
424
                'patron/providers' =>
425
                    'patron/cp/view/providers/default/index',
426
427
                'patron/providers/new' =>
428
                    'patron/cp/view/providers/default/upsert',
429
430
                'patron/providers/<identifier:\d+>' =>
431
                    'patron/cp/view/providers/default/upsert',
432
433
                // TOKENS
434
                'patron/providers/<provider:\d+>/tokens' =>
435
                    'patron/cp/view/providers/tokens/index',
436
437
                'patron/providers/<provider:\d+>/tokens/<identifier:\d+>' =>
438
                    'patron/cp/view/providers/tokens/upsert',
439
            ]
440
        );
441
    }
442
443
    /*******************************************
444
     * TRANSLATE
445
     *******************************************/
446
447
    /**
448
     * Translates a message to the specified language.
449
     *
450
     * This is a shortcut method of [[\Craft::t()]].
451
     *     *
452
     * @param string $message the message to be translated.
453
     * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
454
     * @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
455
     * [[\yii\base\Application::language|application language]] will be used.
456
     * @return string the translated message.
457
     */
458
    public static function t($message, $params = [], $language = null)
459
    {
460
        return Craft::t(self::$category, $message, $params, $language);
461
    }
462
}
463