CelcatWebAPI   A
last analyzed

Complexity

Total Complexity 22

Size/Duplication

Total Lines 158
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 22
eloc 56
c 6
b 0
f 0
dl 0
loc 158
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A throwRunTimeException() 0 3 1
A buildRequest() 0 2 1
A log() 0 2 1
B query() 0 50 9
A __construct() 0 3 1
A buildClient() 0 11 3
A setConfiguration() 0 11 5
A get() 0 3 1
1
<?php
2
3
namespace neilherbertuk\celcatwebapi;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ClientException;
7
use Illuminate\Config\Repository as Config;
8
9
use neilherbertuk\celcatwebapi\Classes\RequestBuilder;
10
use neilherbertuk\celcatwebapi\Classes\Log;
11
use neilherbertuk\celcatwebapi\Traits\ResourcesTrait;
12
13
class CelcatWebAPI
14
{
15
    use ResourcesTrait;
16
17
    /**
18
     * @var
19
     */
20
    private $config;
21
22
    /**
23
     * @var
24
     */
25
    public $logs;
26
27
    /**
28
     * CelcatWebAPI constructor.
29
     * @param $config
30
     */
31
    public function __construct(Config $config)
32
    {
33
        $this->setConfiguration($config);
34
    }
35
36
    /**
37
     * @param Config $config
38
     */
39
    private function setConfiguration(Config $config)
40
    {
41
        if ($config->has('celcat')) {
42
            $this->config['ServerAddress'] = $config->get('celcat.ServerAddress');
43
            $this->config['APICode'] = $config->get('celcat.APICode') ?: $this->throwRunTimeException('No API Code Provided');
44
            $this->config['VerifySSL'] = $config->get('celcat.VerifySSL');
45
            $this->config['PEM'] = $config->get('celcat.PEM');
46
            $this->config['DEBUG'] = $config->get('celcat.DEBUG') ?: false;
47
            $this->config['PROXY'] = $config->get('celcat.PROXY') ?: null;
48
        } else {
49
            $this->throwRunTimeException('No config found');
50
        }
51
    }
52
53
    /**
54
     * @param $exceptionMessage
55
     */
56
    private function throwRunTimeException($exceptionMessage)
57
    {
58
        throw new \RuntimeException($exceptionMessage);
59
    }
60
61
    /**
62
     * Perform an API Query from the Celcat Web API
63
     *
64
     * @param $name
65
     * @param string $requestMethod
66
     * @param array $parameters
67
     * @return mixed
68
     * @throws \GuzzleHttp\Exception\GuzzleException
69
     */
70
    private function query($name, $requestMethod = 'GET', $parameters = [])
71
    {
72
        $this->log()->info("Starting to perform query - resource: {$name} method: {$requestMethod}".(empty($parameters ?: " parameters: ".implode($parameters))));
73
74
        $client = $this->buildClient();
75
        $options = $this->buildRequest($requestMethod)->options($parameters);
76
        $url = $this->buildRequest()->URL($name);
77
78
        try {
79
            $request = $client->request($requestMethod, $url, $options);
80
            $header = $request->getHeaders();
81
            if ($request->getStatusCode() >= 200 and $request->getStatusCode() <= 299) {
82
83
                $this->log()->info('Received '.$request->getStatusCode());
84
85
                // Build object to return
86
                $result = [];
87
88
                // Include pagination details
89
                if ($header['Pagination'] !== null) {
90
                    $result['pagination'] = json_decode($header['Pagination'][0], true);
91
                }
92
93
                if (!empty($parameters)) {
94
                    $result['parameters'] = $parameters;
95
                }
96
                $result['data'] = json_decode($request->getBody()->getContents(), true);
97
98
                return $result;
99
            } else {
100
                // TODO - Error Handling
101
                $this->log()->error('An error occurred, received a '.$request->getStatusCode());
102
                $this->log()->transferLogs();
103
                $this->throwRunTimeException('An error occurred, received a '.$request->getStatusCode());
104
                return null;
105
            }
106
        } catch (\Exception $exception) {
107
            if ($exception instanceof ClientException) {
108
                if ($exception->getCode() == 404) {
109
                    $this->log()->info('Received '.$exception->getCode());
110
                    $result['error']['code'] = 404;
111
                    $result['error']['message'] = "No Results Found";
112
                    return $result;
113
                }
114
            }
115
            // TODO - Error Handling
116
            $this->log()->error('An error occurred, received a '.$exception->getCode().' '.$exception->getMessage());
117
            $this->log()->transferLogs();
118
            $this->throwRunTimeException('An error occurred, received a '.$exception->getCode());
119
            return null;
120
        }
121
    }
122
123
    /**
124
     * Build HTTP Client and add proxy config if required
125
     *
126
     * @return Client
127
     */
128
    private function buildClient()
129
    {
130
        if ($this->config['PROXY']) {
131
            $client = new Client(['proxy' => $this->config['PROXY']]);
132
            if (!empty($this->config['PROXY']['no'])) {
133
                putenv('no_proxy=' .implode(' ,', $this->config['PROXY']['no']));
134
            }
135
136
            return $client;
137
        }
138
        return new Client();
139
    }
140
141
    /**
142
     * Returns RequestBuilder instance - used to build an api request
143
     *
144
     * @param string $requestMethod
145
     * @return RequestBuilder
146
     */
147
    private function buildRequest($requestMethod = 'GET') {
148
        return new RequestBuilder($requestMethod, $this->config);
149
    }
150
151
    /**
152
     * Performs a get request to the Celcat Web API
153
     *
154
     * @param $name
155
     * @param array $parameters
156
     * @return mixed
157
     * @throws \GuzzleHttp\Exception\GuzzleException
158
     */
159
    public function get($name, $parameters = [])
160
    {
161
        return $this->query($name, 'GET', $parameters);
162
    }
163
164
    /**
165
     * Returns a log instance
166
     *
167
     * @return Log
168
     */
169
    public function log() {
170
        return new Log($this);
171
    }
172
173
}