Completed
Push — master ( 5211a1...8ac2fa )
by Jasper
05:11
created

DocumentParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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