Completed
Push — master ( 78ef8c...6e8e35 )
by Luke
03:10
created

AbstractMethod::validateAndSend()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.9256

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
nc 1
nop 3
dl 0
loc 29
ccs 10
cts 15
cp 0.6667
crap 5.9256
rs 8.439
c 2
b 0
f 0
1
<?php
2
3
namespace ZpgRtf\Methods;
4
5
use GuzzleHttp\Exception\ClientException;
6
use GuzzleHttp\Client;
7
use League\JsonGuard\Validator;
8
use League\JsonReference\Dereferencer;
9
10
/**
11
 * The listing method allows you to list, update or delete listings on the ZPG rtf.
12
 */
13
abstract class AbstractMethod
14
{
15
    /** @var array */
16
    private $baseUri = [
17
        'sandbox' => 'https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/',
18
        'live' => 'https://realtime-listings-api.webservices.zpg.co.uk/live/v1/',
19
    ];
20
21
    /** @var Client */
22
    private $client;
23
24
    /**
25
     * @param string $certificate
26
     *
27
     * @throws \Exception You will get an exception if you use an invalid environment variable.
28
     */
29 6
    public function __construct($certificate, $env = 'sandbox')
30
    {
31 6
        if (!in_array($env,['sandbox', 'live'])) {
32
            throw new \Exception(sprintf('Invalid environment. %s is not in [sandbox, live]', $env));
33
        }
34
35 6
        $this->client = new Client([
36 6
            'base_uri' => $this->baseUri[$env],
37 6
            'cert' => $certificate
38
        ]);
39 6
    }
40
41
    /**
42
     * @return Client
43
     */
44 3
    public function getClient()
45
    {
46 3
        return $this->client;
47
    }
48
49
    /**
50
     * @param Client $client
51
     *
52
     * @return static
53
     */
54 6
    public function setClient(Client $client)
55
    {
56 6
        $this->client = $client;
57
58 6
        return $this;
59
    }
60
61
    /**
62
     * @param string $schemaUri
63
     * @param string $uri
64
     * @param \JsonSerializable $object
65
     *
66
     * @return \GuzzleHttp\Psr7\Response
67
     *
68
     * @throws \Exception If validation fails. Needs a custom exception type.
69
     */
70 6
    protected function validateAndSend($schemaUri, $uri, \JsonSerializable $object)
71
    {
72 6
        $payload = json_encode($object);
73 6
        $schema = Dereferencer::draft4()->dereference($schemaUri);
74 6
        $validator = new Validator(json_decode($payload), $schema);
75
76
        // Let's improve this with some sort of factory method to handle the response into a custom response type
77
        // whether it's a normal response, validation error or guzzle exception.
78 6
        if ($validator->fails()) {
79 3
            throw new \Exception('Fails validation');
80
        }
81
82
        try{
83 3
            $response = $this->getClient()->request('POST', $uri, [
84 3
                'body' => $payload,
85
                'headers' => [
86 3
                    'Content-Type' => 'application/json; profile=' . $schemaUri,
87
                ],
88
            ]);
89
90 3
            return $response;
91
        } catch (ClientException $e) {
92
            $responseContents = json_decode($e->getResponse()->getBody(true)->getContents(), true);
0 ignored issues
show
Unused Code introduced by
The call to Psr\Http\Message\MessageInterface::getBody() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

92
            $responseContents = json_decode($e->getResponse()->getBody(/** @scrutinizer ignore-call */ true)->getContents(), true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
93
94
            if (false !== $responseContents && !empty($responseContents['error_advice'])) {
95
                throw new \Exception($responseContents['error_advice']);
96
            }
97
98
            throw new \Exception($e->getMessage());
99
        }
100
    }
101
}
102