|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Speicher210\Monsum\Api; |
|
4
|
|
|
|
|
5
|
|
|
use JMS\Serializer\SerializerInterface; |
|
6
|
|
|
use Speicher210\Monsum\Api\Exception\ApiResponseException; |
|
7
|
|
|
use Speicher210\Monsum\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 Monsum. |
|
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), true)) { |
|
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
|
|
|
|