Completed
Push — master ( 7cc7a3...985876 )
by
unknown
42:38 queued 17:37
created

normalizeGetAttachmentsResponse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MovingImage\Client\VMPro\Util;
6
7
use DateTime;
8
use MovingImage\Client\VMPro\Entity\ChannelsRequestParameters;
9
use MovingImage\Client\VMPro\Entity\VideosRequestParameters;
10
use MovingImage\Client\VMPro\Exception;
11
use MovingImage\Meta\Enums\PublicationState;
12
13
/**
14
 * Helper methods for dealing with search endpoint.
15
 */
16
trait SearchEndpointTrait
17
{
18
    /**
19
     * Creates an elastic search query from the provided array od parameters.
20
     */
21
    private function createElasticSearchQuery(array $params, ?string $operator = 'AND'): string
22
    {
23
        $filteredParams = [];
24
        foreach ($params as $name => $value) {
25
            if (empty($name) || empty($value)) {
26
                continue;
27
            }
28
29
            $filteredParams[] = "$name:$value";
30
        }
31
32
        return implode(" $operator ", $filteredParams);
33
    }
34
35
    /**
36
     * Adjust the response from the `search` endpoint for video data type,
37
     * so that it is compatible with the response of `videos` endpoint.
38
     * Namely, it converts the date to a timestamp, adjusts the format of channels array
39
     * and re-maps some renamed properties (such as duration).
40
     * It also renames root-level properties so that they can be correctly unserialized.
41
     *
42
     * @throws Exception
43
     * @throws \Exception
44
     */
45
    private function normalizeSearchVideosResponse(string $response): string
46
    {
47
        $response = json_decode($response, true);
48
        if (!is_array($response) || !array_key_exists('result', $response) || !array_key_exists('total', $response)) {
49
            throw new Exception('Invalid response from search endpoint');
50
        }
51
52
        $response['totalCount'] = $response['total'];
53
        $response['videos'] = $response['result'];
54
        unset($response['result'], $response['total']);
55
56
        foreach ($response['videos'] as &$video) {
57
            $video['uploadDate'] = $video['createdDate'];
58
            $video['length'] = $video['duration'];
59
            foreach ($video as $prop => $value) {
60
                if (in_array($prop, ['createdDate', 'modifiedDate', 'uploadDate'])) {
61
                    $video[$prop] = (new DateTime($value))->getTimestamp();
62
                }
63
64
                if ('channels' === $prop) {
65
                    foreach ($value as $channelIndex => $channelId) {
66
                        $video[$prop][$channelIndex] = [
67
                            'id' => $channelId,
68
                            'name' => '',
69
                        ];
70
                    }
71
                }
72
            }
73
        }
74
75
        return json_encode($response);
76
    }
77
78
    /**
79
     * Adjust the response from the `search` endpoint for channel data type.
80
     * Namely, it renames the root-level properties, so they can be correctly unserialized.
81
     *
82
     * @throws Exception
83
     */
84
    private function normalizeSearchChannelsResponse(string $response): string
85
    {
86
        $response = json_decode($response, true);
87
        if (!is_array($response) || !array_key_exists('result', $response) || !array_key_exists('total', $response)) {
88
            throw new Exception('Invalid response from search endpoint');
89
        }
90
91
        $response['totalCount'] = $response['total'];
92
        $response['channels'] = $response['result'];
93
        unset($response['result'], $response['total']);
94
95
        return json_encode($response);
96
    }
97
98
    /**
99
     * Adjust the response from the `search` endpoint for ChannelAttachmentsResponse data type.
100
     * Namely, it renames the root-level properties, so they can be correctly unserialized.
101
     *
102
     * @throws Exception
103
     */
104
    private function normalizeGetAttachmentsResponse(string $response): string
105
    {
106
        $response = json_decode($response, true);
107
        if (!is_array($response)) {
108
            throw new Exception('Invalid response from search endpoint');
109
        }
110
        $result = [];
111
        foreach ($response as $item) {
112
            $result[] = [
113
                'id' => $item['data']['id'],
114
                'fileName' => $item['data']['fileName'],
115
                'downloadUrl' => $item['data']['downloadUrl'],
116
                'fileSize' => $item['data']['fileSize'],
117
                'type' => $item['type']['name'],
118
            ];
119
        }
120
121
        return json_encode($result);
122
    }
123
124
    /**
125
     * @throws Exception
126
     */
127
    private function getTotalCountFromSearchVideosResponse(string $response): int
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
128
    {
129
        $response = json_decode($response, true);
130
        if (!is_array($response) || !array_key_exists('total', $response)) {
131
            throw new Exception('Response from search endpoint is missing the "total" key');
132
        }
133
134
        return (int) $response['total'];
135
    }
136
137
    private function getRequestOptionsForSearchVideosEndpoint(
138
        int $videoManagerId,
139
        ?VideosRequestParameters $parameters = null
140
    ): array {
141
        $options = [
142
            'documentType' => 'video',
143
            'videoManagerIds' => [$videoManagerId],
144
        ];
145
146
        $queryParams = [];
147
148
        if ($parameters) {
149
            $queryParams += [
150
                'channels' => implode(',', $parameters->getChannelIds()),
151
                'id' => $parameters->getVideoId(),
152
                $parameters->getSearchInField() => $parameters->getSearchTerm(),
153
            ];
154
155
            switch ($parameters->getPublicationState()) {
156
                case PublicationState::PUBLISHED:
157
                    $queryParams['published'] = 'true';
158
                    break;
159
                case PublicationState::NOT_PUBLISHED:
160
                    $queryParams['published'] = 'false';
161
                    break;
162
                //case 'all': do nothing
163
            }
164
165
            $options += [
166
                'size' => $parameters->getLimit(),
167
                'from' => $parameters->getOffset(),
168
                'orderBy' => $parameters->getOrderProperty(),
169
                'order' => $parameters->getOrder(),
170
            ];
171
172
            if ($parameters->getMetadataSetKey()) {
173
                $options['metaDataSetKey'] = $parameters->getMetadataSetKey();
174
            }
175
        }
176
177
        $options['query'] = $this->createElasticSearchQuery($queryParams);
178
179
        return $options;
180
    }
181
182
    private function getRequestOptionsForSearchChannelsEndpoint(
183
        int $videoManagerId,
184
        ChannelsRequestParameters $parameters = null
185
    ): array {
186
        $options = [
187
            'documentType' => 'channel',
188
            'videoManagerIds' => [$videoManagerId],
189
        ];
190
191
        $queryParams = [
192
            'videoManagerId' => $videoManagerId,
193
        ];
194
195
        if ($parameters) {
196
            $queryParams += [
197
                $parameters->getSearchInField() => $parameters->getSearchTerm(),
198
            ];
199
200
            $options += [
201
                'size' => $parameters->getLimit(),
202
                'from' => $parameters->getOffset(),
203
                'orderBy' => $parameters->getOrderProperty(),
204
                'order' => $parameters->getOrder(),
205
            ];
206
207
            if ($parameters->getMetadataSetKey()) {
208
                $options['metaDataSetKey'] = $parameters->getMetadataSetKey();
209
            }
210
        }
211
212
        $options['query'] = $this->createElasticSearchQuery($queryParams);
213
214
        return $options;
215
    }
216
}
217