Completed
Push — master ( a654a8...533fff )
by Jasper
11:19
created

DocumentParser::getDuplicateItems()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Swis\JsonApi\Client\Parsers;
4
5
use Swis\JsonApi\Client\Collection;
6
use Swis\JsonApi\Client\CollectionDocument;
7
use Swis\JsonApi\Client\Document;
8
use Swis\JsonApi\Client\Exceptions\ValidationException;
9
use Swis\JsonApi\Client\Interfaces\DocumentInterface;
10
use Swis\JsonApi\Client\Interfaces\DocumentParserInterface;
11
use Swis\JsonApi\Client\Interfaces\ItemInterface;
12
use Swis\JsonApi\Client\Interfaces\ManyRelationInterface;
13
use Swis\JsonApi\Client\Interfaces\OneRelationInterface;
14
use Swis\JsonApi\Client\Interfaces\TypeMapperInterface;
15
use Swis\JsonApi\Client\ItemDocument;
16
use Swis\JsonApi\Client\TypeMapper;
17
18
class DocumentParser implements DocumentParserInterface
19
{
20
    /**
21
     * @var \Swis\JsonApi\Client\Parsers\ItemParser
22
     */
23
    private $itemParser;
24
25
    /**
26
     * @var \Swis\JsonApi\Client\Parsers\CollectionParser
27
     */
28
    private $collectionParser;
29
30
    /**
31
     * @var \Swis\JsonApi\Client\Parsers\ErrorCollectionParser
32
     */
33
    private $errorCollectionParser;
34
35
    /**
36
     * @var \Swis\JsonApi\Client\Parsers\LinksParser
37
     */
38
    private $linksParser;
39
40
    /**
41
     * @var \Swis\JsonApi\Client\Parsers\JsonapiParser
42
     */
43
    private $jsonapiParser;
44
45
    /**
46
     * @var \Swis\JsonApi\Client\Parsers\MetaParser
47
     */
48
    private $metaParser;
49
50
    /**
51
     * @param \Swis\JsonApi\Client\Parsers\ItemParser            $itemParser
52
     * @param \Swis\JsonApi\Client\Parsers\CollectionParser      $collectionParser
53
     * @param \Swis\JsonApi\Client\Parsers\ErrorCollectionParser $errorCollectionParser
54
     * @param \Swis\JsonApi\Client\Parsers\LinksParser           $linksParser
55
     * @param \Swis\JsonApi\Client\Parsers\JsonapiParser         $jsonapiParser
56
     * @param \Swis\JsonApi\Client\Parsers\MetaParser            $metaParser
57
     */
58 111
    public function __construct(
59
        ItemParser $itemParser,
60
        CollectionParser $collectionParser,
61
        ErrorCollectionParser $errorCollectionParser,
62
        LinksParser $linksParser,
63
        JsonapiParser $jsonapiParser,
64
        MetaParser $metaParser
65
    ) {
66 111
        $this->itemParser = $itemParser;
67 111
        $this->collectionParser = $collectionParser;
68 111
        $this->errorCollectionParser = $errorCollectionParser;
69 111
        $this->linksParser = $linksParser;
70 111
        $this->jsonapiParser = $jsonapiParser;
71 111
        $this->metaParser = $metaParser;
72 111
    }
73
74
    /**
75
     * @param \Swis\JsonApi\Client\Interfaces\TypeMapperInterface|null $typeMapper
76
     *
77
     * @return static
78
     */
79 111
    public static function create(TypeMapperInterface $typeMapper = null): self
80
    {
81 111
        $metaParser = new MetaParser();
82 111
        $linksParser = new LinksParser($metaParser);
83 111
        $itemParser = new ItemParser($typeMapper ?? new TypeMapper(), $linksParser, $metaParser);
84
85 111
        return new static(
86 111
            $itemParser,
87 111
            new CollectionParser($itemParser),
88 111
            new ErrorCollectionParser(
89 111
                new ErrorParser($linksParser, $metaParser)
90
            ),
91 37
            $linksParser,
92 111
            new JsonapiParser($metaParser),
93 37
            $metaParser
94
        );
95
    }
96
97
    /**
98
     * @param string $json
99
     *
100
     * @return \Swis\JsonApi\Client\Interfaces\DocumentInterface
101
     */
102 102
    public function parse(string $json): DocumentInterface
103
    {
104 102
        $data = $this->decodeJson($json);
105
106 99
        if (!is_object($data)) {
107 18
            throw new ValidationException(sprintf('Document MUST be an object, "%s" given.', gettype($data)));
108
        }
109 81
        if (!property_exists($data, 'data') && !property_exists($data, 'errors') && !property_exists($data, 'meta')) {
110 3
            throw new ValidationException('Document MUST contain at least one of the following properties: `data`, `errors`, `meta`.');
111
        }
112 78
        if (property_exists($data, 'data') && property_exists($data, 'errors')) {
113 3
            throw new ValidationException('The properties `data` and `errors` MUST NOT coexist in Document.');
114
        }
115 75
        if (!property_exists($data, 'data') && property_exists($data, 'included')) {
116 3
            throw new ValidationException('If Document does not contain a `data` property, the `included` property MUST NOT be present either.');
117
        }
118 72
        if (property_exists($data, 'data') && !is_object($data->data) && !is_array($data->data) && $data->data !== null) {
119 12
            throw new ValidationException(sprintf('Document property "data" MUST be null, an array or an object, "%s" given.', gettype($data->data)));
120
        }
121 60
        if (property_exists($data, 'included') && !is_array($data->included)) {
122 18
            throw new ValidationException(sprintf('Document property "included" MUST be an array, "%s" given.', gettype($data->included)));
123
        }
124
125 42
        $document = $this->getDocument($data);
126
127 39
        if (property_exists($data, 'links')) {
128 3
            $document->setLinks($this->linksParser->parse($data->links, LinksParser::SOURCE_DOCUMENT));
129
        }
130
131 39
        if (property_exists($data, 'errors')) {
132 3
            $document->setErrors($this->errorCollectionParser->parse($data->errors));
133
        }
134
135 39
        if (property_exists($data, 'meta')) {
136 6
            $document->setMeta($this->metaParser->parse($data->meta));
137
        }
138
139 39
        if (property_exists($data, 'jsonapi')) {
140 3
            $document->setJsonapi($this->jsonapiParser->parse($data->jsonapi));
141
        }
142
143 39
        return $document;
144
    }
145
146
    /**
147
     * @param string $json
148
     *
149
     * @return mixed
150
     */
151 102
    private function decodeJson(string $json)
152
    {
153 102
        $data = json_decode($json, false);
154
155 102
        if (json_last_error() !== JSON_ERROR_NONE) {
156 3
            throw new ValidationException(sprintf('Unable to parse JSON data: %s', json_last_error_msg()), json_last_error());
157
        }
158
159 99
        return $data;
160
    }
161
162
    /**
163
     * @param mixed $data
164
     *
165
     * @return \Swis\JsonApi\Client\Interfaces\DocumentInterface
166
     */
167 42
    private function getDocument($data): DocumentInterface
168
    {
169 42
        if (!property_exists($data, 'data') || $data->data === null) {
170 6
            return new Document();
171
        }
172
173 36
        if (is_array($data->data)) {
174 21
            $document = (new CollectionDocument())
175 21
                ->setData($this->collectionParser->parse($data->data));
176
        } else {
177 15
            $document = (new ItemDocument())
178 15
                ->setData($this->itemParser->parse($data->data));
179
        }
180
181 36
        if (property_exists($data, 'included')) {
182 18
            $document->setIncluded($this->collectionParser->parse($data->included));
183
        }
184
185 36
        $allItems = Collection::wrap($document->getData())
186 36
            ->concat($document->getIncluded());
187
188 36
        $duplicateItems = $this->getDuplicateItems($allItems);
189
190 36
        if ($duplicateItems->isNotEmpty()) {
191 3
            throw new ValidationException(sprintf('Resources MUST be unique based on their `type` and `id`, %d duplicate(s) found.', $duplicateItems->count()));
192
        }
193
194 33
        $this->linkRelationships($allItems);
195
196 33
        return $document;
197
    }
198
199
    /**
200
     * @param \Swis\JsonApi\Client\Collection $items
201
     */
202 33
    private function linkRelationships(Collection $items): void
203
    {
204 33
        $keyedItems = $items->keyBy(
205
            function (ItemInterface $item) {
206 21
                return $this->getItemKey($item);
207 33
            }
208
        );
209
210 33
        $items->each(
211
            function (ItemInterface $item) use ($keyedItems) {
212 21
                foreach ($item->getRelations() as $name => $relation) {
213 12
                    if ($relation instanceof OneRelationInterface) {
214
                        /** @var \Swis\JsonApi\Client\Interfaces\ItemInterface|null $relatedItem */
215 6
                        $relatedItem = $relation->getIncluded();
216
217 6
                        if ($relatedItem === null) {
218 3
                            continue;
219
                        }
220
221 3
                        $includedItem = $this->getItem($keyedItems, $relatedItem);
222 3
                        if ($includedItem !== null) {
223 3
                            $relation->associate($includedItem);
224
                        }
225 6
                    } elseif ($relation instanceof ManyRelationInterface) {
226
                        /** @var \Swis\JsonApi\Client\Collection $relatedCollection */
227 6
                        $relatedCollection = $relation->getIncluded();
228
229
                        /** @var \Swis\JsonApi\Client\Interfaces\ItemInterface $relatedItem */
230 6
                        foreach ($relatedCollection as $key => $relatedItem) {
231 3
                            $includedItem = $this->getItem($keyedItems, $relatedItem);
232 3
                            if ($includedItem !== null) {
233 3
                                $relatedCollection->put($key, $includedItem);
234
                            }
235
                        }
236
                    }
237
                }
238 33
            }
239
        );
240 33
    }
241
242
    /**
243
     * @param \Swis\JsonApi\Client\Collection               $included
244
     * @param \Swis\JsonApi\Client\Interfaces\ItemInterface $item
245
     *
246
     * @return \Swis\JsonApi\Client\Interfaces\ItemInterface|null
247
     */
248 6
    private function getItem(Collection $included, ItemInterface $item): ?ItemInterface
249
    {
250 6
        return $included->get($this->getItemKey($item));
251
    }
252
253
    /**
254
     * @param \Swis\JsonApi\Client\Interfaces\ItemInterface $item
255
     *
256
     * @return string
257
     */
258 24
    private function getItemKey(ItemInterface $item): string
259
    {
260 24
        return sprintf('%s:%s', $item->getType(), $item->getId());
261
    }
262
263
    /**
264
     * @param \Swis\JsonApi\Client\Collection $items
265
     *
266
     * @return \Swis\JsonApi\Client\Collection
267
     */
268 36
    private function getDuplicateItems(Collection $items): Collection
269
    {
270
        $valueRetriever = function (ItemInterface $item) {
271 24
            return $this->getItemKey($item);
272 36
        };
273
274 36
        return $items->duplicates($valueRetriever);
275
    }
276
}
277