Passed
Branch feature/first-release (43e0cc)
by Andrea Marco
10:48
created

GuzzleAware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 21.43%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 9
c 2
b 0
f 0
dl 0
loc 50
ccs 3
cts 14
cp 0.2143
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A guzzleIsInstalled() 0 3 1
A sendRequest() 0 3 1
A requireGuzzle() 0 4 2
A getJson() 0 6 1
1
<?php
2
3
namespace Cerbero\JsonParser\Concerns;
4
5
use Cerbero\JsonParser\Exceptions\GuzzleRequiredException;
6
use GuzzleHttp\Client;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\UriInterface;
10
11
/**
12
 * The Guzzle-aware trait.
13
 *
14
 */
15
trait GuzzleAware
16
{
17
    /**
18
     * Abort if Guzzle is not loaded
19
     *
20
     * @return void
21
     * @throws GuzzleRequiredException
22
     */
23 2
    protected function requireGuzzle(): void
24
    {
25 2
        if (!$this->guzzleIsInstalled()) {
26 2
            throw new GuzzleRequiredException();
27
        }
28
    }
29
30
    /**
31
     * Determine whether Guzzle is installed
32
     *
33
     * @return bool
34
     */
35
    protected function guzzleIsInstalled(): bool
36
    {
37
        return class_exists(Client::class);
38
    }
39
40
    /**
41
     * Retrieve the JSON response of the given URL
42
     *
43
     * @param UriInterface|string $url
44
     * @return ResponseInterface
45
     */
46
    protected function getJson(UriInterface|string $url): ResponseInterface
47
    {
48
        return (new Client())->get($url, [
49
            'headers' => [
50
                'Accept' => 'application/json',
51
                'Content-Type' => 'application/json',
52
            ],
53
        ]);
54
    }
55
56
    /**
57
     * Retrieve the JSON response of the given request
58
     *
59
     * @param RequestInterface $request
60
     * @return ResponseInterface
61
     */
62
    protected function sendRequest(RequestInterface $request): ResponseInterface
63
    {
64
        return (new Client())->sendRequest($request);
65
    }
66
}
67