Passed
Pull Request — master (#64)
by
unknown
02:38
created

AbstractApiClient::updateThumbnail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 4
1
<?php
2
3
namespace MovingImage\Client\VMPro\ApiClient;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use MovingImage\Client\VMPro\Collection\ChannelCollection;
7
use MovingImage\Client\VMPro\Collection\VideoCollection;
8
use MovingImage\Client\VMPro\Entity\Attachment;
9
use MovingImage\Client\VMPro\Entity\Channel;
10
use MovingImage\Client\VMPro\Entity\ChannelsRequestParameters;
11
use MovingImage\Client\VMPro\Entity\EmbedCode;
12
use MovingImage\Client\VMPro\Entity\Keyword;
13
use MovingImage\Client\VMPro\Entity\Video;
14
use MovingImage\Client\VMPro\Entity\VideoDownloadUrl;
15
use MovingImage\Client\VMPro\Entity\VideoManager;
16
use MovingImage\Client\VMPro\Entity\VideoRequestParameters;
17
use MovingImage\Client\VMPro\Entity\VideosRequestParameters;
18
use MovingImage\Client\VMPro\Entity\Thumbnail;
19
use MovingImage\Client\VMPro\Interfaces\ApiClientInterface;
20
use MovingImage\Client\VMPro\Util\ChannelTrait;
21
use MovingImage\Client\VMPro\Util\Logging\Traits\LoggerAwareTrait;
22
use MovingImage\Client\VMPro\Util\SearchEndpointTrait;
23
24
/**
25
 * Class AbstractApiClient.
26
 *
27
 * @author Ruben Knol <[email protected]>
28
 * @author Omid Rad <[email protected]>
29
 */
30
abstract class AbstractApiClient extends AbstractCoreApiClient implements ApiClientInterface
31
{
32
    use LoggerAwareTrait;
33
    use SearchEndpointTrait;
34
    use ChannelTrait;
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function getChannels($videoManagerId)
40
    {
41
        $response = $this->makeRequest('GET', 'channels', [
42
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
43
        ]);
44
45
        $rootChannel = $this->deserialize($response->getBody(), Channel::class);
46
        $rootChannel->setChildren($this->sortChannels($rootChannel->getChildren()));
47
48
        return $rootChannel;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $rootChannel; (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...tInterface::getChannels of type MovingImage\Client\VMPro\Entity\Channel.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
49
    }
50
51
    /**
52
     * Since the VMPro API doesn't sort any more the returned channels, we have to do it on our side.
53
     *
54
     * @param ArrayCollection $channels
55
     *
56
     * @return ArrayCollection
57
     */
58
    protected function sortChannels(ArrayCollection $channels)
59
    {
60
        $channels->map(function ($channel) {
61
            $channel->setChildren($this->sortChannels($channel->getChildren()));
62
        });
63
64
        $iterator = $channels->getIterator();
65
        $iterator->uasort(function ($a, $b) {
66
            return $a->getName() > $b->getName();
67
        });
68
69
        return new ArrayCollection(iterator_to_array($iterator));
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function createVideo(
76
        $videoManagerId,
77
        $fileName,
78
        $title = '',
79
        $description = '',
80
        $channel = null,
81
        $group = null,
82
        array $keywords = [],
83
        $autoPublish = null
84
    ) {
85
        $response = $this->makeRequest('POST', 'videos', [
86
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
87
            'json' => $this->buildJsonParameters(
88
                compact('fileName'), // Required parameters
89
                compact('title', 'description', 'channel', 'group', 'keywords', 'autoPublish') // Optional parameters
90
            ),
91
        ]);
92
93
        // Guzzle 5+6 co-compatibility - Guzzle 6 for some reason
94
        // wraps headers in arrays.
95
        $videoLocation = is_array($response->getHeader('location'))
96
            ? $response->getHeader('location')[0]
97
            : $response->getHeader('location');
98
99
        $pieces = explode('/', $videoLocation);
100
101
        return end($pieces);
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function getVideos($videoManagerId, VideosRequestParameters $parameters = null)
108
    {
109
        $options = [
110
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
111
        ];
112
113 View Code Duplication
        if ($parameters) {
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...
114
            $query = http_build_query($parameters->getContainer(), null, '&', PHP_QUERY_RFC3986);
115
            $options['query'] = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
116
        }
117
118
        $response = $this->makeRequest('GET', 'videos', $options);
119
        $response = json_encode(json_decode($response->getBody()->getContents(), true)['videos']);
120
121
        return $this->deserialize($response, 'ArrayCollection<'.Video::class.'>');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...ty\Video::class . '>'); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...entInterface::getVideos of type MovingImage\Meta\Interfaces\VideoInterface[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127
    public function getCount($videoManagerId, VideosRequestParameters $parameters = null)
128
    {
129
        $options = [
130
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
131
        ];
132
133 View Code Duplication
        if ($parameters) {
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...
134
            $query = http_build_query($parameters->getContainer(), null, '&', PHP_QUERY_RFC3986);
135
            $options['query'] = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
136
        }
137
138
        $response = $this->makeRequest('GET', 'videos', $options);
139
140
        return json_decode($response->getBody()->getContents(), true)['total'];
141
    }
142
143
    /**
144
     * {@inheritdoc}
145
     */
146
    public function getVideoUploadUrl($videoManagerId, $videoId)
147
    {
148
        $response = $this->makeRequest('GET', sprintf('videos/%s/url', $videoId), [
149
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
150
        ]);
151
152
        // Guzzle 5+6 co-compatibility - Guzzle 6 for some reason
153
        // wraps headers in arrays.
154
        return is_array($response->getHeader('location'))
155
            ? $response->getHeader('location')[0]
156
            : $response->getHeader('location');
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function updateVideo($videoManagerId, $videoId, $title, $description)
163
    {
164
        $this->makeRequest('PATCH', sprintf('videos/%s', $videoId), [
165
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
166
            'json' => $this->buildJsonParameters([], compact('title', 'description')),
167
        ]);
168
    }
169
170
    /**
171
     * {@inheritdoc}
172
     */
173
    public function addVideoToChannel($videoManagerId, $videoId, $channelId)
174
    {
175
        $this->makeRequest('POST', sprintf('channels/%s/videos/%s', $channelId, $videoId), [
176
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
177
        ]);
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183
    public function removeVideoFromChannel($videoManagerId, $videoId, $channelId)
184
    {
185
        $this->makeRequest('DELETE', sprintf('channels/%s/videos/%s', $channelId, $videoId), [
186
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
187
        ]);
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193
    public function setCustomMetaData($videoManagerId, $videoId, $metadata)
194
    {
195
        $this->makeRequest('PATCH', sprintf('videos/%s/metadata', $videoId), [
196
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
197
            'json' => $metadata,
198
        ]);
199
    }
200
201
    /**
202
     * {@inheritdoc}
203
     */
204
    public function getEmbedCode($videoManagerId, $videoId, $playerDefinitionId, $embedType = 'html')
205
    {
206
        $url = sprintf(
207
            'videos/%s/embed-codes?player_definition_id=%s&embed_type=%s',
208
            $videoId,
209
            $playerDefinitionId,
210
            $embedType
211
        );
212
213
        if ($this->cacheTtl) {
214
            $url = sprintf('%s&token_lifetime_in_seconds=%s', $url, $this->cacheTtl);
215
        }
216
217
        $response = $this->makeRequest('GET', $url, [self::OPT_VIDEO_MANAGER_ID => $videoManagerId]);
218
219
        $data = \json_decode($response->getBody(), true);
220
        $embedCode = new EmbedCode();
221
        $embedCode->setCode($data['embedCode']);
222
223
        return $embedCode;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    public function deleteVideo($videoManagerId, $videoId)
230
    {
231
        $this->makeRequest('DELETE', sprintf('videos/%s', $videoId), [
232
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
233
        ]);
234
    }
235
236
    /**
237
     * {@inheritdoc}
238
     */
239
    public function getVideo($videoManagerId, $videoId, VideoRequestParameters $parameters = null)
240
    {
241
        $options = [
242
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
243
        ];
244
245
        if ($parameters) {
246
            $options['query'] = $parameters->getContainer();
247
        }
248
249
        $response = $this->makeRequest(
250
            'GET',
251
            sprintf('videos/%s', $videoId),
252
            $options
253
        );
254
255
        return $this->deserialize($response->getBody()->getContents(), Video::class);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...o\Entity\Video::class); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...ientInterface::getVideo of type MovingImage\Client\VMPro\Entity\Video.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
256
    }
257
258
    /**
259
     * {@inheritdoc}
260
     */
261 View Code Duplication
    public function getAttachments($videoManagerId, $videoId)
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...
262
    {
263
        $response = $this->makeRequest(
264
            'GET',
265
            sprintf('videos/%s/attachments', $videoId),
266
            [self::OPT_VIDEO_MANAGER_ID => $videoManagerId]
267
        );
268
269
        return $this->deserialize($response->getBody()->getContents(), 'ArrayCollection<'.Attachment::class.'>');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...tachment::class . '>'); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...terface::getAttachments of type MovingImage\Client\VMPro\Entity\Attachment[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
270
    }
271
272
    /**
273
     * {@inheritdoc}
274
     */
275 View Code Duplication
    public function getChannelAttachments($videoManagerId, $channelId)
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
    {
277
        $response = $this->makeRequest(
278
            'GET',
279
            sprintf('channels/%s/attachments', $channelId),
280
            [self::OPT_VIDEO_MANAGER_ID => $videoManagerId]
281
        );
282
283
        return $this->deserialize($response->getBody()->getContents(), 'ArrayCollection<'.Attachment::class.'>');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...tachment::class . '>'); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...::getChannelAttachments of type MovingImage\Client\VMPro\Entity\Attachment[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
284
    }
285
286
    /**
287
     * {@inheritdoc}
288
     */
289 View Code Duplication
    public function getKeywords($videoManagerId, $videoId)
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...
290
    {
291
        $response = $this->makeRequest(
292
            'GET',
293
            sprintf('videos/%s/keywords', $videoId),
294
            [self::OPT_VIDEO_MANAGER_ID => $videoManagerId]
295
        );
296
297
        return $this->deserialize($response->getBody()->getContents(), 'ArrayCollection<'.Keyword::class.'>');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...\Keyword::class . '>'); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...tInterface::getKeywords of type MovingImage\Client\VMPro\Entity\Keyword[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
298
    }
299
300
    /**
301
     * {@inheritdoc}
302
     */
303
    public function updateKeywords($videoManagerId, $videoId, $keywords)
304
    {
305
        //remove all keywords
306
        foreach ($this->getKeywords($videoManagerId, $videoId) as $keyword) {
0 ignored issues
show
Bug introduced by
The expression $this->getKeywords($videoManagerId, $videoId) of type object|array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
307
            $this->deleteKeyword($videoManagerId, $videoId, $keyword->getId());
308
        }
309
310
        //add new
311
        foreach ($keywords as $keyword) {
312
            $this->makeRequest('POST', sprintf('videos/%s/keywords', $videoId), [
313
                self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
314
                'json' => ['text' => $keyword],
315
            ]);
316
        }
317
    }
318
319
    /**
320
     * {@inheritdoc}
321
     */
322
    public function deleteKeyword($videoManagerId, $videoId, $keywordId)
323
    {
324
        $this->makeRequest('DELETE', sprintf('videos/%s/keywords/%s', $videoId, $keywordId), [
325
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
326
        ]);
327
    }
328
329
    /**
330
     * {@inheritdoc}
331
     */
332
    public function searchVideos($videoManagerId, VideosRequestParameters $parameters = null, $searchQuery = null)
333
    {
334
        $options = $this->getRequestOptionsForSearchVideosEndpoint($videoManagerId, $parameters);
335
        if ($searchQuery) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $searchQuery of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null 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...
336
            $options['query'] = sprintf('(%s) AND (%s)', $options['query'], $searchQuery);
337
        }
338
        $response = $this->makeRequest('POST', 'search', ['json' => $options]);
339
        $response = $this->normalizeSearchVideosResponse($response->getBody()->getContents());
340
341
        $collection = $this->deserialize($response, VideoCollection::class);
342
343
        return $collection;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $collection; (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...Interface::searchVideos of type MovingImage\Client\VMPro...lection\VideoCollection.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
344
    }
345
346
    /**
347
     * {@inheritdoc}
348
     */
349
    public function searchChannels($videoManagerId, ChannelsRequestParameters $parameters = null)
350
    {
351
        $options = $this->getRequestOptionsForSearchChannelsEndpoint($videoManagerId, $parameters);
352
        $response = $this->makeRequest('POST', 'search', ['json' => $options]);
353
        $response = $this->normalizeSearchChannelsResponse($response->getBody()->getContents());
354
        /** @var ChannelCollection $collection */
355
        $collection = $this->deserialize($response, ChannelCollection::class);
356
357
        //builds parent/children relations on all channels
358
        $channels = $this->setChannelRelations($collection->getChannels());
0 ignored issues
show
Documentation introduced by
$collection->getChannels() is of type array<integer,object<Mov...aces\ChannelInterface>>, but the function expects a array<integer,object<Mov...\VMPro\Entity\Channel>>.

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...
359
        $collection->setChannels($channels);
360
361
        return $collection;
362
    }
363
364
    /**
365
     * {@inheritdoc}
366
     */
367
    public function getVideoManagers()
368
    {
369
        $response = $this->makeRequest('GET', '', []);
370
371
        return $this->deserialize($response->getBody()->getContents(), 'ArrayCollection<'.VideoManager::class.'>');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...oManager::class . '>'); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...rface::getVideoManagers of type MovingImage\Client\VMPro\Entity\VideoManager[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
372
    }
373
374
    /**
375
     * {@inheritdoc}
376
     */
377
    public function getVideoDownloadUrls($videoManagerId, $videoId)
378
    {
379
        $options = [
380
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
381
        ];
382
383
        $response = $this->makeRequest(
384
            'GET',
385
            sprintf('videos/%s/download-urls', $videoId),
386
            $options
387
        );
388
389
        $response = $response->getBody()->getContents();
390
391
        return $this->deserialize($response, 'ArrayCollection<'.VideoDownloadUrl::class.'>');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->deserializ...nloadUrl::class . '>'); (object|array|integer|double|string|boolean) is incompatible with the return type declared by the interface MovingImage\Client\VMPro...e::getVideoDownloadUrls of type MovingImage\Client\VMPro\Entity\VideoDownloadUrl[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
392
    }
393
394
    /**
395
     * {@inheritdoc}
396
     */
397
    public function createThumbnailByTimestamp($videoManagerId, $videoId, $timestamp)
398
    {
399
        $options = [
400
            self::OPT_VIDEO_MANAGER_ID => intval($videoManagerId),
401
        ];
402
403
        $response = $this->makeRequest(
404
            'POST',
405
            'videos/'.$videoId.'/thumbnails?timestamp='.intval($timestamp),
406
            $options
407
        );
408
409
        if (preg_match('/\/thumbnails\/([0-9]*)/', $response->getHeader('Location')[0], $match)) {
410
            return (new Thumbnail())->setId(intval($match[1]));
411
        }
412
    }
413
414
    /**
415
     * {@inheritdoc}
416
     */
417
    public function getThumbnail($videoManagerId, $videoId, $thumbnailId)
418
    {
419
        $options = [
420
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
421
        ];
422
423
        $response = $this->makeRequest(
424
            'GET',
425
            'videos/'.$videoId.'/thumbnails/'.$thumbnailId.'/url',
426
            $options
427
        );
428
429
        $result = \json_decode($response->getBody()->getContents(), true);
430
431
        if (isset($result['downloadUrl'])) {
432
            return (new Thumbnail())
433
                ->setId(intval($thumbnailId))
434
                ->setUrl($result['downloadUrl']);
435
        }
436
437
        return null;
438
    }
439
440
    /**
441
     * {@inheritdoc}
442
     */
443
    public function updateThumbnail($videoManagerId, $videoId, $thumbnailId, $active)
444
    {
445
        $options = [
446
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
447
            'json' => ['active' => boolval($active)],
448
        ];
449
450
        $this->makeRequest(
451
            'PATCH',
452
            'videos/'.$videoId.'/thumbnails/'.intval($thumbnailId),
453
            $options
454
        );
455
    }
456
}
457