Completed
Pull Request — master (#26)
by Karl
02:15
created

AbstractProvider   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 380
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 11
Bugs 1 Features 2
Metric Value
wmc 33
c 11
b 1
f 2
lcom 1
cbo 4
dl 0
loc 380
ccs 94
cts 94
cp 1
rs 9.4

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
createJobObject() 0 1 ?
getDefaultResponseFields() 0 1 ?
getListingsPath() 0 1 ?
A getClientResponse() 0 17 1
A getFormat() 0 4 1
A getJobs() 0 18 3
A getSource() 0 6 1
A parseAttributeDefaults() 0 9 2
A parseLocation() 0 4 1
A setClient() 0 6 1
A setQuery() 0 6 1
A getJobsCollectionFromListings() 0 17 1
A getRawListings() 0 12 2
A getValue() 0 17 4
A parseAsFormat() 0 10 2
A getValueCurrentIndex() 0 4 3
A isArrayNotEmpty() 0 4 2
A parseAsJson() 0 16 3
A parseAsXml() 0 19 2
1
<?php namespace JobApis\Jobs\Client\Providers;
2
3
use GuzzleHttp\Client as HttpClient;
4
use JobApis\Jobs\Client\Collection;
5
use JobApis\Jobs\Client\Exceptions\MissingParameterException;
6
use JobApis\Jobs\Client\Queries\AbstractQuery;
7
8
abstract class AbstractProvider
9
{
10
    /**
11
     * HTTP Client
12
     *
13
     * @var HttpClient
14
     */
15
    protected $client;
16
17
    /**
18
     * Query params
19
     *
20
     * @var array
21
     */
22
    protected $query;
23
24
    /**
25
     * Create new client
26
     *
27
     * @param array $parameters
0 ignored issues
show
Bug introduced by
There is no parameter named $parameters. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
28
     */
29 14
    public function __construct(AbstractQuery $query)
30
    {
31 14
        $this->setQuery($query)
32 14
            ->setClient(new HttpClient);
33 14
    }
34
35
    /**
36
     * Returns the standardized job object
37
     *
38
     * @param array|object $payload
39
     *
40
     * @return \JobApis\Jobs\Client\Job
41
     */
42
    abstract public function createJobObject($payload);
43
44
    /**
45
     * Job response object default keys that should be set
46
     *
47
     * @return  string
48
     */
49
    abstract public function getDefaultResponseFields();
50
51
    /**
52
     * Get listings path
53
     *
54
     * @return  string
55
     */
56
    abstract public function getListingsPath();
57
58
    /**
59
     * Uses the Query to make a call to the client
60
     *
61
     * @return \Psr\Http\Message\ResponseInterface
62
     */
63 4
    public function getClientResponse()
64
    {
65
        // Create a local copy of the client object
66 4
        $client = $this->client;
67
68
        // GET or POST request
69 4
        $verb = strtolower($this->query->getVerb());
0 ignored issues
show
Bug introduced by
The method getVerb cannot be called on $this->query (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
70
71
        // The URL string
72 4
        $url = $this->query->getUrl();
0 ignored issues
show
Bug introduced by
The method getUrl cannot be called on $this->query (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
73
74
        // HTTP method options
75 4
        $options = $this->query->getHttpMethodOptions();
0 ignored issues
show
Bug introduced by
The method getHttpMethodOptions cannot be called on $this->query (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
76
77
        // Get the response
78 4
        return $client->{$verb}($url, $options);
79
    }
80
81
    /**
82
     * Get format
83
     *
84
     * @return  string Currently only 'json' and 'xml' supported
85
     */
86 4
    public function getFormat()
87
    {
88 4
        return 'json';
89
    }
90
91
    /**
92
     * Makes the api call and returns a collection of job objects
93
     *
94
     * @return  \JobApis\Jobs\Client\Collection
95
     * @throws MissingParameterException
96
     */
97 4
    public function getJobs()
98
    {
99
        // Verify that all required query vars are set
100 4
        if ($this->query->isValid()) {
0 ignored issues
show
Bug introduced by
The method isValid cannot be called on $this->query (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
101
            // Get the response from the client using the query
102 2
            $response = $this->getClientResponse();
103
            // Get the response body as a string
104 2
            $body = (string) $response->getBody();
105
            // Parse the string
106 2
            $payload = $this->parseAsFormat($body, $this->getFormat());
107
            // Gets listings if they're nested
108 2
            $listings = is_array($payload) ? $this->getRawListings($payload) : [];
109
            // Return a job collection
110 2
            return $this->getJobsCollectionFromListings($listings);
111
        } else {
112 2
            throw new MissingParameterException("All Required parameters for this provider must be set");
113
        }
114
    }
115
116
    /**
117
     * Get source attribution
118
     *
119
     * @return string
120
     */
121 4
    public function getSource()
122
    {
123 4
        $ref = new \ReflectionClass(get_class($this));
124
125 4
        return $ref->getShortName();
126
    }
127
128
    /**
129
     * Parse job attributes against defaults
130
     *
131
     * @param  array $attributes
132
     * @param  array $defaults
133
     *
134
     * @return array
135
     */
136 4
    public static function parseAttributeDefaults(array $attributes, array $defaults = array())
137
    {
138
        array_map(function ($attribute) use (&$attributes) {
139 4
            if (!isset($attributes[$attribute])) {
140 4
                $attributes[$attribute] = null;
141 4
            }
142 4
        }, $defaults);
143 4
        return $attributes;
144
    }
145
146
    /**
147
     * Parse location string into components.
148
     *
149
     * @param string $location
150
     *
151
     * @return  array
152
     **/
153 2
    public static function parseLocation($location, $separator = ', ')
154
    {
155 2
        return explode($separator, $location);
156
    }
157
158
    /**
159
     * Sets http client
160
     *
161
     * @param HttpClient $client
162
     *
163
     * @return  AbstractProvider
164
     */
165 14
    public function setClient(HttpClient $client)
166
    {
167 14
        $this->client = $client;
168
169 14
        return $this;
170
    }
171
172
    /**
173
     * Sets query object
174
     *
175
     * @param AbstractQuery $query
176
     *
177
     * @return  AbstractProvider
178
     */
179 14
    public function setQuery(AbstractQuery $query)
180
    {
181 14
        $this->query = $query;
0 ignored issues
show
Documentation Bug introduced by
It seems like $query of type object<JobApis\Jobs\Client\Queries\AbstractQuery> is incompatible with the declared type array of property $query.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
182
183 14
        return $this;
184
    }
185
186
    /**
187
     * Create and get collection of jobs from given listings
188
     *
189
     * @param  array $listings
190
     *
191
     * @return Collection
192
     */
193 2
    protected function getJobsCollectionFromListings(array $listings = [])
194
    {
195 2
        $collection = new Collection;
196
197 2
        array_map(function ($item) use ($collection) {
198 2
            $item = static::parseAttributeDefaults(
199 2
                $item,
200 2
                $this->getDefaultResponseFields()
0 ignored issues
show
Documentation introduced by
$this->getDefaultResponseFields() is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
201 2
            );
202 2
            $job = $this->createJobObject($item);
203 2
            $job->setQuery($this->query->getKeyword())
0 ignored issues
show
Bug introduced by
The method getKeyword cannot be called on $this->query (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
204 2
                ->setSource($this->getSource());
205 2
            $collection->add($job);
206 2
        }, $listings);
207
208 2
        return $collection;
209
    }
210
211
    /**
212
     * Get raw listings from payload
213
     *
214
     * @param  array $payload
215
     *
216
     * @return array
217
     */
218 2
    protected function getRawListings(array $payload = array())
219
    {
220 2
        $path = $this->getListingsPath();
221
222 2
        if (!empty($path)) {
223 2
            $index = explode('.', $path);
224
225 2
            return (array) self::getValue($index, $payload);
226
        }
227
228
        return (array) $payload;
229
    }
230
231
    /**
232
     * Navigate through a payload array looking for a particular index
233
     *
234
     * @param array $index The index sequence we are navigating down
235
     * @param array $value The portion of the config array to process
236
     *
237
     * @return mixed
238
     */
239 2
    protected static function getValue($index, $value)
240
    {
241 2
        $current_index = self::getValueCurrentIndex($index);
242
243 2
        if (isset($value[$current_index])) {
244 2
            $index_array = self::isArrayNotEmpty($index);
245 2
            $value_array = self::isArrayNotEmpty($value[$current_index]);
246
247 2
            if ($index_array && $value_array) {
248
                return self::getValue($index, $value[$current_index]);
249
            } else {
250 2
                return $value[$current_index];
251
            }
252
        } else {
253
            throw new \OutOfRangeException("Attempt to access missing variable: $current_index");
254
        }
255
    }
256
257
    /**
258
     * Attempt to parse string as given format
259
     *
260
     * @param  string  $string
261
     * @param  string  $format
262
     *
263
     * @return array
264
     */
265 2
    protected function parseAsFormat($string, $format)
266
    {
267 2
        $method = 'parseAs'.ucfirst(strtolower($format));
268
269 2
        if (method_exists($this, $method)) {
270 2
            return $this->$method($string);
271
        }
272
273
        return [];
274
    }
275
276
    /**
277
     * Get value current index
278
     *
279
     * @param  mixed $index
280
     *
281
     * @return array|null
282
     */
283 2
    private static function getValueCurrentIndex(&$index)
284
    {
285 2
        return is_array($index) && count($index) ? array_shift($index) : null;
286
    }
287
288
    /**
289
     * Checks if given value is an array and that it has contents
290
     *
291
     * @param  mixed $array
292
     *
293
     * @return boolean
294
     */
295 2
    private static function isArrayNotEmpty($array)
296
    {
297 2
        return is_array($array) && count($array);
298
    }
299
300
    /**
301
     * Attempt to parse as Json
302
     *
303
     * @param  string $string
304
     *
305
     * @return array
306
     */
307 2
    private function parseAsJson($string)
308
    {
309
        try {
310 2
            $json = json_decode($string, true);
311
312 2
            if (json_last_error() != JSON_ERROR_NONE) {
313
                throw new \Exception;
314
            }
315
316 2
            return $json;
317
        } catch (\Exception $e) {
318
            // Ignore malformed json.
319
        }
320
321
        return [];
322
    }
323
324
    /**
325
     * Attempt to parse as XML
326
     *
327
     * @param  string $string
328
     *
329
     * @return array
330
     */
331
    private function parseAsXml($string)
332
    {
333
        try {
334
            return json_decode(
335
                json_encode(
336
                    simplexml_load_string(
337
                        $string,
338
                        null,
339
                        LIBXML_NOCDATA
340
                    )
341
                ),
342
                true
343
            );
344
        } catch (\Exception $e) {
345
            // Ignore malformed xml.
346
        }
347
348
        return [];
349
    }
350
}
351