Completed
Push — master ( 91f80b...b28fcf )
by Denis
01:47
created

Curl   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 1
dl 0
loc 67
ccs 35
cts 40
cp 0.875
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C getResponse() 0 53 11
A getError() 0 10 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: dp
5
 * Date: 26.07.17
6
 * Time: 12:06
7
 */
8
9
namespace Lan\Ebs\Sdk\Helper;
10
11
use Exception;
12
13
class Curl
14
{
15 16
    public static function getResponse($host, $url, $method, $token, array $params)
16
    {
17 16
        $curl = curl_init();
18
19
        switch ($method) {
20 16
            case 'GET':
21 15
                if (!empty($params)) {
22 11
                    $url = sprintf("%s?%s", $url, http_build_query($params));
23 11
                };
24
25 15
                break;
26 2
            case 'POST':
27 2
            case 'PUT':
28 2
            case 'DELETE':
29 2
                if (!empty($params)) {
30 2
                    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
31 2
                }
32 2
                break;
33
            default:
34
                throw new Exception('Method ' . $method . ' unknown');
35
        }
36
37
        $headers = [
38 16
            'X-Auth-Token: ' . $token,
39 16
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
40
            'Accept: application/json'
41 16
        ];
42
43 16
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
44 16
        curl_setopt($curl, CURLOPT_URL, $host . $url);
45 16
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
46 16
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
47
48 16
        $curlResult = curl_exec($curl);
49
50 16
        Debuger::dump($method . ' ' . $host . $url . ' [' . (curl_errno($curl) ? 500 : curl_getinfo($curl)['http_code']) . ']');
51
52 16
        if (curl_errno($curl)) {
53
            return Curl::getError('Curl error: ' . curl_errno($curl), 500);
54
        }
55
56 16
        $response = json_decode($curlResult, true);
57
58 16
        if (json_last_error()) {
59 1
            return Curl::getError('JSON error: ' . json_last_error_msg() . "\n" . $curlResult, curl_getinfo($curl)['http_code']);
60
        }
61
62 15
        if (empty($response)) {
63
            return Curl::getError('Response is empty', curl_getinfo($curl)['http_code']);
64
        }
65
66 15
        return $response;
67
    }
68
69 1
    private static function getError($message, $code)
70
    {
71
        return [
72 1
            'type' => 'none',
73 1
            'data' => null,
74 1
            'count' => 0,
75 1
            'status' => $code,
76
            'message' => $message
77 1
        ];
78
    }
79
}