Request   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 249
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 71.08%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 1
dl 0
loc 249
c 0
b 0
f 0
ccs 59
cts 83
cp 0.7108
rs 9.6

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A execute() 0 11 1
B sendRequest() 0 37 4
B getParams() 0 12 6
A getUrl() 0 15 4
A getBinaryArgs() 0 17 4
B checkResponseForErrors() 0 24 5
A isPost() 0 4 2
A isBinary() 0 4 2
A getProtocol() 0 4 3
1
<?php
2
3
namespace LeadThread\Viddler\Api;
4
5
class Request
6
{
7
    protected $method;
8
    protected $apiKey;
9
    protected $options;
10
    protected $secure;
11
12
    /**
13
     * Methods that require Binary transfer
14
     */
15
    protected $binaryMethods = [
16
        'viddler.videos.setThumbnail'
17
    ];
18
19
    /**
20
     * Methods that require HTTPS
21
     */
22
    protected $secureMethods = [
23
        'viddler.users.auth',
24
        'viddler.users.register'
25
    ];
26
27
    /**
28
     * Methods that require POST
29
     */
30
    protected $postMethods = [
31
        'viddler.encoding.cancel',
32
        'viddler.encoding.encode',
33
        'viddler.encoding.setOptions',
34
        'viddler.encoding.setSettings',
35
        'viddler.logins.add',
36
        'viddler.logins.delete',
37
        'viddler.logins.update',
38
        'viddler.playlists.addVideo',
39
        'viddler.playlists.create',
40
        'viddler.playlists.delete',
41
        'viddler.playlists.moveVideo',
42
        'viddler.playlists.removeVideo',
43
        'viddler.playslists.setDetails',
44
        'viddler.resellers.removeSubaccount',
45
        'viddler.users.register',
46
        'viddler.users.setSettings',
47
        'viddler.users.setProfile',
48
        'viddler.users.setOptions',
49
        'viddler.users.setPlayerBranding',
50
        'viddler.videos.addClosedCaptioning',
51
        'viddler.videos.comments.add',
52
        'viddler.videos.comments.remove',
53
        'viddler.videos.delClosedCaptioning',
54
        'viddler.videos.delete',
55
        'viddler.videos.delFile',
56
        'viddler.videos.disableAds',
57
        'viddler.videos.enableAds',
58
        'viddler.videos.favorite',
59
        'viddler.videos.setClosedCaptioning',
60
        'viddler.videos.setDetails',
61
        'viddler.videos.setPermalink',
62
        'viddler.videos.setThumbnail',
63
    ];
64
65
    /**
66
     * A Mapping of what Exception to throw when Viddler returns a certain error code
67
     */
68
    protected $exceptions = [
69
        "203"     => Exceptions\ViddlerUploadingDisabledException::class,
70
        "202"     => Exceptions\ViddlerInvalidFormTypeException::class,
71
        "200"     => Exceptions\ViddlerSizeLimitExceededException::class,
72
        "105"     => Exceptions\ViddlerUsernameExistsException::class,
73
        "104"     => Exceptions\ViddlerTermsNotAcceptedException::class,
74
        "103"     => Exceptions\ViddlerInvalidPasswordException::class,
75
        "102"     => Exceptions\ViddlerAccountSuspendedException::class,
76
        "101"     => Exceptions\ViddlerForbiddenException::class,
77
        "100"     => Exceptions\ViddlerNotFoundException::class,
78
        "8"       => Exceptions\ViddlerInvalidApiKeyException::class,
79
        "default" => Exceptions\ViddlerException::class
80
    ];
81
82 15
    public function __construct($apiKey, $method, $options, $secure = false)
83
    {
84 15
        $this->method  = $method;
85 15
        $this->apiKey  = $apiKey;
86 15
        $this->secure  = $secure;
87 15
        $this->options = $options;
88 15
    }
89
90
    /**
91
     * Constructs the Request requirements and then sends the Request returning the response
92
     */
93 6
    public function execute()
94
    {
95
        // Get the parameters
96 6
        $params = $this->getParams();
97
98
        // Get the url
99 6
        $url = $this->getUrl($params);
100
101
        // Run it
102 6
        return $this->sendRequest($url, $params);
103
    }
104
105
    /**
106
     * Sends the actual curl request
107
     */
108
    protected function sendRequest($url, $params)
109
    {
110
        // Construct the cURL call
111
        $ch = curl_init();
112
        curl_setopt($ch, CURLOPT_URL, $url);
113
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
114
        curl_setopt($ch, CURLOPT_HEADER, 0);
115
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
116
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
117
118
        // Figure POST vs. GET
119
        if ($this->isPost()) {
120
            curl_setopt($ch, CURLOPT_POST, true);
121
            if ($this->isBinary()) {
122
                curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getBinaryArgs());
123
            } else {
124
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
125
            }
126
        } else {
127
            curl_setopt($ch, CURLOPT_HTTPGET, true);
128
        }
129
130
        //Get the response
131
        $response = curl_exec($ch);
132
133
        if (!$response) {
134
            throw new Exceptions\ViddlerException(curl_error($ch));
135
        } else {
136
            $response = unserialize($response);
137
        }
138
139
        curl_close($ch);
140
141
        $response = $this->checkResponseForErrors($response);
142
143
        return $response;
144
    }
145
146
    /**
147
     * Builds the query object from the options property
148
     */
149 6
    protected function getParams()
150
    {
151 6
        $params = ["key=".$this->apiKey];
152 6
        if (@count($this->options[0]) > 0 && is_array($this->options[0])) {
153 6
            foreach ($this->options[0] as $k => $v) {
154 6
                if ($k != "response_type" && $k != "apiKey") {
155 6
                    array_push($params, "$k=$v");
156 6
                }
157 6
            }
158 6
        }
159 6
        return $params;
160
    }
161
162
    /**
163
     * Builds the URL for the request
164
     */
165 6
    protected function getUrl($params)
166
    {
167
        // Figure protocol http:// or https://
168 6
        $protocol = $this->getProtocol();
169
170
        // The base
171 6
        $url = $protocol . "://api.viddler.com/api/v2/" . $this->method . ".php";
172
173
        // Add on the params
174 6
        if (!$this->isPost() && @count($params) > 0 && is_array($params)) {
175 3
            $url .= "?" . implode("&", $params);
176 3
        }
177
178 6
        return $url;
179
    }
180
181
    /**
182
     * Returns the binary arguments for the request
183
     */
184 3
    protected function getBinaryArgs()
185
    {
186 3
        $bArgs = array();
187 3
        foreach ($this->options[0] as $k => $v) {
188 3
            if ($k != 'file') {
189 3
                $bArgs[$k] = $v;
190 3
            }
191 3
        }
192
193 3
        if (!isset($bArgs['key'])) {
194 3
            $bArgs['key'] = $this->apiKey;
195 3
        }
196
197 3
        $bArgs['file'] = curl_file_create($this->options[0]['file']);
198
199 3
        return $bArgs;
200
    }
201
202
    /**
203
     * Throws an Exception if the response contains an error
204
     */
205 6
    protected function checkResponseForErrors($response)
206
    {
207 6
        if (isset($response["error"])) {
208 3
            $msg = [];
209 3
            $parts = ["code", "description", "details"];
210
            
211 3
            foreach ($parts as $part) {
212 3
                if (!empty($response["error"][$part])) {
213 3
                    $msg[] = $part.": ".$response["error"][$part];
214 3
                }
215 3
            }
216
217 3
            $msg = implode(" | ", $msg);
218 3
            $code = $response["error"]["code"];
219
220 3
            if (!array_key_exists($code, $this->exceptions)) {
221 3
                $code = "default";
222 3
            }
223
224 3
            throw new $this->exceptions[$code]($msg);
225
        }
226
227 3
        return $response;
228
    }
229
230
    /**
231
     * Checks if the method should be run as a POST
232
     */
233 6
    protected function isPost()
234
    {
235 6
        return (in_array($this->method, $this->postMethods)) ? true : false;
236
    }
237
238
    /**
239
     * Checks if the method is a binary method
240
     */
241
    protected function isBinary()
242
    {
243
        return (in_array($this->method, $this->binaryMethods)) ? true : false;
244
    }
245
246
    /**
247
     * Returns the correct protocol for the provided method
248
     */
249 6
    protected function getProtocol()
250
    {
251 6
        return (in_array($this->method, $this->secureMethods) || $this->secure === true) ? "https" : "http";
252
    }
253
}
254