Completed
Pull Request — master (#20)
by
unknown
03:07
created

AbstractApiClient::sortChannels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
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\Entity\Channel;
7
use MovingImage\Client\VMPro\Entity\EmbedCode;
8
use MovingImage\Client\VMPro\Entity\Video;
9
use MovingImage\Client\VMPro\Entity\VideoRequestParameters;
10
use MovingImage\Client\VMPro\Entity\VideosRequestParameters;
11
use MovingImage\Client\VMPro\Interfaces\ApiClientInterface;
12
use MovingImage\Client\VMPro\Util\Logging\Traits\LoggerAwareTrait;
13
14
/**
15
 * Class AbstractApiClient.
16
 *
17
 * @author Ruben Knol <[email protected]>
18
 * @author Omid Rad <[email protected]>
19
 */
20
abstract class AbstractApiClient extends AbstractCoreApiClient implements ApiClientInterface
21
{
22
    use LoggerAwareTrait;
23
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function getChannels($videoManagerId)
28
    {
29
        $response = $this->makeRequest('GET', 'channels', [
30
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
31
        ]);
32
33
        $rootChannel = $this->deserialize($response->getBody(), Channel::class);
34
        $rootChannel->setChildren($this->sortChannels($rootChannel->getChildren()));
35
        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...
36
    }
37
38
    /**
39
     * Since the VMPro API doesn't sort any more the returned channels, we have to do it on our side.
40
     *
41
     * @param ArrayCollection $channels
42
     *
43
     * @return ArrayCollection
44
     */
45
    protected function sortChannels(ArrayCollection $channels)
46
    {
47
        $channels->map(function($channel) {
48
            $channel->setChildren($this->sortChannels($channel->getChildren()));
49
        });
50
51
        $iterator = $channels->getIterator();
52
        $iterator->uasort(function($a, $b) {
53
            return ($a->getName() > $b->getName());
54
        });
55
56
        return new ArrayCollection(iterator_to_array($iterator));
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function createVideo(
63
        $videoManagerId,
64
        $fileName,
65
        $title = '',
66
        $description = '',
67
        $channel = null,
68
        $group = null,
69
        array $keywords = [],
70
        $autoPublish = null
71
    ) {
72
        $response = $this->makeRequest('POST', 'videos', [
73
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
74
            'json' => $this->buildJsonParameters(
75
                compact('fileName'), // Required parameters
76
                compact('title', 'description', 'channel', 'group', 'keywords', 'autoPublish') // Optional parameters
77
            ),
78
        ]);
79
80
        // Guzzle 5+6 co-compatibility - Guzzle 6 for some reason
81
        // wraps headers in arrays.
82
        $videoLocation = is_array($response->getHeader('location'))
83
            ? $response->getHeader('location')[0]
84
            : $response->getHeader('location');
85
86
        $pieces = explode('/', $videoLocation);
87
88
        return end($pieces);
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function getVideos($videoManagerId, VideosRequestParameters $parameters = null)
95
    {
96
        $options = [
97
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
98
        ];
99
100
        if ($parameters) {
101
            $options['query'] = $parameters->getContainer();
102
        }
103
104
        $response = $this->makeRequest('GET', 'videos', $options);
105
        $response = json_encode(json_decode($response->getBody()->getContents(), true)['videos']);
106
107
        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 string.

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...
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113 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...
114
    {
115
        $options = [
116
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
117
        ];
118
119
        if ($parameters) {
120
            $options['query'] = $parameters->getContainer();
121
        }
122
123
        $response = $this->makeRequest('GET', 'videos', $options);
124
125
        return json_decode($response->getBody()->getContents(), true)['total'];
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function getVideoUploadUrl($videoManagerId, $videoId)
132
    {
133
        $response = $this->makeRequest('GET', sprintf('videos/%s/url', $videoId), [
134
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
135
        ]);
136
137
        // Guzzle 5+6 co-compatibility - Guzzle 6 for some reason
138
        // wraps headers in arrays.
139
        return is_array($response->getHeader('location'))
140
            ? $response->getHeader('location')[0]
141
            : $response->getHeader('location');
142
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147
    public function updateVideo($videoManagerId, $videoId, $title, $description)
148
    {
149
        $this->makeRequest('PATCH', sprintf('videos/%s', $videoId), [
150
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
151
            'json' => $this->buildJsonParameters([], compact('title', 'description')),
152
        ]);
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function addVideoToChannel($videoManagerId, $videoId, $channelId)
159
    {
160
        $this->makeRequest('POST', sprintf('channels/%s/videos/%s', $channelId, $videoId), [
161
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
162
        ]);
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function setCustomMetaData($videoManagerId, $videoId, $metadata)
169
    {
170
        $this->makeRequest('PATCH', sprintf('videos/%s/metadata', $videoId), [
171
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
172
            'json' => $metadata,
173
        ]);
174
    }
175
176
    /**
177
     * {@inheritdoc}
178
     */
179
    public function getEmbedCode($videoManagerId, $videoId, $playerDefinitionId, $embedType = 'html')
180
    {
181
        $response = $this->makeRequest('GET',
182
            sprintf('videos/%s/embed-codes?player_definition_id=%s&embed_type=%s',
183
                $videoId, $playerDefinitionId, $embedType), [
184
                self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
185
            ]
186
        );
187
188
        $data = \json_decode($response->getBody(), true);
189
        $embedCode = new EmbedCode();
190
        $embedCode->setCode($data['embedCode']);
191
192
        return $embedCode;
193
    }
194
195
    /**
196
     * {@inheritdoc}
197
     */
198
    public function deleteVideo($videoManagerId, $videoId)
199
    {
200
        $this->makeRequest('DELETE', sprintf('videos/%s', $videoId), [
201
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
202
        ]);
203
    }
204
205
    /**
206
     * {@inheritdoc}
207
     */
208 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...
209
    {
210
        $options = [
211
            self::OPT_VIDEO_MANAGER_ID => $videoManagerId,
212
        ];
213
214
        if ($parameters) {
215
            $options['query'] = $parameters->getContainer();
216
        }
217
218
        $response = $this->makeRequest(
219
            'GET',
220
            sprintf('videos/%s', $videoId),
221
            $options
222
        );
223
224
        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...
225
    }
226
}
227