Passed
Branch v1 (0c7460)
by Andrew
06:14
created

Transcoder::customFrontendRoutes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Transcoder plugin for Craft CMS 3.x
4
 *
5
 * Transcode videos to various formats, and provide thumbnails of the video
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) 2017 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\transcoder;
12
13
use nystudio107\transcoder\services\Transcode;
14
use nystudio107\transcoder\variables\TranscoderVariable;
15
use nystudio107\transcoder\models\Settings;
16
17
use Craft;
18
use craft\base\Plugin;
19
use craft\console\Application as ConsoleApplication;
20
use craft\elements\Asset;
21
use craft\events\AssetThumbEvent;
22
use craft\events\PluginEvent;
23
use craft\events\RegisterUrlRulesEvent;
24
use craft\events\RegisterCacheOptionsEvent;
25
use craft\helpers\Assets as AssetsHelper;
26
use craft\helpers\FileHelper;
27
use craft\helpers\UrlHelper;
28
use craft\services\Assets;
29
use craft\services\Plugins;
30
use craft\utilities\ClearCaches;
31
use craft\web\twig\variables\CraftVariable;
32
use craft\web\UrlManager;
33
34
use yii\base\ErrorException;
35
use yii\base\Event;
36
use yii\base\InvalidArgumentException;
37
38
/**
39
 * Class Transcode
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   Transcode
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  Transcode $transcode
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 2
Loading history...
46
 */
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...
47
class Transcoder extends Plugin
48
{
49
    // Static Properties
50
    // =========================================================================
51
52
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
53
     * @var Transcoder
54
     */
55
    public static $plugin;
56
57
    // Public Methods
58
    // =========================================================================
59
60
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
61
     * @inheritdoc
62
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
63
    public function init()
64
    {
65
        parent::init();
66
        self::$plugin = $this;
67
        // Handle console commands
68
        if (Craft::$app instanceof ConsoleApplication) {
69
            $this->controllerNamespace = 'nystudio107\transcoder\console\controllers';
70
        }
71
        // Add in our Craft components
72
        $this->addComponents();
73
        // Install our global event handlers
74
        $this->installEventHandlers();
75
        // We've loaded!
76
        Craft::info(
77
            Craft::t(
78
                'transcoder',
79
                '{name} plugin loaded',
80
                ['name' => $this->name]
81
            ),
82
            __METHOD__
83
        );
84
    }
85
86
    /**
87
     * Clear all the caches!
88
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
89
    public function clearAllCaches()
90
    {
91
        $transcoderPaths = Transcoder::$plugin->getSettings()->transcoderPaths;
92
        foreach ($transcoderPaths as $key => $value) {
93
            $dir = Craft::getAlias($value);
94
            try {
95
                FileHelper::clearDirectory($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type boolean; however, parameter $dir of craft\helpers\FileHelper::clearDirectory() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

95
                FileHelper::clearDirectory(/** @scrutinizer ignore-type */ $dir);
Loading history...
96
                Craft::info(
97
                    Craft::t(
98
                        'transcoder',
99
                        '{name} cache directory cleared',
100
                        ['name' => $key]
101
                    ),
102
                    __METHOD__
103
                );
104
            } catch (ErrorException $e) {
105
                // the directory doesn't exist
106
                Craft::error($e->getMessage(), __METHOD__);
107
            }
108
        }
109
    }
110
111
    // Protected Methods
112
    // =========================================================================
113
114
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
115
     * @inheritdoc
116
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
117
    protected function createSettingsModel()
118
    {
119
        return new Settings();
120
    }
121
122
    /**
123
     * Add in our Craft components
124
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
125
    protected function addComponents()
126
    {
127
        // Register our variables
128
        Event::on(
129
            CraftVariable::class,
130
            CraftVariable::EVENT_INIT,
131
            function (Event $event) {
132
                /** @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...
133
                $variable = $event->sender;
134
                $variable->set('transcoder', TranscoderVariable::class);
135
            }
136
        );
137
    }
138
139
    /**
140
     * Install our event handlers
141
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
142
    protected function installEventHandlers()
143
    {
144
        // Handler: Assets::EVENT_GET_THUMB_PATH
145
        Event::on(
146
            Assets::class,
147
            Assets::EVENT_GET_THUMB_PATH,
148
            function (AssetThumbEvent $event) {
149
                Craft::debug(
150
                    'Assets::EVENT_GET_THUMB_PATH',
151
                    __METHOD__
152
                );
153
                /** @var Asset $asset */
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...
154
                $asset = $event->asset;
155
                if (AssetsHelper::getFileKindByExtension($asset->filename) === Asset::KIND_VIDEO) {
0 ignored issues
show
Bug introduced by
It seems like $asset->filename can also be of type null; however, parameter $file of craft\helpers\Assets::getFileKindByExtension() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

155
                if (AssetsHelper::getFileKindByExtension(/** @scrutinizer ignore-type */ $asset->filename) === Asset::KIND_VIDEO) {
Loading history...
156
                    $event->path = Transcoder::$plugin->transcode->handleGetAssetThumbPath($event);
157
                }
158
            }
159
        );
160
        // Add the Transcode path to the list of things the Clear Caches tool can delete.
161
        Event::on(
162
            ClearCaches::class,
163
            ClearCaches::EVENT_REGISTER_CACHE_OPTIONS,
164
            function (RegisterCacheOptionsEvent $event) {
165
                $event->options[] = [
166
                    'key' => 'transcoder',
167
                    'label' => Craft::t('transcoder', 'Transcoder caches'),
168
                    'action' => [$this, 'clearAllCaches']
169
                ];
170
            }
171
        );
172
        // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN
173
        Event::on(
174
            Plugins::class,
175
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
176
            function (PluginEvent $event) {
177
                if ($event->plugin === $this) {
178
                    $request = Craft::$app->getRequest();
179
                    if ($request->isCpRequest) {
180
                        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('transcoder/welcome'))->send();
181
                    }
182
                }
183
            }
184
        );
185
        $request = Craft::$app->getRequest();
186
        // Install only for non-console site requests
187
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
188
            $this->installSiteEventListeners();
189
        }
190
    }
191
192
    /**
193
     * Install site event listeners for site requests only
194
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
195
    protected function installSiteEventListeners()
196
    {
197
        // Handler: UrlManager::EVENT_REGISTER_SITE_URL_RULES
198
        Event::on(
199
            UrlManager::class,
200
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
201
            function (RegisterUrlRulesEvent $event) {
202
                Craft::debug(
203
                    'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
204
                    __METHOD__
205
                );
206
                // Register our AdminCP routes
207
                $event->rules = array_merge(
208
                    $event->rules,
209
                    $this->customFrontendRoutes()
210
                );
211
            }
212
        );
213
    }
214
215
    /**
216
     * Return the custom frontend routes
217
     *
218
     * @return array
219
     */
220
    protected function customFrontendRoutes(): array
221
    {
222
        return [
223
            // Make webpack async bundle loading work out of published AssetBundles
224
            '/cpresources/transcoder/<resourceType:{handle}>/<fileName>' => 'transcoder/cp-nav/resource',
225
        ];
226
    }
227
}
228