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

normalizeSearchVideosResponse()   D

Complexity

Conditions 9
Paths 9

Size

Total Lines 32
Code Lines 19

Duplication

Lines 3
Ratio 9.38 %

Importance

Changes 0
Metric Value
dl 3
loc 32
rs 4.909
c 0
b 0
f 0
cc 9
eloc 19
nc 9
nop 1
1
<?php
2
3
namespace MovingImage\Client\VMPro\Util;
4
5
use MovingImage\Client\VMPro\Entity\VideosRequestParameters;
6
use MovingImage\Client\VMPro\Exception;
7
8
/**
9
 * Helper methods for dealing with search endpoint.
10
 */
11
trait SearchEndpointTrait
12
{
13
    /**
14
     * Creates an elastic search query from the provided array od parameters.
15
     *
16
     * @param array  $params
17
     * @param string $operator
18
     *
19
     * @return string
20
     */
21
    private function createElasticSearchQuery(array $params, $operator = 'AND')
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
     * @param string $response
43
     *
44
     * @return string
45
     *
46
     * @throws Exception
47
     */
48
    private function normalizeSearchVideosResponse($response)
49
    {
50
        $response = json_decode($response, true);
51 View Code Duplication
        if (!is_array($response) || !array_key_exists('result', $response) || !array_key_exists('total', $response)) {
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...
52
            throw new Exception('Invalid response from search endpoint');
53
        }
54
55
        $response['totalCount'] = $response['total'];
56
        $response['videos'] = $response['result'];
57
        unset($response['result'], $response['total']);
58
59
        foreach ($response['videos'] as &$video) {
60
            $video['uploadDate'] = $video['createdDate'];
61
            $video['length'] = $video['duration'];
62
            foreach ($video as $prop => $value) {
63
                if (in_array($prop, ['createdDate', 'modifiedDate', 'uploadDate'])) {
64
                    $video[$prop] = (new \DateTime($value))->getTimestamp();
65
                }
66
67
                if ($prop === 'channels') {
68
                    foreach ($value as $channelIndex => $channelId) {
69
                        $video[$prop][$channelIndex] = [
70
                            'id' => $channelId,
71
                            'name' => '',
72
                        ];
73
                    }
74
                }
75
            }
76
        }
77
78
        return json_encode($response);
79
    }
80
81
    /**
82
     * Adjust the response from the `search` endpoint for channel data type.
83
     * Namely, it renames the root-level properties, so they can be correctly unserialized.
84
     *
85
     * @param string $response
86
     *
87
     * @return string
88
     *
89
     * @throws Exception
90
     */
91
    private function normalizeSearchChannelsResponse($response)
92
    {
93
        $response = json_decode($response, true);
94 View Code Duplication
        if (!is_array($response) || !array_key_exists('result', $response) || !array_key_exists('total', $response)) {
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...
95
            throw new Exception('Invalid response from search endpoint');
96
        }
97
98
        $response['totalCount'] = $response['total'];
99
        $response['channels'] = $response['result'];
100
        unset($response['result'], $response['total']);
101
102
        return json_encode($response);
103
    }
104
105
    /**
106
     * @param string $response
107
     *
108
     * @return int
109
     *
110
     * @throws Exception
111
     */
112
    private function getTotalCountFromSearchVideosResponse($response)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
113
    {
114
        $response = json_decode($response, true);
115
        if (!is_array($response) || !array_key_exists('total', $response)) {
116
            throw new Exception('Response from search endpoint is missing the "total" key');
117
        }
118
119
        return (int) $response['total'];
120
    }
121
122
    /**
123
     * @param int                          $videoManagerId
124
     * @param VideosRequestParameters|null $parameters
125
     *
126
     * @return array
127
     */
128
    private function getRequestOptionsForSearchVideosEndpoint(
129
        $videoManagerId,
130
        VideosRequestParameters $parameters = null
131
    ) {
132
        $options = [
133
            'documentType' => 'video',
134
            'videoManagerIds' => [$videoManagerId],
135
            'fetchSources' => [
136
                'id',
137
                'title',
138
                'description',
139
                'createdDate',
140
                'duration',
141
                'published',
142
                'customMetadata',
143
                'keywords',
144
                'channels',
145
                'downloadable',
146
            ],
147
        ];
148
149
        if ($parameters) {
150
            $queryParams = [
151
                'channels' => $parameters->getChannelId(),
152
                'published' => $parameters->getPublicationState(),
153
                $parameters->getSearchInField() => $parameters->getSearchTerm(),
154
            ];
155
156
            $options += [
157
                'size' => $parameters->getLimit(),
158
                'from' => $parameters->getOffset(),
159
                'orderBy' => $parameters->getOrderProperty(),
160
                'order' => $parameters->getOrder(),
161
                'query' => $this->createElasticSearchQuery($queryParams),
162
            ];
163
        }
164
165
        return $options;
166
    }
167
}
168