Completed
Push — master ( 24faf9...e9a21a )
by Guillaume
02:39
created

ServiceApiCall::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
namespace AlfredTime;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ClientException;
7
use GuzzleHttp\Exception\ConnectException;
8
9
/**
10
 * ServiceApiCall
11
 */
12
class ServiceApiCall
13
{
14
    /**
15
     * @var mixed
16
     */
17
    private $client = null;
18
19
    /**
20
     * @var int
21
     */
22
    private $code = 0;
23
24
    /**
25
     * @var string
26
     */
27
    private $message = '';
28
29
    /**
30
     * @param array $config
31
     */
32
    public function __construct(array $config = [])
33
    {
34
        $config = array_merge_recursive($config, [
35
            'headers' => [
36
                'Content-type' => 'application/json',
37
                'Accept'       => 'application/json',
38
            ]]);
39
40
        $this->client = new Client($config);
41
    }
42
43
    /**
44
     * @return mixed
45
     */
46
    public function getCode()
47
    {
48
        return $this->code;
49
    }
50
51
    /**
52
     * @return mixed
53
     */
54
    public function getMessage()
55
    {
56
        return $this->message;
57
    }
58
59
    /**
60
     * @param  $status
61
     * @return mixed
62
     */
63
    public function last($status = '')
64
    {
65
        switch ($status) {
66
            case 'success':
67
                if ($this->code >= 200 && $this->code <= 299) {
68
                    return true;
69
                }
70
71
                break;
72
        }
73
74
        return false;
75
    }
76
77
    /**
78
     * @param  $method
79
     * @param  $uri
80
     * @param  array     $options
81
     * @return mixed
82
     */
83
    public function send($method, $uri = '', array $options = [], $returnData = false)
84
    {
85
        try {
86
            $response = $this->client->request(strtoupper($method), $uri, $options);
87
            $this->code = $response->getStatusCode();
88
89
            if ($returnData === false) {
90
                return true;
91
            }
92
93
            return json_decode($response->getBody(), true);
94
        } catch (ConnectException $e) {
95
            $this->message = 'cannot connect to api!';
96
97
            return false;
98
        } catch (ClientException $e) {
99
            $this->code = $e->getResponse()->getStatusCode();
100
            $this->message = $e->getResponse()->getBody();
101
102
            return false;
103
        }
104
    }
105
}
106