Completed
Branch master (003c26)
by Pixelneat
02:56
created

VideoSliderItem   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 11

Importance

Changes 0
Metric Value
wmc 22
lcom 2
cbo 11
dl 0
loc 228
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A singular_name() 0 3 1
A plural_name() 0 3 1
A getSliderTypes() 0 9 2
A getCMSFields() 0 61 1
A fieldLabels() 0 14 1
A getVideoId() 0 9 3
C getEmbedLink() 0 22 8
B validate() 0 21 5
1
<?php
2
3
/**
4
 * @author    Donatas Navidonskis <[email protected]>
5
 * @since     2017
6
 * @class     VideoSliderItem
7
 *
8
 * @property int     Mp4ID
9
 * @property int     WebMID
10
 * @property int     OggID
11
 * @property string  Type
12
 * @property string  URL
13
 * @property boolean AutoPlay
14
 *
15
 * @method File Mp4
16
 * @method File WebM
17
 * @method File Ogg
18
 *
19
 * @TODO      implement https://github.com/xemle/html5-video-php package to convert webm and ogg videos when saving.
20
 */
21
class VideoSliderItem extends BaseSliderItem {
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(128)',
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
    ];
42
43
    /**
44
     * Set providers default embed link. The key value should
45
     * be equal within Type field value.
46
     * {VideoId} - will be replaced with actual video id
47
     * {AutoPlay} - will be replaced within key of AutoPlay if AutoPlay field is true.
48
     *
49
     * @var array
50
     * @config
51
     */
52
    private static $embed_links = [
0 ignored issues
show
Unused Code introduced by
The property $embed_links 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...
53
        "Youtube" => [
54
            "Link"     => "https://www.youtube.com/embed/{VideoId}{AutoPlay}",
55
            "AutoPlay" => "?autoplay=1",
56
        ],
57
        "Vimeo"   => [
58
            "Link"     => "https://player.vimeo.com/video/{VideoId}{AutoPlay}",
59
            "AutoPlay" => "?autoplay=1",
60
        ],
61
        // Set your own providers options
62
    ];
63
64
    /**
65
     * @return string
66
     */
67
    public function singular_name() {
68
        return _t('VideoSliderItem.SINGULARNAME', 'Video slider');
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    public function plural_name() {
75
        return _t('VideoSliderItem.PLURALNAME', 'Video sliders');
76
    }
77
78
    /**
79
     * @return array
80
     */
81
    public function getSliderTypes() {
82
        $types = [];
83
84
        foreach ($this->dbObject('Type')->enumValues() as $type) {
85
            $types[$type] = $this->fieldLabel($type);
86
        }
87
88
        return $types;
89
    }
90
91
    /**
92
     * @return \FieldList
93
     */
94
    public function getCMSFields() {
95
        $fields = parent::getCMSFields();
96
        $fields->removeByName(['Type', 'Mp4', 'WebM', 'Ogg', 'URL', 'AutoPlay']);
97
        $fields->findOrMakeTab('Root.Media', $this->fieldLabel('Media'));
98
99
        $fields->addFieldsToTab('Root.Media', [
100
            DropdownField::create('AutoPlay', $this->fieldLabel('TurnOnAutoPlayMode'), BlocksUtility::localized_answers()),
101
            $videoType = OptionsetField::create('Type', $this->fieldLabel('Type'), $this->getSliderTypes(), 'File'),
102
            $uploadFieldContainer = DisplayLogicWrapper::create(
103
                $mp4UploadField = UploadField::create('Mp4', $this->fieldLabel('VideoMp4')),
104
                $webMUploadField = UploadField::create('WebM', $this->fieldLabel('VideoWebM')),
105
                $oggUploadField = UploadField::create('Ogg', $this->fieldLabel('VideoOgg'))
106
            ),
107
            $urlAddressField = TextField::create('URL', $this->fieldLabel('URLAddress'))->setRightTitle(
108
                $this->fieldLabel('SetVideoURLAddress')
109
            ),
110
        ]);
111
112
        $mp4UploadField
113
            ->setAllowedMaxFileNumber(1)
114
            ->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...
115
            ->setRightTitle(
116
                _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...
117
                    'extensions' => '.mp4',
118
                ])
119
            )
120
            ->setFolderName(
121
                sprintf('%s/Video-Sliders', BaseBlock::config()->upload_directory)
122
            );
123
124
        $webMUploadField
125
            ->setAllowedMaxFileNumber(1)
126
            ->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...
127
            ->setRightTitle(
128
                _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...
129
                    'extensions' => '.webm',
130
                ])
131
            )
132
            ->setFolderName(
133
                sprintf('%s/Video-Sliders', BaseBlock::config()->upload_directory)
134
            );
135
136
        $oggUploadField
137
            ->setAllowedMaxFileNumber(1)
138
            ->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...
139
            ->setRightTitle(
140
                _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...
141
                    'extensions' => '.ogg',
142
                ])
143
            )
144
            ->setFolderName(
145
                sprintf('%s/Video-Sliders', BaseBlock::config()->upload_directory)
146
            );
147
148
        $uploadFieldContainer->displayIf('Type')->isEqualTo('File');
149
        $urlAddressField->displayIf('Type')->isNotEqualTo('File');
150
151
        $this->extend('updateCMSFields', $fields);
152
153
        return $fields;
154
    }
155
156
    /**
157
     * @param bool $includeRelations
158
     *
159
     * @return array
160
     */
161
    public function fieldLabels($includeRelations = true) {
162
        return array_merge(parent::fieldLabels($includeRelations), [
163
            'Type'               => _t('VideoSliderItem.TYPE', 'Type'),
164
            'Youtube'            => _t('VideoSliderItem.YOUTUBE', 'Youtube'),
165
            'Vimeo'              => _t('VideoSliderItem.VIMEO', 'Vimeo'),
166
            'File'               => _t('VideoSliderItem.FILE', 'File'),
167
            'URLAddress'         => _t('VideoSliderItem.URL_ADDRESS', 'URL address'),
168
            'SetVideoURLAddress' => _t('VideoSliderItem.SET_VIDEO_URL_ADDRESS', 'Set video URL address'),
169
            'VideoMp4'           => _t('SliderItem.VIDEO_MP4', 'Video Mp4'),
170
            'VideoWebM'          => _t('SliderItem.VIDEO_WEBM', 'Video WebM'),
171
            'VideoOgg'           => _t('SliderItem.VIDEO_OGG', 'Video Ogg'),
172
            'TurnOnAutoPlayMode' => _t('SliderItem.TURN_ON_AUTO_PLAY_MODE', 'Turn on auto play mode?'),
173
        ]);
174
    }
175
176
    /**
177
     * This will get an id of the URL address or false
178
     * if can't parsed, object type not one of supported
179
     * providers or just empty url address field.
180
     *
181
     * @return bool|string
182
     * @throws ProviderNotFound
183
     */
184
    public function getVideoId() {
185
        if (! empty($this->URL) && $this->Type != 'File') {
186
            $videoId = BlocksUtility::parse_video_id($this->URL, $this->Type);
187
188
            return $videoId;
189
        }
190
191
        return false;
192
    }
193
194
    /**
195
     * Get embed link by the set of Type field. Method depends by
196
     * static::$embed_links property.
197
     *
198
     * @return bool|string
199
     */
200
    public function getEmbedLink() {
201
        if (! empty($this->URL) && $this->Type != 'File') {
202
            try {
203
                $videoId = BlocksUtility::parse_video_id($this->URL, $this->Type);
204
            } catch (ProviderNotFound $ex) {
205
                return false;
206
            }
207
208
            if ($videoId && array_key_exists($this->Type, ($options = static::config()->embed_links))) {
209
                $options = $options[$this->Type];
210
                $autoPlay = array_key_exists("AutoPlay", $options) && ! empty($options["AutoPlay"]) ? $options["AutoPlay"] : '';
211
212
                return str_replace(
213
                    ['{VideoId}', '{AutoPlay}'],
214
                    [$videoId, $autoPlay],
215
                    $options["Link"]
216
                );
217
            }
218
        }
219
220
        return false;
221
    }
222
223
    /**
224
     * @return \ValidationResult
225
     */
226
    protected function validate() {
227
        $validation = parent::validate();
228
229
        if (! empty($this->URL) && $this->Type != 'File') {
230
            try {
231
                $result = $this->getVideoId();
232
            } catch (ProviderNotFound $ex) {
233
                $validation->error($ex->getMessage());
234
235
                return $validation;
236
            }
237
238
            // if we can't parse url address, return an error with bad url address or
239
            // the type is not of the url address providers.
240
            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...
241
                $validation->error(_t('VideoSliderItem.INVALID_URL_ADDRESS_OR_THE_TYPE', 'Invalid URL address or the type'));
242
            }
243
        }
244
245
        return $validation;
246
    }
247
248
}