Transcoder::installSiteEventListeners()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nc 1
nop 0
dl 0
loc 15
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * Transcoder plugin for Craft CMS
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 Craft;
14
use craft\base\Model;
15
use craft\base\Plugin;
16
use craft\console\Application as ConsoleApplication;
17
use craft\elements\Asset;
0 ignored issues
show
Bug introduced by
The type craft\elements\Asset 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...
18
use craft\events\DefineAssetThumbUrlEvent;
19
use craft\events\PluginEvent;
20
use craft\events\RegisterCacheOptionsEvent;
21
use craft\events\RegisterUrlRulesEvent;
22
use craft\helpers\Assets as AssetsHelper;
23
use craft\helpers\FileHelper;
24
use craft\helpers\UrlHelper;
25
use craft\services\Assets;
26
use craft\services\Plugins;
27
use craft\utilities\ClearCaches;
28
use craft\web\twig\variables\CraftVariable;
29
use craft\web\UrlManager;
30
use nystudio107\transcoder\models\Settings;
31
use nystudio107\transcoder\services\ServicesTrait;
32
use nystudio107\transcoder\variables\TranscoderVariable;
33
use yii\base\ErrorException;
34
use yii\base\Event;
35
36
/**
37
 * Class Transcode
38
 *
39
 * @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...
40
 * @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...
41
 * @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...
42
 * @method Settings getSettings()
0 ignored issues
show
Coding Style introduced by
Tag value for @method tag indented incorrectly; expected 2 spaces but found 1
Loading history...
43
 */
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...
44
class Transcoder extends Plugin
45
{
46
    // Traits
47
    // =========================================================================
48
49
    use ServicesTrait;
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 null|Transcoder
56
     */
57
    public static ?Transcoder $plugin;
58
59
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
60
     * @var null|Settings
61
     */
62
    public static ?Settings $settings;
63
64
    // Public Properties
65
    // =========================================================================
66
67
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
68
     * @var bool
69
     */
70
    public bool $hasCpSection = false;
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @var bool
74
     */
75
    public bool $hasCpSettings = false;
76
77
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
78
     * @var string
79
     */
80
    public string $schemaVersion = '1.0.0';
81
82
    // Public Methods
83
    // =========================================================================
84
85
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
86
     * @inheritdoc
87
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
88
    public function init(): void
89
    {
90
        parent::init();
91
        self::$plugin = $this;
92
        // Initialize properties
93
        self::$settings = self::$plugin->getSettings();
94
        // Handle console commands
95
        if (Craft::$app instanceof ConsoleApplication) {
96
            $this->controllerNamespace = 'nystudio107\transcoder\console\controllers';
97
        }
98
        // Add in our Craft components
99
        $this->addComponents();
100
        // Install our global event handlers
101
        $this->installEventHandlers();
102
        // We've loaded!
103
        Craft::info(
104
            Craft::t(
105
                'transcoder',
106
                '{name} plugin loaded',
107
                ['name' => $this->name]
108
            ),
109
            __METHOD__
110
        );
111
    }
112
113
    /**
114
     * Clear all the caches!
115
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
116
    public function clearAllCaches(): void
117
    {
118
        $transcoderPaths = self::$plugin->getSettings()->transcoderPaths;
0 ignored issues
show
Bug introduced by
The method getSettings() does not exist on null. ( Ignorable by Annotation )

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

118
        $transcoderPaths = self::$plugin->/** @scrutinizer ignore-call */ getSettings()->transcoderPaths;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
119
120
        foreach ($transcoderPaths as $key => $value) {
121
            $dir = Craft::parseEnv($value);
0 ignored issues
show
Deprecated Code introduced by
The function Craft::parseEnv() has been deprecated: in 3.7.29. [[App::parseEnv()]] should be used instead. ( Ignorable by Annotation )

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

121
            $dir = /** @scrutinizer ignore-deprecated */ Craft::parseEnv($value);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
122
            try {
123
                FileHelper::clearDirectory($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type 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

123
                FileHelper::clearDirectory(/** @scrutinizer ignore-type */ $dir);
Loading history...
124
                Craft::info(
125
                    Craft::t(
126
                        'transcoder',
127
                        '{name} cache directory cleared',
128
                        ['name' => $key]
129
                    ),
130
                    __METHOD__
131
                );
132
            } catch (ErrorException $e) {
133
                // the directory doesn't exist
134
                Craft::error($e->getMessage(), __METHOD__);
135
            }
136
        }
137
    }
138
139
    // Protected Methods
140
    // =========================================================================
141
142
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
143
     * @inheritdoc
144
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
145
    protected function createSettingsModel(): ?Model
146
    {
147
        return new Settings();
148
    }
149
150
    /**
151
     * Add in our Craft components
152
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
153
    protected function addComponents(): void
154
    {
155
        // Register our variables
156
        Event::on(
157
            CraftVariable::class,
158
            CraftVariable::EVENT_INIT,
159
            function(Event $event) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
160
                /** @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...
161
                $variable = $event->sender;
162
                $variable->set('transcoder', [
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...
163
                    'class' => TranscoderVariable::class,
164
                    'viteService' => $this->vite,
165
                ]);
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...
166
            }
167
        );
168
    }
169
170
    /**
171
     * Install our event handlers
172
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
173
    protected function installEventHandlers(): void
174
    {
175
        $settings = $this->getSettings();
176
        // Handler: Assets::EVENT_GET_THUMB_PATH
177
        Event::on(
178
            Assets::class,
179
            Assets::EVENT_DEFINE_THUMB_URL,
180
            static function(DefineAssetThumbUrlEvent $event) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
181
                Craft::debug(
182
                    'Assets::EVENT_GET_THUMB_PATH',
183
                    __METHOD__
184
                );
185
                $asset = $event->asset;
186
                if (AssetsHelper::getFileKindByExtension($asset->filename) === Asset::KIND_VIDEO) {
187
                    $path = Transcoder::$plugin->transcode->handleGetAssetThumbPath($event);
188
                    if (!empty($path)) {
189
                        $event->url = $path;
190
                    }
191
                }
192
            }
193
        );
194
        if ($settings->clearCaches) {
195
            // Add the Transcoded path to the list of things the Clear Caches tool can delete.
196
            Event::on(
197
                ClearCaches::class,
198
                ClearCaches::EVENT_REGISTER_CACHE_OPTIONS,
199
                function(RegisterCacheOptionsEvent $event) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
200
                    $event->options[] = [
201
                        'key' => 'transcoder',
202
                        'label' => Craft::t('transcoder', 'Transcoder caches'),
203
                        'action' => [$this, 'clearAllCaches'],
204
                    ];
205
                }
206
            );
207
        }
208
        // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN
209
        Event::on(
210
            Plugins::class,
211
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
212
            function(PluginEvent $event) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
213
                if ($event->plugin === $this) {
0 ignored issues
show
introduced by
The condition $event->plugin === $this is always false.
Loading history...
214
                    $request = Craft::$app->getRequest();
215
                    if ($request->isCpRequest) {
216
                        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('transcoder/welcome'))->send();
217
                    }
218
                }
219
            }
220
        );
221
        $request = Craft::$app->getRequest();
222
        // Install only for non-console site requests
223
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
224
            $this->installSiteEventListeners();
225
        }
226
    }
227
228
    /**
229
     * Install site event listeners for site requests only
230
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
231
    protected function installSiteEventListeners(): void
232
    {
233
        // Handler: UrlManager::EVENT_REGISTER_SITE_URL_RULES
234
        Event::on(
235
            UrlManager::class,
236
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
237
            function(RegisterUrlRulesEvent $event) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
238
                Craft::debug(
239
                    'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
240
                    __METHOD__
241
                );
242
                // Register our Control Panel routes
243
                $event->rules = array_merge(
244
                    $event->rules,
245
                    $this->customFrontendRoutes()
246
                );
247
            }
248
        );
249
    }
250
251
    /**
252
     * Return the custom frontend routes
253
     *
254
     * @return array
255
     */
256
    protected function customFrontendRoutes(): array
257
    {
258
        return [
259
        ];
260
    }
261
}
262