AbstractService::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Speicher210\Fastbill\Api;
4
5
use JMS\Serializer\SerializerInterface;
6
use Speicher210\Fastbill\Api\Exception\ApiResponseException;
7
use Speicher210\Fastbill\Api\Transport\TransportInterface;
8
9
/**
10
 * Abstract service.
11
 */
12
abstract class AbstractService implements ServiceInterface
13
{
14
    /**
15
     * Transport for the requests.
16
     *
17
     * @var TransportInterface
18
     */
19
    protected $transport;
20
21
    /**
22
     * @var SerializerInterface
23
     */
24
    protected $serializer;
25
26
    /**
27
     * Constructor.
28
     *
29
     * @param TransportInterface $transport Transport for the requests.
30
     * @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses.
31
     */
32 141
    public function __construct(TransportInterface $transport, SerializerInterface $serializer)
33
    {
34 141
        $this->transport = $transport;
35 141
        $this->serializer = $serializer;
36 141
    }
37
38
    /**
39
     * Send a request to fastbill.
40
     *
41
     * @param mixed $request The request to send.
42
     * @param string $responseClass The class that should be used to unserialize the response.
43
     * @return ApiResponseInterface
44
     * @throws ApiResponseException If the API response has errors.
45
     */
46 135
    protected function sendRequest(RequestInterface $request, $responseClass)
47
    {
48 135
        if (!in_array(ApiResponseInterface::class, class_implements($responseClass))) {
49
            throw new \InvalidArgumentException('The response class must implement "'.ApiResponseInterface::class.'".');
50
        }
51
52 135
        $body = $this->serializer->serialize($request, 'json');
53 135
        $response = $this->transport->sendRequest($body);
54
55
        /** @var ApiResponseInterface $apiResponse */
56 135
        $apiResponse = $this->serializer->deserialize($response, $responseClass, 'json');
57 135
        if ($apiResponse->getResponse() !== null && $apiResponse->getResponse()->hasErrors()) {
58 18
            throw new ApiResponseException(
59 18
                sprintf('Error calling "%s"', $request->getService()),
60 18
                $apiResponse->getResponse()->getErrors()
61 18
            );
62
        }
63
64 117
        return $apiResponse;
65
    }
66
}
67