Completed
Pull Request — master (#29)
by
unknown
26:31 queued 23:57
created

AbstractApiClient::searchChannels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 1
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\Channel;
9
use MovingImage\Client\VMPro\Entity\EmbedCode;
10
use MovingImage\Client\VMPro\Entity\Video;
11
use MovingImage\Client\VMPro\Entity\Attachment;
12
use MovingImage\Client\VMPro\Entity\VideoRequestParameters;
13
use MovingImage\Client\VMPro\Entity\VideosRequestParameters;
14
use MovingImage\Client\VMPro\Interfaces\ApiClientInterface;
15
use MovingImage\Client\VMPro\Util\ChannelTrait;
16
use MovingImage\Client\VMPro\Util\Logging\Traits\LoggerAwareTrait;
17
use MovingImage\Client\VMPro\Util\SearchEndpointTrait;
18
19
/**
20
 * Class AbstractApiClient.
21
 *
22
 * @author Ruben Knol <[email protected]>
23
 * @author Omid Rad <[email protected]>
24
 */
25
abstract class AbstractApiClient extends AbstractCoreApiClient implements ApiClientInterface
26
{
27
    use LoggerAwareTrait;
28
    use SearchEndpointTrait;
29
    use ChannelTrait;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function getChannels($videoManagerId)
35
    {
36
        $response = $this->makeRequest('GET', 'channels', [
37
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
38
        ]);
39
40
        $rootChannel = $this->deserialize($response->getBody(), Channel::class);
41
        $rootChannel->setChildren($this->sortChannels($rootChannel->getChildren()));
42
43
        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...
44
    }
45
46
    /**
47
     * Since the VMPro API doesn't sort any more the returned channels, we have to do it on our side.
48
     *
49
     * @param ArrayCollection $channels
50
     *
51
     * @return ArrayCollection
52
     */
53
    protected function sortChannels(ArrayCollection $channels)
54
    {
55
        $channels->map(function ($channel) {
56
            $channel->setChildren($this->sortChannels($channel->getChildren()));
57
        });
58
59
        $iterator = $channels->getIterator();
60
        $iterator->uasort(function ($a, $b) {
61
            return $a->getName() > $b->getName();
62
        });
63
64
        return new ArrayCollection(iterator_to_array($iterator));
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function createVideo(
71
        $videoManagerId,
72
        $fileName,
73
        $title = '',
74
        $description = '',
75
        $channel = null,
76
        $group = null,
77
        array $keywords = [],
78
        $autoPublish = null
79
    ) {
80
        $response = $this->makeRequest('POST', 'videos', [
81
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
82
            'json' => $this->buildJsonParameters(
83
                compact('fileName'), // Required parameters
84
                compact('title', 'description', 'channel', 'group', 'keywords', 'autoPublish') // Optional parameters
85
            ),
86
        ]);
87
88
        // Guzzle 5+6 co-compatibility - Guzzle 6 for some reason
89
        // wraps headers in arrays.
90
        $videoLocation = is_array($response->getHeader('location'))
91
            ? $response->getHeader('location')[0]
92
            : $response->getHeader('location');
93
94
        $pieces = explode('/', $videoLocation);
95
96
        return end($pieces);
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function getVideos($videoManagerId, VideosRequestParameters $parameters = null)
103
    {
104
        $options = [
105
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
106
        ];
107
108
        if ($parameters) {
109
            $options['query'] = $parameters->getContainer();
110
        }
111
112
        $response = $this->makeRequest('GET', 'videos', $options);
113
        $response = json_encode(json_decode($response->getBody()->getContents(), true)['videos']);
114
115
        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...
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121 View Code Duplication
    public function getCount($videoManagerId, VideosRequestParameters $parameters = null)
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...
122
    {
123
        $options = [
124
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
125
        ];
126
127
        if ($parameters) {
128
            $options['query'] = $parameters->getContainer();
129
        }
130
131
        $response = $this->makeRequest('GET', 'videos', $options);
132
133
        return json_decode($response->getBody()->getContents(), true)['total'];
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function getVideoUploadUrl($videoManagerId, $videoId)
140
    {
141
        $response = $this->makeRequest('GET', sprintf('videos/%s/url', $videoId), [
142
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
143
        ]);
144
145
        // Guzzle 5+6 co-compatibility - Guzzle 6 for some reason
146
        // wraps headers in arrays.
147
        return is_array($response->getHeader('location'))
148
            ? $response->getHeader('location')[0]
149
            : $response->getHeader('location');
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    public function updateVideo($videoManagerId, $videoId, $title, $description)
156
    {
157
        $this->makeRequest('PATCH', sprintf('videos/%s', $videoId), [
158
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
159
            'json' => $this->buildJsonParameters([], compact('title', 'description')),
160
        ]);
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function addVideoToChannel($videoManagerId, $videoId, $channelId)
167
    {
168
        $this->makeRequest('POST', sprintf('channels/%s/videos/%s', $channelId, $videoId), [
169
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
170
        ]);
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176
    public function setCustomMetaData($videoManagerId, $videoId, $metadata)
177
    {
178
        $this->makeRequest('PATCH', sprintf('videos/%s/metadata', $videoId), [
179
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
180
            'json' => $metadata,
181
        ]);
182
    }
183
184
    /**
185
     * {@inheritdoc}
186
     */
187
    public function getEmbedCode($videoManagerId, $videoId, $playerDefinitionId, $embedType = 'html')
188
    {
189
        $url = sprintf(
190
            'videos/%s/embed-codes?player_definition_id=%s&embed_type=%s',
191
            $videoId,
192
            $playerDefinitionId,
193
            $embedType
194
        );
195
196
        if ($this->cacheTtl) {
197
            $url = sprintf('%s&token_lifetime_in_seconds=%s', $url, $this->cacheTtl);
198
        }
199
200
        $response = $this->makeRequest('GET', $url, [self::OPT_VIDEO_MANAGER_ID => $videoManagerId]);
201
202
        $data = \json_decode($response->getBody(), true);
203
        $embedCode = new EmbedCode();
204
        $embedCode->setCode($data['embedCode']);
205
206
        return $embedCode;
207
    }
208
209
    /**
210
     * {@inheritdoc}
211
     */
212
    public function deleteVideo($videoManagerId, $videoId)
213
    {
214
        $this->makeRequest('DELETE', sprintf('videos/%s', $videoId), [
215
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
216
        ]);
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     */
222 View Code Duplication
    public function getVideo($videoManagerId, $videoId, VideoRequestParameters $parameters = null)
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...
223
    {
224
        $options = [
225
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
226
        ];
227
228
        if ($parameters) {
229
            $options['query'] = $parameters->getContainer();
230
        }
231
232
        $response = $this->makeRequest(
233
            'GET',
234
            sprintf('videos/%s', $videoId),
235
            $options
236
        );
237
238
        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...
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244
    public function getAttachments($videoManagerId, $videoId)
245
    {
246
        $response = $this->makeRequest(
247
            'GET',
248
            sprintf('videos/%s/attachments', $videoId),
249
            [self::OPT_VIDEO_MANAGER_ID => $videoManagerId]
250
        );
251
252
        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...
253
    }
254
255
    /**
256
     * {@inheritdoc}
257
     */
258
    public function searchVideos($videoManagerId, VideosRequestParameters $parameters = null)
259
    {
260
        $options = $this->getRequestOptionsForSearchVideosEndpoint($videoManagerId, $parameters);
261
        $response = $this->makeRequest('POST', 'search', ['json' => $options]);
262
        $response = $this->normalizeSearchVideosResponse($response->getBody()->getContents());
263
264
        $collection = $this->deserialize($response, VideoCollection::class);
265
266
        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...
267
    }
268
269
    /**
270
     * {@inheritdoc}
271
     */
272
    public function searchChannels($videoManagerId)
273
    {
274
        $requestOptions = [
275
            'documentType' => 'channel',
276
            'videoManagerIds' => [$videoManagerId],
277
            'query' => $this->createElasticSearchQuery([
278
                'videoManagerId' => $videoManagerId,
279
            ]),
280
        ];
281
282
        $response = $this->makeRequest('POST', 'search', ['json' => $requestOptions]);
283
        $response = $this->normalizeSearchChannelsResponse($response->getBody()->getContents());
284
        /** @var ChannelCollection $collection */
285
        $collection = $this->deserialize($response, ChannelCollection::class);
286
287
        //builds parent/children relations on all channels
288
        $channels = $this->setChannelRelations($collection->getChannels());
289
        $collection->setChannels($channels);
290
291
        return $collection;
292
    }
293
}
294