Completed
Push — master ( 5543da...b12456 )
by Donata
02:40
created

VideoBlock   F

Complexity

Total Complexity 58

Size/Duplication

Total Lines 402
Duplicated Lines 41.54 %

Coupling/Cohesion

Components 2
Dependencies 21

Importance

Changes 0
Metric Value
wmc 58
lcom 2
cbo 21
dl 167
loc 402
rs 1.9075
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A singular_name() 0 3 1
A plural_name() 0 3 1
A getVideoType() 0 3 1
A getVideoTypes() 9 9 2
A getCMSFields() 60 60 1
A fieldLabels() 0 3 1
A getVideoId() 9 9 3
C getEmbedLink() 22 22 8
B validate() 21 21 5
A getCoverImage() 0 7 2
B getBetterButtonsActions() 3 15 9
A getMp4VideoUrl() 9 9 3
A getWebMVideoUrl() 9 9 3
A getOggVideoUrl() 9 9 3
C fetchVideosPicture() 16 51 11
A renderVideo() 0 21 1
A getVideoOptions() 0 23 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like VideoBlock often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use VideoBlock, and based on these observations, apply Extract Interface, too.

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 = [
0 ignored issues
show
Unused Code introduced by
The property $better_buttons_actions 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...
51
        'fetchVideosPicture',
52
        'renderVideo'
53
    ];
54
55
    /**
56
     * Load javascript plugin to load all block features. Set to false
57
     * and add yours. This will load /assets/javascript/video-block.js file.
58
     *
59
     * @var bool
60
     * @config
61
     */
62
    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...
63
64
    /**
65
     * If the singular name is set in a private static $singular_name, it cannot be changed using the translation files
66
     * for some reason. Fix it by defining a method that handles the translation.
67
     * @return string
68
     */
69
    public function singular_name() {
70
        return _t('VideoBlock.SINGULARNAME', 'Video Block');
71
    }
72
73
    /**
74
     * If the plural name is set in a private static $plural_name, it cannot be changed using the translation files
75
     * for some reason. Fix it by defining a method that handles the translation.
76
     * @return string
77
     */
78
    public function plural_name() {
79
        return _t('VideoBlock.PLURALNAME', 'Video Blocks');
80
    }
81
82
    /**
83
     * @return string
84
     */
85
    public function getVideoType() {
86
        return strtolower($this->Type);
87
    }
88
89
    /**
90
     * @return array
91
     */
92 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...
93
        $types = [];
94
95
        foreach ($this->dbObject('Type')->enumValues() as $type) {
96
            $types[$type] = $this->fieldLabel($type);
97
        }
98
99
        return $types;
100
    }
101
102
    /**
103
     * @return FieldList
104
     */
105 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...
106
        $fields = parent::getCMSFields();
107
        $fields->removeByName(['Type', 'Mp4', 'WebM', 'Ogg', 'URL', 'AutoPlay', 'Cover', 'Content']);
108
        $fields->findOrMakeTab('Root.Media', $this->fieldLabel('Media'));
109
110
        $fields->addFieldsToTab('Root.Media', [
111
            $coverField = UploadField::create('Cover', $this->fieldLabel('Cover')),
112
            DropdownField::create('AutoPlay', $this->fieldLabel('TurnOnAutoPlayMode'), BlocksUtility::localized_answers()),
113
            $videoType = OptionsetField::create('Type', $this->fieldLabel('Type'), $this->getVideoTypes(), 'File'),
114
            $uploadFieldContainer = DisplayLogicWrapper::create(
115
                $mp4UploadField = UploadField::create('Mp4', $this->fieldLabel('VideoMp4')),
116
                $webMUploadField = UploadField::create('WebM', $this->fieldLabel('VideoWebM')),
117
                $oggUploadField = UploadField::create('Ogg', $this->fieldLabel('VideoOgg'))
118
            ),
119
            $urlAddressField = TextField::create('URL', $this->fieldLabel('URLAddress'))->setRightTitle(
120
                $this->fieldLabel('SetVideoURLAddress')
121
            ),
122
        ]);
123
124
        $coverField
125
            ->setAllowedMaxFileNumber(1)
126
            ->setAllowedFileCategories('image')
127
            ->setRightTitle(
128
                _t('VideoSliderItem.SET_VIDEO_COVER_IMAGE', 'Set video cover image')
129
            )->setFolderName(sprintf('%s/covers', BaseBlock::config()->upload_directory));
130
131
        $mp4UploadField
132
            ->setAllowedMaxFileNumber(1)
133
            ->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...
134
            ->setRightTitle(
135
                _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...
136
                    'extensions' => '.mp4',
137
                ])
138
            )->setFolderName(sprintf('%s/videos', BaseBlock::config()->upload_directory));
139
140
        $webMUploadField
141
            ->setAllowedMaxFileNumber(1)
142
            ->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...
143
            ->setRightTitle(
144
                _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...
145
                    'extensions' => '.webm',
146
                ])
147
            )->setFolderName(sprintf('%s/videos', BaseBlock::config()->upload_directory));
148
149
        $oggUploadField
150
            ->setAllowedMaxFileNumber(1)
151
            ->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...
152
            ->setRightTitle(
153
                _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...
154
                    'extensions' => '.ogg',
155
                ])
156
            )->setFolderName(sprintf('%s/videos', BaseBlock::config()->upload_directory));
157
158
        $uploadFieldContainer->displayIf('Type')->isEqualTo('File');
159
        $urlAddressField->displayIf('Type')->isNotEqualTo('File');
160
161
        $this->extend('updateCMSFields', $fields);
162
163
        return $fields;
164
    }
165
166
    /**
167
     * @param bool $includeRelations
168
     *
169
     * @return array
170
     */
171
    public function fieldLabels($includeRelations = true) {
172
        return array_merge(parent::fieldLabels($includeRelations), VideoSliderItem::labels());
173
    }
174
175
    /**
176
     * This will get an id of the URL address or false
177
     * if can't parsed, object type not one of supported
178
     * providers or just empty url address field.
179
     *
180
     * @return string|false
181
     * @throws ProviderNotFound
182
     */
183 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...
184
        if (! empty($this->URL) && $this->Type != 'File') {
185
            $videoId = BlocksUtility::parse_video_id($this->URL, $this->Type);
186
187
            return $videoId;
188
        }
189
190
        return false;
191
    }
192
193
    /**
194
     * Get embed link by the set of Type field. Method depends by
195
     * VideoSliderItem::$embed_links property.
196
     *
197
     * @return bool|string
198
     */
199 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...
200
        if (! empty($this->URL) && $this->Type != 'File') {
201
            try {
202
                $videoId = BlocksUtility::parse_video_id($this->URL, $this->Type);
203
            } catch (ProviderNotFound $ex) {
204
                return false;
205
            }
206
207
            if ($videoId && array_key_exists($this->Type, ($options = VideoSliderItem::config()->embed_links))) {
208
                $options = $options[$this->Type];
209
                $autoPlay = array_key_exists("AutoPlay", $options) && ! empty($options["AutoPlay"]) ? $options["AutoPlay"] : '';
210
211
                return str_replace(
212
                    ['{VideoId}', '{AutoPlay}'],
213
                    [$videoId, $autoPlay],
214
                    $options["Link"]
215
                );
216
            }
217
        }
218
219
        return false;
220
    }
221
222
    /**
223
     * @return \ValidationResult
224
     */
225 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...
226
        $validation = parent::validate();
227
228
        if (! empty($this->URL) && $this->Type != 'File') {
229
            try {
230
                $result = $this->getVideoId();
231
            } catch (ProviderNotFound $ex) {
232
                $validation->error($ex->getMessage());
233
234
                return $validation;
235
            }
236
237
            // if we can't parse url address, return an error with bad url address or
238
            // the type is not of the url address providers.
239
            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...
240
                $validation->error(_t('VideoSliderItem.INVALID_URL_ADDRESS_OR_THE_TYPE', 'Invalid URL address or the type'));
241
            }
242
        }
243
244
        return $validation;
245
    }
246
247
    /**
248
     * @return Image|false
249
     */
250
    public function getCoverImage() {
251
        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...
252
            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...
253
        }
254
255
        return false;
256
    }
257
258
    /**
259
     * Creating a button to fetch videos picture if cover image not exists.
260
     *
261
     * @return FieldList
262
     */
263
    public function getBetterButtonsActions() {
264
        $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...
265
266 View Code Duplication
        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...
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...
267
            $fields->push(BetterButtonCustomAction::create('fetchVideosPicture', _t('VideoSliderItem.FETCH_VIDEOS_PICTURE', 'Fetch videos picture')));
268
        }
269
270
        if ($this->Type == 'File' && $this->Mp4()->exists() && ! empty(BlocksUtility::whichFFMPEG())) {
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...
271
            if (! $this->WebM()->exists() || ! $this->Ogg()->exists()) {
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...
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...
272
                $fields->push(BetterButtonCustomAction::create('renderVideo', _t('VideoBlock.RENDER_HTML5_VIDEO', 'Render HTML5 Video (WebM & Ogg)')));
273
            }
274
        }
275
276
        return $fields;
277
    }
278
279
    /**
280
     * @return bool|string
281
     */
282 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...
283
        $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...
284
285
        if (! ($file instanceof File) || ! $file->exists()) {
286
            return false;
287
        }
288
289
        return $file->getAbsoluteURL();
290
    }
291
292
    /**
293
     * @return bool|string
294
     */
295 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...
296
        $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...
297
298
        if (! ($file instanceof File) || ! $file->exists()) {
299
            return false;
300
        }
301
302
        return $file->getAbsoluteURL();
303
    }
304
305
    /**
306
     * @return bool|string
307
     */
308 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...
309
        $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...
310
311
        if (! ($file instanceof File) || ! $file->exists()) {
312
            return false;
313
        }
314
315
        return $file->getAbsoluteURL();
316
    }
317
318
    /**
319
     * Fetching/downloading picture from the providers url address and
320
     * saving as Image object.
321
     *
322
     * @return false
323
     */
324
    public function fetchVideosPicture() {
325
        try {
326
            $videoId = $this->getVideoId();
327
        } catch (ProviderNotFound $ex) {
328
            return false;
329
        }
330
331
        $directoryPath = sprintf("%s/Sliders", BaseBlock::config()->upload_directory);
332
        $folder = Folder::find_or_make($directoryPath);
333
334
        if (empty($this->URL)) {
335
            return false;
336
        }
337
338
        $title = ! empty($this->Title) ? FileNameFilter::create()->filter($this->Title)."-{$this->ID}" : "video-{$this->ID}";
339
        $fileName = strtolower(sprintf("%s.jpg", $title));
340
        $baseFolder = Director::baseFolder()."/".$folder->getFilename();
341
        $type = strtolower($this->Type);
342
        $fileContent = file_get_contents(str_replace('{VideoId}', $videoId, VideoSliderItem::config()->thumbnail_links[$type]));
343
344
        switch ($type) {
345
            case 'vimeo':
346
                $fileContent = unserialize($fileContent);
347
                $fileContent = file_get_contents($fileContent[0]['thumbnail_large']);
348
                break;
349
            case 'file':
350
                // get picture from video (via ffmpeg)
351
                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...
352
353
                }
354
355
                break;
356
        }
357
358 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...
359
            if (file_put_contents($absoluteFileName = ($baseFolder.$fileName), $fileContent)) {
360
                $image = Image::create([
361
                    "Filename" => $folder->getFilename().$fileName,
362
                    "Title"    => $this->Title,
363
                    "Name"     => $fileName,
364
                    "ParentID" => $folder->ID,
365
                    "OwnerID"  => Member::currentUserID(),
366
                ]);
367
368
                if ($image->write()) {
369
                    $this->CoverID = $image->ID;
370
                    $this->write();
371
                }
372
            }
373
        }
374
    }
375
376
    public function renderVideo() {
377
        $config = array(
378
            'ffmpeg.bin' => BlocksUtility::whichFFMPEG(),
379
            'qt-faststart.bin' => '/usr/local/bin/qt-faststart',
380
        );
381
        $html5 = new \Html5Video\Html5Video($config);
382
383
        $source = Controller::join_links(
384
            Director::baseFolder(),
385
            $this->Mp4()->getFilename()
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...
386
        );
387
388
        $destination = Controller::join_links(
389
            Director::baseFolder(),
390
            '/assets/test.webm'
391
        );
392
393
        // target format is the file extension of $targetVideo. One of mp4, webm, or ogg
394
        $profileName = '720p-hd'; // other profiles are listed in src/Html5Video/profiles
395
        $html5->convert($source, $destination, $profileName);
396
    }
397
398
    public function getVideoOptions() {
399
        $options = [];
400
401
        if ($this->Type == 'File') {
402
            $options = [
403
                'videoTypes' => [
404
                    'mp4'  => $this->getMp4VideoUrl(),
405
                    'webm' => $this->getWebMVideoUrl(),
406
                    'ogg'  => $this->getOggVideoUrl(),
407
                ],
408
            ];
409
        } else {
410
            $options['embed'] = $this->getEmbedLink();
411
        }
412
413
        $options = array_merge([
414
            'autoPlay'   => (boolean) $this->AutoPlay,
415
            'type'       => $this->getVideoType(),
416
            'coverImage' => (($cover = $this->getCoverImage()) ? $cover->getAbsoluteURL() : false),
417
        ], $options);
418
419
        return Convert::raw2att(Convert::array2json($options));
420
    }
421
422
}
423
424
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...
425
426
    public function init() {
427
        if (VideoBlock::config()->load_javascript_plugin) {
428
            Requirements::javascript(CONTENT_BLOCKS_DIR."/assets/javascript/video-block.js");
429
        }
430
431
        parent::init();
432
    }
433
434
}