Completed
Push — master ( 2222d5...7d7847 )
by WEBEWEB
01:48
created

AbstractProvider::setLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the pexels-library package.
5
 *
6
 * (c) 2019 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Library\Pexels\Provider;
13
14
use DateTime;
15
use Exception;
16
use GuzzleHttp\Client;
17
use InvalidArgumentException;
18
use Psr\Log\LoggerInterface;
19
use WBW\Library\Pexels\API\PaginateResponseInterface;
20
use WBW\Library\Pexels\API\SubstituteRequestInterface;
21
use WBW\Library\Pexels\Exception\APIException;
22
use WBW\Library\Pexels\Model\AbstractRequest;
23
use WBW\Library\Pexels\Traits\RateLimitTrait;
24
25
/**
26
 * Abstract provider.
27
 *
28
 * @author webeweb <https://github.com/webeweb/>
29
 * @package WBW\Library\Pexels\Provider
30
 * @abstract
31
 */
32
abstract class AbstractProvider {
33
34
    use RateLimitTrait;
35
36
    /**
37
     * Endpoint path.
38
     *
39
     * @var string
40
     */
41
    const ENDPOINT_PATH = "https://api.pexels.com";
42
43
    /**
44
     * Authorization.
45
     *
46
     * @var string
47
     */
48
    private $authorization;
49
50
    /**
51
     * Debug.
52
     *
53
     * @var bool
54
     */
55
    private $debug;
56
57
    /**
58
     * Logger.
59
     *
60
     * @var LoggerInterface
61
     */
62
    private $logger;
63
64
    /**
65
     * Constructor.
66
     *
67
     * @param string $authorization The authorization.
68
     * @param LoggerInterface|null $logger The logger.
69
     */
70
    public function __construct($authorization = null, LoggerInterface $logger = null) {
71
        $this->setAuthorization($authorization);
72
        $this->setDebug(false);
73
        $this->setLogger($logger);
74
    }
75
76
    /**
77
     * Build the configuration.
78
     *
79
     * @return array Returns the configuration.
80
     */
81
    private function buildConfiguration() {
82
        return [
83
            "debug"       => $this->getDebug(),
84
            "headers"     => [
85
                "Accept"        => "application/json",
86
                "User-Agent"    => "webeweb/pexels-library",
87
                "Authorization" => $this->getAuthorization(),
88
            ],
89
            "synchronous" => true,
90
        ];
91
    }
92
93
    /**
94
     * Build a resource path.
95
     *
96
     * @param AbstractRequest $request The request.
97
     * @return string Returns the resource path.
98
     * @throws InvalidArgumentException Throws an invalid argument exception if a parameter is missing.
99
     */
100
    private function buildResourcePath(AbstractRequest $request) {
101
102
        if (false === ($request instanceof SubstituteRequestInterface)) {
103
            return $request->getResourcePath();
104
        }
105
106
        if (null === $request->getSubstituteValue()) {
107
            throw new InvalidArgumentException(sprintf("The substitute value %s is missing", $request->getSubstituteName()));
108
        }
109
110
        return str_replace($request->getSubstituteName(), $request->getSubstituteValue(), $request->getResourcePath());
111
    }
112
113
    /**
114
     * Call the API.
115
     *
116
     * @param string $uri The URI.
117
     * @param array $queryData The query data.
118
     * @return string Returns the raw response.
119
     * @throws APIException Throws an API exception if an error occurs.
120
     * @throws InvalidArgumentException Throws an invalid argument exception if a parameter is missing.
121
     */
122
    private function callAPI($uri, array $queryData) {
123
124
        if (null === $this->getAuthorization()) {
125
            throw new InvalidArgumentException("The mandatory parameter \"authorization\" is missing");
126
        }
127
128
        try {
129
130
            $config = $this->buildConfiguration();
131
132
            $client = new Client($config);
133
134
            $method  = "GET";
135
            $options = 0 < count($queryData) ? ["query" => $queryData] : [];
136
137
            $this->log(sprintf("Call Pexels API %s %s", $method, $uri), ["config" => $config, "options" => $options]);
138
139
            $response = $client->request($method, $uri, $options);
140
141
            $this->setLimit(intval($response->getHeaderLine("X-Ratelimit-Limit")));
142
            $this->setRemaining(intval($response->getHeaderLine("X-Ratelimit-Remaining")));
143
            $this->setReset(new DateTime("@" . $response->getHeaderLine("X-Ratelimit-Reset")));
144
145
            return $response->getBody()->getContents();
146
        } catch (Exception $ex) {
147
148
            throw new APIException("Call Pexels API failed", $ex);
149
        }
150
    }
151
152
    /**
153
     * Call the API.
154
     *
155
     * @param AbstractRequest $request The request.
156
     * @param array $queryData The query data.
157
     * @return string Returns the raw response.
158
     * @throws APIException Throws an API exception if an error occurs.
159
     * @throws InvalidArgumentException Throws an invalid argument exception if a parameter is missing.
160
     */
161
    protected function callAPIWithRequest(AbstractRequest $request, array $queryData) {
162
163
        try {
164
165
            $uri = self::ENDPOINT_PATH . $this->buildResourcePath($request);
166
167
            return $this->callAPI($uri, $queryData);
168
        } catch (InvalidArgumentException $ex) {
169
170
            throw $ex;
171
        }
172
    }
173
174
    /**
175
     * Call the API.
176
     *
177
     * @param PaginateResponseInterface $response The request.
178
     * @param bool $nextPage Next page ?.
179
     * @return string Returns the raw response.
180
     * @throws APIException Throws an API exception if an error occurs.
181
     * @throws InvalidArgumentException Throws an invalid argument exception if a parameter is missing.
182
     */
183
    protected function callAPIWithResponse(PaginateResponseInterface $response, $nextPage) {
184
185
        try {
186
187
            $uri = false === $nextPage ? $response->getPrevPage() : $response->getNextPage();
188
            if (null === $uri) {
189
                return "";
190
            }
191
192
            return $this->callAPI($uri, []);
193
        } catch (InvalidArgumentException $ex) {
194
195
            throw $ex;
196
        }
197
    }
198
199
    /**
200
     * Get the authorization.
201
     *
202
     * @return string Returns the authorization.
203
     */
204
    public function getAuthorization() {
205
        return $this->authorization;
206
    }
207
208
    /**
209
     * Get the debug.
210
     *
211
     * @return bool Returns the debug.
212
     */
213
    public function getDebug() {
214
        return $this->debug;
215
    }
216
217
    /**
218
     * Get the logger.
219
     *
220
     * @return LoggerInterface Returns the logger.
221
     */
222
    public function getLogger() {
223
        return $this->logger;
224
    }
225
226
    /**
227
     * Log.
228
     *
229
     * @param string $message The message.
230
     * @param array $context The context.
231
     * @return AbstractProvider Returns this provider.
232
     */
233
    protected function log($message, array $context) {
234
        if (null !== $this->getLogger()) {
235
            $this->getLogger()->info($message, $context);
236
        }
237
        return $this;
238
    }
239
240
    /**
241
     * Set the authorization.
242
     *
243
     * @param string $authorization The authorization.
244
     * @return AbstractProvider Returns this provider.
245
     */
246
    public function setAuthorization($authorization) {
247
        $this->authorization = $authorization;
248
        return $this;
249
    }
250
251
    /**
252
     * Set the debug.
253
     *
254
     * @param bool $debug The debug.
255
     * @return AbstractProvider Returns this provider.
256
     */
257
    public function setDebug($debug) {
258
        $this->debug = $debug;
259
        return $this;
260
    }
261
262
    /**
263
     * Set the logger.
264
     *
265
     * @param LoggerInterface|null $logger The logger
266
     * @return AbstractProvider Returns this provider
267
     */
268
    protected function setLogger(LoggerInterface $logger = null) {
269
        $this->logger = $logger;
270
        return $this;
271
    }
272
}
273