Completed
Push — master ( f66f76...b92ed5 )
by Luke
01:31
created

AbstractMethod::validateAndSend()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 2
rs 9.4285
1
<?php
2
3
namespace ZpgRtf\Methods;
4
5
use GuzzleHttp\Client;
6
use League\JsonGuard\Validator;
7
use League\JsonReference\Dereferencer;
8
9
/**
10
 * The listing method allows you to list, update or delete listings on the ZPG rtf.
11
 */
12
abstract class AbstractMethod
13
{
14
    /** @var string */
15
    const BASE_URI = 'https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/';
16
17
    /** @var Client */
18
    private $client;
19
20
    /**
21
     * @param string $certificate
22
     */
23 2
    public function __construct($certificate)
24
    {
25 2
        $this->client = new Client([
26 2
            'base_uri' => self::BASE_URI,
27 2
            'cert' => $certificate,
28
        ]);
29 2
    }
30
31
    /**
32
     * @return Client
33
     */
34 1
    public function getClient()
35
    {
36 1
        return $this->client;
37
    }
38
39
    /**
40
     * @param Client $client
41
     *
42
     * @return static
43
     */
44 2
    public function setClient(Client $client)
45
    {
46 2
        $this->client = $client;
47
48 2
        return $this;
49
    }
50
51
    /**
52
     * @param string $schemaUri
53
     * @param string $uri
54
     * @param \JsonSerializable $object
55
     *
56
     * @return \GuzzleHttp\Psr7\Response
57
     *
58
     * @throws \Exception If validation fails. Needs a custom exception type.
59
     */
60 2
    protected function validateAndSend($schemaUri, $uri, \JsonSerializable $object)
61
    {
62 2
        $payload = json_encode($object);
63 2
        $schema = Dereferencer::draft4()->dereference($schemaUri);
64 2
        $validator = new Validator(json_decode($payload), $schema);
65
66 2
        if ($validator->fails()) {
67 1
            throw new \Exception('Fails validation');
68
        }
69
70 1
        return $this->getClient()->request('POST', $uri, [
71 1
            'body' => $payload
72
        ]);
73
    }
74
}
75