Completed
Push — master ( b12456...51f5d4 )
by Donata
02:29 queued 49s
created

VideoBlock::getBetterButtonsActions()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
dl 9
loc 9
rs 9.2
c 0
b 0
f 0
cc 4
eloc 5
nc 2
nop 0
1
<?php
2
3
/**
4
 * @author    Donatas Navidonskis <[email protected]>
5
 * @since     2017
6
 * @class     VideoBlock
7
 *
8
 * @property int     CoverID
9
 * @property int     Mp4ID
10
 * @property int     WebMID
11
 * @property int     OggID
12
 * @property string  Type
13
 * @property string  URL
14
 * @property boolean AutoPlay
15
 *
16
 * @method File Mp4
17
 * @method File WebM
18
 * @method File Ogg
19
 * @method Image Cover
20
 */
21
class VideoBlock extends BaseBlock {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
22
23
    /**
24
     * @var array
25
     * @config
26
     */
27
    private static $db = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
28
        'Type'     => 'Enum(array("Youtube", "Vimeo", "File"), "File")',
29
        'URL'      => 'Varchar(1024)',
30
        'AutoPlay' => 'Boolean(true)',
31
    ];
32
33
    /**
34
     * @var array
35
     * @config
36
     */
37
    private static $has_one = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
38
        'Mp4'   => 'File',
39
        'WebM'  => 'File',
40
        'Ogg'   => 'File',
41
        'Cover' => 'Image',
42
    ];
43
44
    /**
45
     * Allow to call those functions.
46
     *
47
     * @var array
48
     * @config
49
     */
50
    private static $better_buttons_actions = [
51
        'fetchVideosPicture'
52
    ];
53
54
    /**
55
     * Load javascript plugin to load all block features. Set to false
56
     * and add yours. This will load /assets/javascript/video-block.js file.
57
     *
58
     * @var bool
59
     * @config
60
     */
61
    private static $load_javascript_plugin = true;
0 ignored issues
show
Unused Code introduced by
The property $load_javascript_plugin is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
62
63
    /**
64
     * If the singular name is set in a private static $singular_name, it cannot be changed using the translation files
65
     * for some reason. Fix it by defining a method that handles the translation.
66
     * @return string
67
     */
68
    public function singular_name() {
69
        return _t('VideoBlock.SINGULARNAME', 'Video Block');
70
    }
71
72
    /**
73
     * If the plural name is set in a private static $plural_name, it cannot be changed using the translation files
74
     * for some reason. Fix it by defining a method that handles the translation.
75
     * @return string
76
     */
77
    public function plural_name() {
78
        return _t('VideoBlock.PLURALNAME', 'Video Blocks');
79
    }
80
81
    /**
82
     * @return string
83
     */
84
    public function getVideoType() {
85
        return strtolower($this->Type);
86
    }
87
88
    /**
89
     * @return array
90
     */
91 View Code Duplication
    public function getVideoTypes() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
92
        $types = [];
93
94
        foreach ($this->dbObject('Type')->enumValues() as $type) {
95
            $types[$type] = $this->fieldLabel($type);
96
        }
97
98
        return $types;
99
    }
100
101
    /**
102
     * @return FieldList
103
     */
104 View Code Duplication
    public function getCMSFields() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
        $fields = parent::getCMSFields();
106
        $fields->removeByName(['Type', 'Mp4', 'WebM', 'Ogg', 'URL', 'AutoPlay', 'Cover', 'Content']);
107
        $fields->findOrMakeTab('Root.Media', $this->fieldLabel('Media'));
108
109
        $fields->addFieldsToTab('Root.Media', [
110
            $coverField = UploadField::create('Cover', $this->fieldLabel('Cover')),
111
            DropdownField::create('AutoPlay', $this->fieldLabel('TurnOnAutoPlayMode'), BlocksUtility::localized_answers()),
112
            $videoType = OptionsetField::create('Type', $this->fieldLabel('Type'), $this->getVideoTypes(), 'File'),
113
            $uploadFieldContainer = DisplayLogicWrapper::create(
114
                $mp4UploadField = UploadField::create('Mp4', $this->fieldLabel('VideoMp4')),
115
                $webMUploadField = UploadField::create('WebM', $this->fieldLabel('VideoWebM')),
116
                $oggUploadField = UploadField::create('Ogg', $this->fieldLabel('VideoOgg'))
117
            ),
118
            $urlAddressField = TextField::create('URL', $this->fieldLabel('URLAddress'))->setRightTitle(
119
                $this->fieldLabel('SetVideoURLAddress')
120
            ),
121
        ]);
122
123
        $coverField
124
            ->setAllowedMaxFileNumber(1)
125
            ->setAllowedFileCategories('image')
126
            ->setRightTitle(
127
                _t('VideoSliderItem.SET_VIDEO_COVER_IMAGE', 'Set video cover image')
128
            )->setFolderName(sprintf('%s/covers', BaseBlock::config()->upload_directory));
129
130
        $mp4UploadField
131
            ->setAllowedMaxFileNumber(1)
132
            ->setAllowedExtensions('mp4')
0 ignored issues
show
Documentation introduced by
'mp4' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
133
            ->setRightTitle(
134
                _t('VideoSliderItem.ALLOWED_FILE_EXTENSIONS', 'Allowed file extensions: {extensions}', [
0 ignored issues
show
Documentation introduced by
array('extensions' => '.mp4') is of type array<string,string,{"extensions":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
135
                    'extensions' => '.mp4',
136
                ])
137
            )->setFolderName(sprintf('%s/videos', BaseBlock::config()->upload_directory));
138
139
        $webMUploadField
140
            ->setAllowedMaxFileNumber(1)
141
            ->setAllowedExtensions('webm')
0 ignored issues
show
Documentation introduced by
'webm' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
142
            ->setRightTitle(
143
                _t('VideoSliderItem.ALLOWED_FILE_EXTENSIONS', 'Allowed file extensions: {extensions}', [
0 ignored issues
show
Documentation introduced by
array('extensions' => '.webm') is of type array<string,string,{"extensions":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
                    'extensions' => '.webm',
145
                ])
146
            )->setFolderName(sprintf('%s/videos', BaseBlock::config()->upload_directory));
147
148
        $oggUploadField
149
            ->setAllowedMaxFileNumber(1)
150
            ->setAllowedExtensions('ogg')
0 ignored issues
show
Documentation introduced by
'ogg' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
            ->setRightTitle(
152
                _t('VideoSliderItem.ALLOWED_FILE_EXTENSIONS', 'Allowed file extensions: {extensions}', [
0 ignored issues
show
Documentation introduced by
array('extensions' => '.ogg') is of type array<string,string,{"extensions":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
153
                    'extensions' => '.ogg',
154
                ])
155
            )->setFolderName(sprintf('%s/videos', BaseBlock::config()->upload_directory));
156
157
        $uploadFieldContainer->displayIf('Type')->isEqualTo('File');
158
        $urlAddressField->displayIf('Type')->isNotEqualTo('File');
159
160
        $this->extend('updateCMSFields', $fields);
161
162
        return $fields;
163
    }
164
165
    /**
166
     * @param bool $includeRelations
167
     *
168
     * @return array
169
     */
170
    public function fieldLabels($includeRelations = true) {
171
        return array_merge(parent::fieldLabels($includeRelations), VideoSliderItem::labels());
172
    }
173
174
    /**
175
     * This will get an id of the URL address or false
176
     * if can't parsed, object type not one of supported
177
     * providers or just empty url address field.
178
     *
179
     * @return string|false
180
     * @throws ProviderNotFound
181
     */
182 View Code Duplication
    public function getVideoId() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
        if (! empty($this->URL) && $this->Type != 'File') {
184
            $videoId = BlocksUtility::parse_video_id($this->URL, $this->Type);
185
186
            return $videoId;
187
        }
188
189
        return false;
190
    }
191
192
    /**
193
     * Get embed link by the set of Type field. Method depends by
194
     * VideoSliderItem::$embed_links property.
195
     *
196
     * @return bool|string
197
     */
198 View Code Duplication
    public function getEmbedLink() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
199
        if (! empty($this->URL) && $this->Type != 'File') {
200
            try {
201
                $videoId = BlocksUtility::parse_video_id($this->URL, $this->Type);
202
            } catch (ProviderNotFound $ex) {
203
                return false;
204
            }
205
206
            if ($videoId && array_key_exists($this->Type, ($options = VideoSliderItem::config()->embed_links))) {
207
                $options = $options[$this->Type];
208
                $autoPlay = array_key_exists("AutoPlay", $options) && ! empty($options["AutoPlay"]) ? $options["AutoPlay"] : '';
209
210
                return str_replace(
211
                    ['{VideoId}', '{AutoPlay}'],
212
                    [$videoId, $autoPlay],
213
                    $options["Link"]
214
                );
215
            }
216
        }
217
218
        return false;
219
    }
220
221
    /**
222
     * @return \ValidationResult
223
     */
224 View Code Duplication
    protected function validate() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225
        $validation = parent::validate();
226
227
        if (! empty($this->URL) && $this->Type != 'File') {
228
            try {
229
                $result = $this->getVideoId();
230
            } catch (ProviderNotFound $ex) {
231
                $validation->error($ex->getMessage());
232
233
                return $validation;
234
            }
235
236
            // if we can't parse url address, return an error with bad url address or
237
            // the type is not of the url address providers.
238
            if (! $result) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $result of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
239
                $validation->error(_t('VideoSliderItem.INVALID_URL_ADDRESS_OR_THE_TYPE', 'Invalid URL address or the type'));
240
            }
241
        }
242
243
        return $validation;
244
    }
245
246
    /**
247
     * @return Image|false
248
     */
249
    public function getCoverImage() {
250
        if ($this->Cover()->exists()) {
0 ignored issues
show
Documentation Bug introduced by
The method Cover does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
251
            return $this->Cover();
0 ignored issues
show
Documentation Bug introduced by
The method Cover does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
252
        }
253
254
        return false;
255
    }
256
257
    /**
258
     * Creating a button to fetch videos picture if cover image not exists.
259
     *
260
     * @return FieldList
261
     */
262 View Code Duplication
    public function getBetterButtonsActions() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
263
        $fields = parent::getBetterButtonsActions();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class BaseBlock as the method getBetterButtonsActions() does only exist in the following sub-classes of BaseBlock: VideoBlock. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
264
265
        if ($this->Type != 'File' && ! $this->Cover()->exists() && ! empty($this->URL)) {
0 ignored issues
show
Documentation Bug introduced by
The method Cover does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
266
            $fields->push(BetterButtonCustomAction::create('fetchVideosPicture', _t('VideoSliderItem.FETCH_VIDEOS_PICTURE', 'Fetch videos picture')));
267
        }
268
269
        return $fields;
270
    }
271
272
    /**
273
     * @return bool|string
274
     */
275 View Code Duplication
    public function getMp4VideoUrl() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
276
        $file = $this->Mp4();
0 ignored issues
show
Documentation Bug introduced by
The method Mp4 does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
277
278
        if (! ($file instanceof File) || ! $file->exists()) {
279
            return false;
280
        }
281
282
        return $file->getAbsoluteURL();
283
    }
284
285
    /**
286
     * @return bool|string
287
     */
288 View Code Duplication
    public function getWebMVideoUrl() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
289
        $file = $this->WebM();
0 ignored issues
show
Documentation Bug introduced by
The method WebM does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
290
291
        if (! ($file instanceof File) || ! $file->exists()) {
292
            return false;
293
        }
294
295
        return $file->getAbsoluteURL();
296
    }
297
298
    /**
299
     * @return bool|string
300
     */
301 View Code Duplication
    public function getOggVideoUrl() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
302
        $file = $this->Ogg();
0 ignored issues
show
Documentation Bug introduced by
The method Ogg does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
303
304
        if (! ($file instanceof File) || ! $file->exists()) {
305
            return false;
306
        }
307
308
        return $file->getAbsoluteURL();
309
    }
310
311
    /**
312
     * Fetching/downloading picture from the providers url address and
313
     * saving as Image object.
314
     *
315
     * @return false
316
     */
317
    public function fetchVideosPicture() {
318
        try {
319
            $videoId = $this->getVideoId();
320
        } catch (ProviderNotFound $ex) {
321
            return false;
322
        }
323
324
        $directoryPath = sprintf("%s/Sliders", BaseBlock::config()->upload_directory);
325
        $folder = Folder::find_or_make($directoryPath);
326
327
        if (empty($this->URL)) {
328
            return false;
329
        }
330
331
        $title = ! empty($this->Title) ? FileNameFilter::create()->filter($this->Title)."-{$this->ID}" : "video-{$this->ID}";
332
        $fileName = strtolower(sprintf("%s.jpg", $title));
333
        $baseFolder = Director::baseFolder()."/".$folder->getFilename();
334
        $type = strtolower($this->Type);
335
        $fileContent = file_get_contents(str_replace('{VideoId}', $videoId, VideoSliderItem::config()->thumbnail_links[$type]));
336
337
        switch ($type) {
338
            case 'vimeo':
339
                $fileContent = unserialize($fileContent);
340
                $fileContent = file_get_contents($fileContent[0]['thumbnail_large']);
341
                break;
342
            case 'file':
343
                // get picture from video (via ffmpeg)
344
                if ($this->Mp4()->exists() && ($fileUrl = $this->getMp4VideoUrl())) {
0 ignored issues
show
Documentation Bug introduced by
The method Mp4 does not exist on object<VideoBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
345
346
                }
347
348
                break;
349
        }
350
351 View Code Duplication
        if ($fileContent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
352
            if (file_put_contents($absoluteFileName = ($baseFolder.$fileName), $fileContent)) {
353
                $image = Image::create([
354
                    "Filename" => $folder->getFilename().$fileName,
355
                    "Title"    => $this->Title,
356
                    "Name"     => $fileName,
357
                    "ParentID" => $folder->ID,
358
                    "OwnerID"  => Member::currentUserID(),
359
                ]);
360
361
                if ($image->write()) {
362
                    $this->CoverID = $image->ID;
363
                    $this->write();
364
                }
365
            }
366
        }
367
    }
368
369
    public function getVideoOptions() {
370
        $options = [];
371
372
        if ($this->Type == 'File') {
373
            $options = [
374
                'videoTypes' => [
375
                    'mp4'  => $this->getMp4VideoUrl(),
376
                    'webm' => $this->getWebMVideoUrl(),
377
                    'ogg'  => $this->getOggVideoUrl(),
378
                ],
379
            ];
380
        } else {
381
            $options['embed'] = $this->getEmbedLink();
382
        }
383
384
        $options = array_merge([
385
            'autoPlay'   => (boolean) $this->AutoPlay,
386
            'type'       => $this->getVideoType(),
387
            'coverImage' => (($cover = $this->getCoverImage()) ? $cover->getAbsoluteURL() : false),
388
        ], $options);
389
390
        return Convert::raw2att(Convert::array2json($options));
391
    }
392
393
}
394
395
class VideoBlock_Controller extends Block_Controller {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
396
397
    public function init() {
398
        if (VideoBlock::config()->load_javascript_plugin) {
399
            Requirements::javascript(CONTENT_BLOCKS_DIR."/assets/javascript/video-block.js");
400
        }
401
402
        parent::init();
403
    }
404
405
}