Passed
Push — develop ( da884c...389d86 )
by Andrew
04:32
created

Transcoder::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
cc 2
eloc 13
c 6
b 0
f 1
nc 2
nop 0
dl 0
loc 22
rs 9.8333
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
37
/**
38
 * Class Transcode
39
 *
40
 * @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 for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
41
 * @package   Transcode
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
42
 * @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 for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
43
 *
44
 * @property  Transcode $transcode
0 ignored issues
show
Coding Style introduced by
Tag value for @property tag indented incorrectly; expected 1 spaces but found 2
Loading history...
45
 * @property Settings   $settings
46
 * @method   Settings   getSettings()
47
 */
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...
48
class Transcoder extends Plugin
49
{
50
    // Static Properties
51
    // =========================================================================
52
53
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
54
     * @var Transcoder
55
     */
56
    public static $plugin;
57
58
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
59
     * @var Settings
60
     */
61
    public static $settings;
62
63
    // Public Methods
64
    // =========================================================================
65
66
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
67
     * @inheritdoc
68
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
69
    public function init()
70
    {
71
        parent::init();
72
        self::$plugin = $this;
73
        // Initialize properties
74
        self::$settings = self::$plugin->getSettings();
75
        // Handle console commands
76
        if (Craft::$app instanceof ConsoleApplication) {
77
            $this->controllerNamespace = 'nystudio107\transcoder\console\controllers';
78
        }
79
        // Add in our Craft components
80
        $this->addComponents();
81
        // Install our global event handlers
82
        $this->installEventHandlers();
83
        // We've loaded!
84
        Craft::info(
85
            Craft::t(
86
                'transcoder',
87
                '{name} plugin loaded',
88
                ['name' => $this->name]
89
            ),
90
            __METHOD__
91
        );
92
    }
93
94
    /**
95
     * Clear all the caches!
96
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
97
    public function clearAllCaches()
98
    {
99
        $transcoderPaths = self::$plugin->getSettings()->transcoderPaths;
100
101
        foreach ($transcoderPaths as $key => $value) {
102
            $dir = Craft::parseEnv($value);
103
            try {
104
                FileHelper::clearDirectory($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type boolean and null; 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

104
                FileHelper::clearDirectory(/** @scrutinizer ignore-type */ $dir);
Loading history...
105
                Craft::info(
106
                    Craft::t(
107
                        'transcoder',
108
                        '{name} cache directory cleared',
109
                        ['name' => $key]
110
                    ),
111
                    __METHOD__
112
                );
113
            } catch (ErrorException $e) {
114
                // the directory doesn't exist
115
                Craft::error($e->getMessage(), __METHOD__);
116
            }
117
        }
118
    }
119
120
    // Protected Methods
121
    // =========================================================================
122
123
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
124
     * @inheritdoc
125
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
126
    protected function createSettingsModel()
127
    {
128
        return new Settings();
129
    }
130
131
    /**
132
     * Add in our Craft components
133
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
134
    protected function addComponents()
135
    {
136
        // Register our variables
137
        Event::on(
138
            CraftVariable::class,
139
            CraftVariable::EVENT_INIT,
140
            function (Event $event) {
141
                /** @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...
142
                $variable = $event->sender;
143
                $variable->set('transcoder', TranscoderVariable::class);
144
            }
145
        );
146
    }
147
148
    /**
149
     * Install our event handlers
150
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
151
    protected function installEventHandlers()
152
    {
153
        $settings = $this->getSettings();
154
        // Handler: Assets::EVENT_GET_THUMB_PATH
155
        Event::on(
156
            Assets::class,
157
            Assets::EVENT_GET_THUMB_PATH,
158
            function (AssetThumbEvent $event) {
159
                Craft::debug(
160
                    'Assets::EVENT_GET_THUMB_PATH',
161
                    __METHOD__
162
                );
163
                /** @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...
164
                $asset = $event->asset;
165
                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

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