Passed
Push — develop ( 335e9d...0c2b1f )
by Andrew
03:15
created

Webperf::clearAllCaches()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Webperf plugin for Craft CMS 3.x
4
 *
5
 * Monitor the performance of your webpages through real-world user timing data
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2018 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\webperf;
12
13
use nystudio107\webperf\log\ProfileTarget;
14
use nystudio107\webperf\models\DataSample;
15
use nystudio107\webperf\models\Settings;
16
use nystudio107\webperf\services\DataSamples as DataSamplesService;
17
use nystudio107\webperf\services\Beacons as BeaconsService;
18
use nystudio107\webperf\variables\WebperfVariable;
19
use nystudio107\webperf\widgets\Metrics as MetricsWidget;
20
21
use Craft;
0 ignored issues
show
Bug introduced by
The type Craft was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use craft\base\Plugin;
0 ignored issues
show
Bug introduced by
The type craft\base\Plugin was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
use craft\services\Plugins;
0 ignored issues
show
Bug introduced by
The type craft\services\Plugins was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
use craft\events\PluginEvent;
0 ignored issues
show
Bug introduced by
The type craft\events\PluginEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
25
use craft\events\RegisterComponentTypesEvent;
0 ignored issues
show
Bug introduced by
The type craft\events\RegisterComponentTypesEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use craft\events\RegisterUserPermissionsEvent;
0 ignored issues
show
Bug introduced by
The type craft\events\RegisterUserPermissionsEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use craft\events\RegisterUrlRulesEvent;
0 ignored issues
show
Bug introduced by
The type craft\events\RegisterUrlRulesEvent was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
use craft\helpers\UrlHelper;
0 ignored issues
show
Bug introduced by
The type craft\helpers\UrlHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
use craft\services\Dashboard;
0 ignored issues
show
Bug introduced by
The type craft\services\Dashboard was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
use craft\services\UserPermissions;
0 ignored issues
show
Bug introduced by
The type craft\services\UserPermissions was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use craft\web\twig\variables\CraftVariable;
0 ignored issues
show
Bug introduced by
The type craft\web\twig\variables\CraftVariable was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
use craft\web\UrlManager;
0 ignored issues
show
Bug introduced by
The type craft\web\UrlManager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
33
use craft\web\View;
0 ignored issues
show
Bug introduced by
The type craft\web\View was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
35
use yii\base\Event;
0 ignored issues
show
Bug introduced by
The type yii\base\Event was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
use yii\base\InvalidConfigException;
0 ignored issues
show
Bug introduced by
The type yii\base\InvalidConfigException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
38
/**
39
 * Class Webperf
40
 *
41
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 4
Loading history...
42
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
43
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 3 spaces but found 5
Loading history...
44
 *
45
 * @property  DataSamplesService  $dataSamples
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 2
Loading history...
46
 * @property  BeaconsService      $beacons
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 2
Loading history...
47
 * @property  ProfileTarget       $profileTarget
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 2
Loading history...
48
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
49
class Webperf extends Plugin
50
{
51
    // Static Properties
52
    // =========================================================================
53
54
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
55
     * @var Webperf
56
     */
57
    public static $plugin;
58
59
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
60
     * @var Settings
61
     */
62
    public static $settings;
63
64
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
65
     * @var int|null
66
     */
67
    public static $requestUuid;
68
69
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
70
     * @var int|null
71
     */
72
    public static $requestUrl;
73
74
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
75
     * @var bool
76
     */
77
    public static $beaconIncluded = false;
78
79
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
80
     * @var string
81
     */
82
    public static $renderType = 'html';
83
84
    // Public Properties
85
    // =========================================================================
86
87
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
88
     * @var string
89
     */
90
    public $schemaVersion = '1.0.0';
91
92
    // Public Methods
93
    // =========================================================================
94
95
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
96
     * @inheritdoc
97
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
98
    public function init()
99
    {
100
        parent::init();
101
        // Initialize properties
102
        self::$plugin = $this;
103
        self::$settings = $this->getSettings();
104
        try {
105
            self::$requestUuid = random_int(0, PHP_INT_MAX);
106
        } catch (\Exception $e) {
107
            self::$requestUuid = null;
108
        }
109
        $this->name = self::$settings->pluginName;
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
110
        // Add in our components
111
        $this->addComponents();
112
        // Install event listeners
113
        $this->installEventListeners();
114
        // Load that we've loaded
115
        Craft::info(
116
            Craft::t(
117
                'webperf',
118
                '{name} plugin loaded',
119
                ['name' => $this->name]
120
            ),
121
            __METHOD__
122
        );
123
    }
124
125
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
126
     * @inheritdoc
127
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
128
    public function getSettingsResponse()
129
    {
130
        // Just redirect to the plugin settings page
131
        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('webperf/settings'));
132
    }
133
134
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
135
     * @inheritdoc
136
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
137
    public function getCpNavItem()
138
    {
139
        $subNavs = [];
140
        $navItem = parent::getCpNavItem();
141
        $currentUser = Craft::$app->getUser()->getIdentity();
142
        // Only show sub-navs the user has permission to view
143
        if ($currentUser->can('webperf:dashboard')) {
144
            $subNavs['dashboard'] = [
145
                'label' => 'Dashboard',
146
                'url' => 'webperf/dashboard',
147
            ];
148
        }
149
        if ($currentUser->can('webperf:pages')) {
150
            $subNavs['pages'] = [
151
                'label' => 'Pages',
152
                'url' => 'webperf/pages',
153
            ];
154
        }
155
        if ($currentUser->can('webperf:settings')) {
156
            $subNavs['settings'] = [
157
                'label' => 'Settings',
158
                'url' => 'webperf/settings',
159
            ];
160
        }
161
        $navItem = array_merge($navItem, [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
162
            'subnav' => $subNavs,
163
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
164
165
        return $navItem;
166
    }
167
168
    // Protected Methods
169
    // =========================================================================
170
171
    /**
172
     * Add in our components
173
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
174
    protected function addComponents()
175
    {
176
        $request = Craft::$app->getRequest();
177
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
178
            $this->setRequestUrl();
179
            if (self::$settings->includeCraftProfiling) {
180
                // Add in the ProfileTarget component
181
                try {
182
                    $this->set('profileTarget', [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
183
                        'class' => ProfileTarget::class,
184
                        'levels' => ['profile'],
185
                        'categories' => [],
186
                        'logVars' => [],
187
                        'except' => [],
188
                    ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
189
                } catch (InvalidConfigException $e) {
190
                    Craft::error($e->getMessage(), __METHOD__);
191
                }
192
                // Attach our log target
193
                Craft::$app->getLog()->targets['webperf'] = $this->profileTarget;
194
            }
195
        }
196
    }
197
198
    /**
199
     * Set the request URL
200
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
201
    protected function setRequestUrl()
202
    {
203
        self::$requestUrl = DataSample::PLACEHOLDER_URL;
0 ignored issues
show
Documentation Bug introduced by
It seems like nystudio107\webperf\mode...Sample::PLACEHOLDER_URL of type string is incompatible with the declared type integer|null of property $requestUrl.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
204
        if (!self::$settings->includeBeacon) {
205
            $request = Craft::$app->getRequest();
206
            self::$requestUrl = UrlHelper::stripQueryString(
207
                urldecode($request->getAbsoluteUrl())
208
            );
209
        }
210
    }
211
212
    /**
213
     * Install our event listeners.
214
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
215
    protected function installEventListeners()
216
    {
217
        $request = Craft::$app->getRequest();
218
        // Add in our event listeners that are needed for every request
219
        $this->installGlobalEventListeners();
220
        // Install only for non-console site requests
221
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
222
            $this->installSiteEventListeners();
223
        }
224
        // Install only for non-console Control Panel requests
225
        if ($request->getIsCpRequest() && !$request->getIsConsoleRequest()) {
226
            $this->installCpEventListeners();
227
        }
228
        // Handler: EVENT_AFTER_INSTALL_PLUGIN
229
        Event::on(
230
            Plugins::class,
231
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
232
            function (PluginEvent $event) {
233
                if ($event->plugin === $this) {
234
                    // Invalidate our caches after we've been installed
235
                    $this->clearAllCaches();
236
                    // Send them to our welcome screen
237
                    $request = Craft::$app->getRequest();
238
                    if ($request->isCpRequest) {
239
                        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl(
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
240
                            'webperf/dashboard',
241
                            [
242
                                'showWelcome' => true,
243
                            ]
244
                        ))->send();
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
245
                    }
246
                }
247
            }
248
        );
249
    }
250
251
    /**
252
     * Install global event listeners for all request types
253
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
254
    protected function installGlobalEventListeners()
255
    {
256
        // Handler: CraftVariable::EVENT_INIT
257
        Event::on(
258
            CraftVariable::class,
259
            CraftVariable::EVENT_INIT,
260
            function (Event $event) {
261
                /** @var CraftVariable $variable */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
262
                $variable = $event->sender;
263
                $variable->set('webperf', WebperfVariable::class);
264
            }
265
        );
266
        // Handler: Plugins::EVENT_AFTER_LOAD_PLUGINS
267
        Event::on(
268
            Plugins::class,
269
            Plugins::EVENT_AFTER_LOAD_PLUGINS,
270
            function () {
271
                // Install these only after all other plugins have loaded
272
                $request = Craft::$app->getRequest();
273
                // Only respond to non-console site requests
274
                if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
275
                    $this->handleSiteRequest();
276
                }
277
                // Respond to Control Panel requests
278
                if ($request->getIsCpRequest() && !$request->getIsConsoleRequest()) {
279
                    $this->handleAdminCpRequest();
280
                }
281
            }
282
        );
283
    }
284
285
    /**
286
     * Install site event listeners for site requests only
287
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
288
    protected function installSiteEventListeners()
289
    {
290
        // Handler: UrlManager::EVENT_REGISTER_SITE_URL_RULES
291
        Event::on(
292
            UrlManager::class,
293
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
294
            function (RegisterUrlRulesEvent $event) {
295
                Craft::debug(
296
                    'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
297
                    __METHOD__
298
                );
299
                // Register our Control Panel routes
300
                $event->rules = array_merge(
301
                    $event->rules,
302
                    $this->customFrontendRoutes()
303
                );
304
            }
305
        );
306
    }
307
308
    /**
309
     * Install site event listeners for Control Panel requests only
310
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
311
    protected function installCpEventListeners()
312
    {
313
        // Handler: UrlManager::EVENT_REGISTER_CP_URL_RULES
314
        Event::on(
315
            UrlManager::class,
316
            UrlManager::EVENT_REGISTER_CP_URL_RULES,
317
            function (RegisterUrlRulesEvent $event) {
318
                Craft::debug(
319
                    'UrlManager::EVENT_REGISTER_CP_URL_RULES',
320
                    __METHOD__
321
                );
322
                // Register our Control Panel routes
323
                $event->rules = array_merge(
324
                    $event->rules,
325
                    $this->customAdminCpRoutes()
326
                );
327
            }
328
        );
329
        // Handler: Dashboard::EVENT_REGISTER_WIDGET_TYPES
330
        Event::on(
331
            Dashboard::class,
332
            Dashboard::EVENT_REGISTER_WIDGET_TYPES,
333
            function (RegisterComponentTypesEvent $event) {
334
                $event->types[] = MetricsWidget::class;
335
            }
336
        );
337
        // Handler: UserPermissions::EVENT_REGISTER_PERMISSIONS
338
        Event::on(
339
            UserPermissions::class,
340
            UserPermissions::EVENT_REGISTER_PERMISSIONS,
341
            function (RegisterUserPermissionsEvent $event) {
342
                Craft::debug(
343
                    'UserPermissions::EVENT_REGISTER_PERMISSIONS',
344
                    __METHOD__
345
                );
346
                // Register our custom permissions
347
                $event->permissions[Craft::t('webperf', 'Webperf')] = $this->customAdminCpPermissions();
348
            }
349
        );
350
    }
351
352
    /**
353
     * Handle site requests.  We do it only after we receive the event
354
     * EVENT_AFTER_LOAD_PLUGINS so that any pending db migrations can be run
355
     * before our event listeners kick in
356
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
357
    protected function handleSiteRequest()
358
    {
359
        // Don't include the beacon for response codes >= 400
360
        $response = Craft::$app->getResponse();
361
        if ($response->statusCode < 400) {
362
            // Handler: View::EVENT_END_PAGE
363
            Event::on(
364
                View::class,
365
                View::EVENT_END_PAGE,
366
                function () {
367
                    Craft::debug(
368
                        'View::EVENT_END_PAGE',
369
                        __METHOD__
370
                    );
371
                    $view = Craft::$app->getView();
372
                    // The page is done rendering, include our beacon
373
                    if (Webperf::$settings->includeBeacon && $view->getIsRenderingPageTemplate()) {
374
                        switch (self::$renderType) {
375
                            case 'html':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
376
                                Webperf::$plugin->beacons->includeHtmlBeacon();
377
                                self::$beaconIncluded = true;
378
                                break;
379
                            case 'amp-html':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
380
                                Webperf::$plugin->beacons->includeAmpHtmlScript();
381
                                break;
382
                        }
383
                    }
384
                }
385
            );
386
            // Handler: View::EVENT_END_BODY
387
            Event::on(
388
                View::class,
389
                View::EVENT_END_BODY,
390
                function () {
391
                    Craft::debug(
392
                        'View::EVENT_END_BODY',
393
                        __METHOD__
394
                    );
395
                    $view = Craft::$app->getView();
396
                    // The page is done rendering, include our beacon
397
                    if (Webperf::$settings->includeBeacon && $view->getIsRenderingPageTemplate()) {
398
                        switch (self::$renderType) {
399
                            case 'html':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
400
                                break;
401
                            case 'amp-html':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
402
                                Webperf::$plugin->beacons->includeAmpHtmlBeacon();
403
                                self::$beaconIncluded = true;
404
                                break;
405
                        }
406
                    }
407
                }
408
            );
409
        }
410
    }
411
412
    /**
413
     * Handle Control Panel requests. We do it only after we receive the event
414
     * EVENT_AFTER_LOAD_PLUGINS so that any pending db migrations can be run
415
     * before our event listeners kick in
416
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
417
    protected function handleAdminCpRequest()
418
    {
419
    }
420
421
    /**
422
     * Clear all the caches!
423
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
424
    public function clearAllCaches()
425
    {
426
    }
427
428
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
429
     * @inheritdoc
430
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
431
    protected function createSettingsModel()
432
    {
433
        return new Settings();
434
    }
435
436
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
437
     * @inheritdoc
438
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
439
    protected function settingsHtml(): string
440
    {
441
        return Craft::$app->view->renderTemplate(
442
            'webperf/settings',
443
            [
444
                'settings' => $this->getSettings()
445
            ]
446
        );
447
    }
448
449
    /**
450
     * Return the custom frontend routes
451
     *
452
     * @return array
453
     */
454
    protected function customFrontendRoutes(): array
455
    {
456
        return [
457
            // Beacon
458
            '/webperf/metrics/beacon' => 'webperf/metrics/beacon',
459
            // Render
460
            '/webperf/render/amp-iframe' => 'webperf/render/amp-iframe',
461
            // Tables
462
            '/webperf/tables/dashboard' => 'webperf/tables/dashboard',
463
            '/webperf/tables/redirects' => 'webperf/tables/redirects',
464
            // Charts
465
            '/webperf/charts/dashboard-stats-average/<days:\d+>/<column:{handle}>'
466
            => 'webperf/charts/dashboard-stats-average',
467
            '/webperf/charts/dashboard-stats-average/<days:\d+>/<column:{handle}>/<siteId:\d+>'
468
            => 'webperf/charts/dashboard-stats-average',
469
            '/webperf/charts/dashboard-slowest-pages/<days:\d+>/<column:{handle}>/<limit:\d+>'
470
            => 'webperf/charts/dashboard-slowest-pages',
471
            '/webperf/charts/dashboard-slowest-pages/<days:\d+>/<column:{handle}>/<limit:\d+>/<siteId:\d+>'
472
            => 'webperf/charts/dashboard-slowest-pages',
473
            '/webperf/charts/widget/<days>' => 'webperf/charts/widget',
474
        ];
475
    }
476
    /**
477
     * Return the custom Control Panel routes
478
     *
479
     * @return array
480
     */
481
    protected function customAdminCpRoutes(): array
482
    {
483
        return [
484
            'webperf' => 'webperf/sections/dashboard',
485
            'webperf/dashboard' => 'webperf/sections/dashboard',
486
            'webperf/dashboard/<siteHandle:{handle}>' => 'webperf/sections/dashboard',
487
488
            'webperf/pages' => 'webperf/sections/pages-index',
489
            'webperf/pages/<siteHandle:{handle}>' => 'webperf/sections/pages-index',
490
491
            'webperf/settings' => 'webperf/settings/plugin-settings',
492
        ];
493
    }
494
495
    /**
496
     * Returns the custom Control Panel user permissions.
497
     *
498
     * @return array
499
     */
500
    protected function customAdminCpPermissions(): array
501
    {
502
        return [
503
            'webperf:dashboard' => [
504
                'label' => Craft::t('webperf', 'Dashboard'),
505
            ],
506
            'webperf:pages' => [
507
                'label' => Craft::t('webperf', 'Pages'),
508
            ],
509
            'webperf:settings' => [
510
                'label' => Craft::t('webperf', 'Settings'),
511
            ],
512
        ];
513
    }
514
}
515