Issues (6)

src/ApiOperations/Request.php (1 issue)

Severity
1
<?php
2
3
namespace Digikraaft\Abokifx\ApiOperations;
4
5
use Digikraaft\Abokifx\Abokifx;
6
use Digikraaft\Abokifx\Exceptions\ApiErrorException;
7
use Digikraaft\Abokifx\Exceptions\InvalidArgumentException;
8
use Digikraaft\Abokifx\Exceptions\IsNullException;
9
use Digikraaft\Abokifx\Util\Util;
10
use GuzzleHttp\Client;
11
use GuzzleHttp\Exception\ClientException;
12
13
/**
14
 * Trait for resources that need to make API requests.
15
 */
16
trait Request
17
{
18
    /**
19
     * Instance of Client.
20
     */
21
    protected static $client;
22
23
    /**
24
     *  Response from requests made to Abokifx.
25
     *
26
     * @var mixed
27
     */
28
    protected static $response;
29
30
    /**
31
     * @param null|array|mixed $params   The list of parameters to validate
32
     * @param bool             $required
33
     *
34
     * @throws InvalidArgumentException if $params exists and is not an array
35
     */
36
    public static function validateParams($params = null, $required = false): void
37
    {
38
        if ($required) {
39
            if (empty($params) || ! is_array($params)) {
40
                $message = 'The parameter passed must be an array and must not be empty';
41
42
                throw new InvalidArgumentException($message);
43
            }
44
        }
45
        if ($params && ! is_array($params)) {
46
            $message = 'The parameter passed must be an array';
47
48
            throw new InvalidArgumentException($message);
49
        }
50
    }
51
52
    /**
53
     * @param string $method      HTTP method ('get', 'post', etc.)
54
     * @param string $url         URL for the request
55
     * @param array  $params      list of parameters for the request
56
     * @param string $return_type return array or object accepted values: 'arr' and 'obj'
57
     *
58
     * @throws InvalidArgumentException
59
     * @throws IsNullException
60
     *
61
     * @return array|object (the JSON response as array or object)
62
     */
63
    public static function staticRequest($method, $url, $params = [], $return_type = Abokifx::ARRAY_RESPONSE)
64
    {
65
        if (Abokifx::$responseType != Abokifx::ARRAY_RESPONSE && Abokifx::$responseType != Abokifx::OBJECT_RESPONSE) {
66
            throw new InvalidArgumentException('Return type can only be '. Abokifx::OBJECT_RESPONSE .' or '. Abokifx::ARRAY_RESPONSE);
67
        }
68
        static::setHttpResponse($method, $url, $params);
69
70
        if (Abokifx::$responseType == Abokifx::ARRAY_RESPONSE) {
71
            return static::getResponseData();
72
        }
73
74
        return Util::convertArrayToObject(static::getResponse());
75
    }
76
77
    /**
78
     * Set options for making the Client request.
79
     */
80
    protected static function setRequestOptions(): void
81
    {
82
        $auth = Abokifx::getApiToken();
83
84
        static::$client = new Client(
85
            [
86
                'base_uri' => Abokifx::$apiBaseUrl,
87
                'headers' => [
88
                    'Authorization' => "Bearer " . $auth,
89
                    'Content-Type' => 'application/json',
90
                    'Accept' => 'application/json',
91
                ],
92
            ]
93
        );
94
    }
95
96
    /**
97
     * @param string $url
98
     * @param string $method
99
     * @param array $body
100
     *
101
     * @throws IsNullException
102
     * @throws ApiErrorException
103
     */
104
    private static function setHttpResponse($method, $url, $body = []): \GuzzleHttp\Psr7\Response
105
    {
106
        if (is_null($method)) {
0 ignored issues
show
The condition is_null($method) is always false.
Loading history...
107
            throw new IsNullException('Empty method not allowed');
108
        }
109
110
        static::setRequestOptions();
111
112
        try {
113
            static::$response = static::$client->{strtolower($method)}(
114
                Abokifx::$apiBaseUrl . '/' . $url,
115
                ['body' => json_encode($body)]
116
            );
117
118
            return static::$response;
119
        } catch (ClientException $exception) {
120
            throw new ApiErrorException($exception->getMessage());
121
        }
122
    }
123
124
    /**
125
     * Get the data response from an API operation.
126
     *
127
     * @return array
128
     */
129
    private static function getResponse(): array
130
    {
131
        return json_decode(static::$response->getBody(), true);
132
    }
133
134
    /**
135
     * Get the data response from a get operation.
136
     *
137
     * @return array
138
     */
139
    private static function getResponseData(): array
140
    {
141
        return json_decode(static::$response->getBody(), true)['response'];
142
    }
143
}
144