Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.15% covered (success)
96.15%
75 / 78
91.67% covered (success)
91.67%
11 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
Result
96.15% covered (success)
96.15%
75 / 78
91.67% covered (success)
91.67%
11 / 12
33
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setResponse
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 testMeta
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
9
 getRequest
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getResponse
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isStatus
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getEntity
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getCollection
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 getData
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getMeta
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getIds
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
7.33
 setData
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3namespace BO\Zmsclient;
4
5use BO\Mellon\Valid;
6use BO\Mellon\Validator;
7use BO\Zmsentities\Metaresult;
8use BO\Zmsentities\Collection\Base as BaseCollection;
9use BO\Zmsentities\Schema\Entity;
10use BO\Zmsentities\Schema\Factory;
11use Psr\Http\Message\RequestInterface;
12use Psr\Http\Message\ResponseInterface;
13
14/**
15 * Handle default response
16 */
17class Result
18{
19    /**
20     * @var ResponseInterface
21     */
22    protected $response;
23
24    /**
25     * @var RequestInterface|null
26     */
27    protected $request;
28
29    /**
30     * @var Entity[]|null
31     */
32    protected $data = null;
33
34    /**
35     * @var Metaresult|null
36     */
37    protected $meta = null;
38
39    /**
40     * @param ResponseInterface $response
41     * @param RequestInterface|null $request (optional) reference for better error messages
42     */
43    public function __construct(
44        ResponseInterface $response,
45        RequestInterface $request = null
46    ) {
47        $this->request = $request;
48        $this->response = $response;
49    }
50
51    /**
52     * Parse response and the object values
53     * @param ResponseInterface $response
54     * @return self
55     */
56    public function setResponse(ResponseInterface $response)
57    {
58        $body = Validator::value((string) $response->getBody())->isJson();
59        $this->testMeta($body, $response);
60        $result = $body->getValue();
61        if (array_key_exists("data", $result)) {
62            $this->setData($result['data']);
63        }
64        return $this;
65    }
66
67    /**
68     * Test meta data on errors
69     *
70     * @param Valid $body
71     * @param ResponseInterface $response
72     *
73     * @throws Exception
74     *
75     * @return void
76     */
77    protected function testMeta($body, ResponseInterface $response)
78    {
79        if ($body->hasFailed()) {
80            $content = (string) $response->getBody();
81            throw new Exception\ApiFailed(
82                'API-Call failed, JSON parsing with error: ' . $body->getMessages()
83                . ' - Snippet: ' . substr(\strip_tags($content), 0, 2000) . '[...]',
84                $response,
85                $this->request
86            );
87        }
88        $result = $body->getValue();
89        if (!$result || !array_key_exists("meta", $result)) {
90            throw new Exception(
91                'Missing "meta" value on result, API-Call failed.',
92                $response,
93                $this->request
94            );
95        }
96        $entity = Factory::create($result['meta'])->getEntity();
97        $this->meta = $entity;
98        if ($entity->error == true) {
99            $message = $entity->message ? $entity->message : $entity->exception;
100            $exception = new Exception(
101                'API-Error: ' . $message,
102                $response,
103                $this->request
104            );
105            if (isset($entity->trace)) {
106                $exception->trace = $entity['trace'];
107            }
108            $exception->originalMessage = $entity->message;
109            if (array_key_exists('data', $result)) {
110                $exception->data = $result['data'];
111            }
112            if (isset($entity->exception)) {
113                $exception->template = $entity->exception;
114            }
115            throw $exception;
116        }
117    }
118
119    /**
120     * Get the origin request
121     *
122     * @return RequestInterface|null
123     */
124    public function getRequest()
125    {
126        return $this->request;
127    }
128
129    /**
130     * Get the origin response
131     *
132     * @return ResponseInterface
133     */
134    public function getResponse()
135    {
136        return $this->response;
137    }
138
139    /**
140     * Get the origin response
141     *
142     * @return bool
143     */
144    public function isStatus($statuscode)
145    {
146        return $this->getResponse()->getStatusCode() == $statuscode;
147    }
148
149    /**
150     * Description
151     *
152     * @return Entity|null|false
153     */
154    public function getEntity()
155    {
156        $entity = null;
157        if (null !== $this->getData()) {
158            $data = $this->getData();
159            $entity = reset($data);
160        }
161        return $entity;
162    }
163
164    /**
165     * Description
166     *
167     * @return BaseCollection|null
168     */
169    public function getCollection()
170    {
171        $collection = null;
172        $entity = $this->getEntity();
173        if (null !== $entity) {
174            $class = get_class($entity);
175            $alias = ucfirst(preg_replace('#^.*\\\#', '', $class) ?? '');
176            $className = "\\BO\\Zmsentities\\Collection\\" . $alias . "List";
177            $collection = new $className($this->getData());
178        }
179        return $collection;
180    }
181
182    /**
183     * Description
184     *
185     * @return Entity[]|null
186     */
187    public function getData()
188    {
189        if (null === $this->data) {
190            $this->setResponse($this->response);
191        }
192        return $this->data;
193    }
194
195    /**
196     * Description
197     *
198     * @return Metaresult|null
199     */
200    public function getMeta()
201    {
202        if (null === $this->meta) {
203            $this->setResponse($this->response);
204        }
205        return $this->meta;
206    }
207
208    /**
209     * Get the list of IDs from the data
210     *
211     * @return string
212     */
213    public function getIds()
214    {
215        $data = $this->getData();
216        $idList = [];
217
218        foreach ($data as $item) {
219            if (is_object($item) && method_exists($item, 'getId')) {
220                $idList[] = $item->getId();
221            } elseif (is_array($item) && array_key_exists('id', $item)) {
222                $idList[] = $item['id'];
223            } else {
224                throw new \UnexpectedValueException('Item is neither array nor object with getId() method');
225            }
226        }
227
228        return implode(',', array_unique($idList));
229    }
230
231    /**
232     * Set entity from response
233     *
234     * @param array $data
235     *
236     * @return self
237     */
238    public function setData(array $data)
239    {
240        if (array_key_exists('$schema', $data)) {
241            $data = [$data];
242        }
243        foreach ($data as $entityData) {
244            if (!array_key_exists('$schema', $entityData)) {
245                $entityData['$schema'] = $data[0]['$schema'];
246            }
247            $this->data[] = Factory::create($entityData)->getEntity();
248        }
249        return $this;
250    }
251}