Client::getHttpClient()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace kop\kue;
4
5
use GuzzleHttp\Client as HttpClient;
6
use kop\kue\exceptions\ApiException;
7
use kop\kue\resources\Job;
8
use Psr\Log\LoggerInterface;
9
use Psr\Log\NullLogger;
10
11
/**
12
 * Class `Client`
13
 * ==============
14
 *
15
 * This class represents a client for Kue JSON API.
16
 *
17
 *
18
 * @link    https://kop.github.io/php-kue-client/ Project page.
19
 * @license https://github.com/kop/php-kue-client/blob/master/LICENSE.md MIT
20
 *
21
 * @author  Ivan Koptiev <[email protected]>
22
 */
23
class Client
24
{
25
    /**
26
     * @var HttpClient $httpClient Guzzle HTTP client.
27
     */
28
    private $httpClient;
29
30
    /**
31
     * @var LoggerInterface $logger PSR-3 compatible logger.
32
     */
33
    private $logger;
34
35
    /**
36
     * @var bool $throwExceptions Whether to throw exceptions in case of API request errors or just return `false`.
37
     */
38
    private $throwExceptions;
39
40
    /**
41
     * @var array $resources Instances of Kue API resources.
42
     */
43
    private $resources = [];
44
45
    /**
46
     * Class constructor.
47
     *
48
     * @param string $apiURI URI of the Kue JSON API server.
49
     * @param array $clientOptions Options that are used as default request options with every request created by the client.
50
     * You can use this param to configure proxy, authentication or other request settings.
51
     * See {@link http://docs.guzzlephp.org/en/latest/request-options.html Guzzle documentation} for options available.
52
     * @param LoggerInterface $logger PSR-3 compatible logger to use. Logging is disabled by default.
53
     * @param bool $throwExceptions Whether to throw exceptions in case of API request errors or just return `false`.
54
     * Exceptions are disabled by default.
55
     */
56
    public function __construct($apiURI, array $clientOptions = [], LoggerInterface $logger = null, $throwExceptions = false)
57
    {
58
        $this->httpClient = new HttpClient(array_merge($clientOptions, [
59
            'base_uri' => $apiURI,
60
            'headers' => [
61
                'Accept' => 'application/json',
62
            ]
63
        ]));
64
65
        $this->setLogger($logger);
66
        $this->setThrowExceptions($throwExceptions);
67
    }
68
69
    /**
70
     * Responds with state counts, and worker activity time in milliseconds.
71
     *
72
     * @return bool|mixed API response or `false` if API request fails.
73
     * @throws \kop\kue\exceptions\ApiException If API request fails and {@link Client::$_throwExceptions} is enabled.
74
     */
75
    public function stats()
76
    {
77
        return $this->request('GET', 'stats');
78
    }
79
80
    /**
81
     * Returns a `Job` resource object.
82
     *
83
     * This object implements commands that are related to the Kue jobs.
84
     *
85
     * @return Job
86
     */
87
    public function jobs()
88
    {
89
        if (!isset($this->resources[Job::class])) {
90
            $this->resources[Job::class] = new Job($this);
91
        }
92
93
        return $this->resources[Job::class];
94
    }
95
96
    /**
97
     * Returns Guzzle HTTP client.
98
     *
99
     * @return HttpClient
100
     */
101
    public function getHttpClient()
102
    {
103
        return $this->httpClient;
104
    }
105
106
    /**
107
     * Sets a logger instance to use.
108
     *
109
     * @param LoggerInterface|null $logger PSR-3 compatible logger or null to disable logging.
110
     */
111
    public function setLogger(LoggerInterface $logger = null)
112
    {
113
        $this->logger = $logger;
114
    }
115
116
    /**
117
     * Returns a logger instance.
118
     *
119
     * @return LoggerInterface
120
     */
121
    public function getLogger()
122
    {
123
        if (!$this->logger) {
124
            $this->logger = new NullLogger();
125
        }
126
127
        return $this->logger;
128
    }
129
130
    /**
131
     * Sets an option whether to throw API exceptions or not.
132
     *
133
     * @param bool $enabled Whether to throw exceptions.
134
     */
135
    public function setThrowExceptions($enabled = true)
136
    {
137
        $this->throwExceptions = $enabled;
138
    }
139
140
    /**
141
     * Returns an option whether to throw API exceptions or not.
142
     *
143
     * @return bool Whether to throw exceptions
144
     */
145
    public function getThrowExceptions()
146
    {
147
        return $this->throwExceptions;
148
    }
149
150
    /**
151
     * Executes a request against the Kue JSON API.
152
     *
153
     * @param string $method HTTP method to use (e.g. GET, POST, etc).
154
     * @param string $path Request path.
155
     * @param array $options Additional request options.
156
     *
157
     * @return bool|mixed API response or `false` if API request fails.
158
     * @throws \kop\kue\exceptions\ApiException If API request fails and {@link Client::$_throwExceptions} is enabled.
159
     */
160
    public function request($method, $path, array $options = [])
161
    {
162
        // Make request
163
        $this->getLogger()->debug("Executing Kue API request: {$method} {$path}", $options);
164
        $response = $this->httpClient->request($method, $path, $options);
165
166
        // Success
167
        if ($response->getStatusCode() === 200) {
168
            $this->getLogger()->debug('API request successfully completed.', [
169
                'response' => $response->getBody(),
170
            ]);
171
            return json_decode($response->getBody());
172
        }
173
174
        // Failure
175
        $this->getLogger()->error('Kue API error #' . $response->getStatusCode(), [
176
            'reason' => $response->getReasonPhrase(),
177
            'body' => $response->getBody(),
178
        ]);
179
        if ($this->getThrowExceptions()) {
180
            throw new ApiException($response->getStatusCode(), $response->getBody());
181
        }
182
183
        return false;
184
    }
185
}