1 <?php
2 3 4
5 namespace Team3\PayU\Communication\Process\ResponseDeserializer;
6
7 use Buzz\Message\MessageInterface;
8 use Team3\PayU\Communication\Process\RequestProcessException;
9 use Team3\PayU\Communication\Request\PayURequestInterface;
10 use Team3\PayU\Communication\Response\ResponseInterface;
11 use Team3\PayU\Serializer\SerializerException;
12 use Team3\PayU\Serializer\SerializerInterface;
13
14 15 16
17 class ResponseDeserializer implements ResponseDeserializerInterface
18 {
19 20 21
22 private $responses;
23
24 25 26
27 private $serializer;
28
29 30 31
32 public function __construct(SerializerInterface $serializer)
33 {
34 $this->responses = [];
35 $this->serializer = $serializer;
36 }
37
38 39 40 41 42
43 public function addResponse(ResponseInterface $response)
44 {
45 $this->responses[] = $response;
46
47 return $this;
48 }
49
50 51 52 53 54
55 public function setResponses(array $responses)
56 {
57 $this->responses = $responses;
58
59 return $this;
60 }
61
62 63 64 65 66 67 68
69 public function deserializeResponse(
70 MessageInterface $curlResponse,
71 PayURequestInterface $payURequest
72 ) {
73 return $this
74 ->deserialize(
75 $curlResponse,
76 $this->getResponseClass($payURequest)
77 );
78 }
79
80 81 82 83 84 85
86 private function getResponseClass(
87 PayURequestInterface $payURequest
88 ) {
89 foreach ($this->responses as $response) {
90 if ($response->supports($payURequest)) {
91 return get_class($response);
92 }
93 }
94
95 throw new NoResponseFoundException(sprintf(
96 'No response class that supports %s was found',
97 get_class($payURequest)
98 ));
99 }
100
101 102 103 104 105 106 107
108 private function deserialize(
109 MessageInterface $curlResponse,
110 $responseClass
111 ) {
112 try {
113 return $this
114 ->serializer
115 ->fromJson(
116 $curlResponse->getContent(),
117 $responseClass
118 );
119 } catch (SerializerException $exception) {
120 throw new RequestProcessException(
121 sprintf(
122 'Exception %s was thrown during deserialization. Message: "%s"',
123 get_class($exception),
124 $exception->getMessage()
125 ),
126 $exception->getCode(),
127 $exception
128 );
129 }
130 }
131 }
132