Normalizer::extractAttributes()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 11
nc 5
nop 2
1
<?php
2
3
namespace As3\Modlr\Api\JsonApiOrg;
4
5
use As3\Modlr\Api\AbstractNormalizer;
6
use As3\Modlr\Api\NormalizerException;
7
use As3\Modlr\Metadata\EntityMetadata;
8
use As3\Modlr\Rest\RestPayload;
9
10
/**
11
 * Normalizes REST payloads into standard arrays based on the JSON API spec.
12
 *
13
 * @author Jacob Bare <[email protected]>
14
 */
15
final class Normalizer extends AbstractNormalizer
16
{
17
    /**
18
     * {@inheritDoc}
19
     */
20 View Code Duplication
    protected function extractId(array $rawPayload)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
21
    {
22
        if (isset($rawPayload['data']['id']) && !empty($rawPayload['data']['id'])) {
23
            return $rawPayload['data']['id'];
24
        }
25
        return null;
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     */
31 View Code Duplication
    protected function extractType(array $rawPayload)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
32
    {
33
        if (isset($rawPayload['data']['type']) && !empty($rawPayload['data']['type'])) {
34
            return $rawPayload['data']['type'];
35
        }
36
        throw NormalizerException::badRequest('The "type" member was missing from the payload. All payloads must contain a type.');
37
    }
38
39
    /**
40
     * {@inheritDoc}
41
     */
42
    protected function extractProperties(array $rawPayload, EntityMetadata $metadata)
43
    {
44
        $data = $rawPayload['data'];
45
        $attributes = $this->extractAttributes($data, $metadata);
46
        $relationships = $this->extractRelationships($data, $metadata);
47
        return array_merge($attributes, $relationships);
48
    }
49
50
    /**
51
     * Extracts the model's attributes, per JSON API spec.
52
     *
53
     * @param   array           $data
54
     * @param   EntityMetadata  $metadata
55
     * @return  array
56
     */
57
    protected function extractAttributes(array $data, EntityMetadata $metadata)
58
    {
59
        $flattened = [];
60
        if (!isset($data['attributes']) || !is_array($data['attributes'])) {
61
            return $data['attributes'] = [];
62
        }
63
64
        $keyMap = array_flip(array_keys($data['attributes']));
65
        foreach ($metadata->getProperties() as $key => $propMeta) {
66
            if (!isset($keyMap[$key])) {
67
                continue;
68
            }
69
            if (true === $metadata->hasAttribute($key) || true === $metadata->hasEmbed($key)) {
70
                $flattened[$key] = $data['attributes'][$key];
71
            }
72
        }
73
        return $flattened;
74
    }
75
76
    /**
77
     * Extracts the model's relationships, per JSON API spec.
78
     *
79
     * @param   array           $data
80
     * @param   EntityMetadata  $metadata
81
     * @return  array
82
     */
83
    protected function extractRelationships(array $data, EntityMetadata $metadata)
84
    {
85
        $flattened = [];
86
        if (!isset($data['relationships']) || !is_array($data['relationships'])) {
87
            return $flattened;
88
        }
89
90
        foreach ($metadata->getRelationships() as $key => $relMeta) {
91
            if (!isset($data['relationships'][$key])) {
92
                continue;
93
            }
94
            $rel = $data['relationships'][$key];
95
            // Need to use array_key_exists over isset because 'null' is valid. Creating a key map for each relationship is too costly since every relationship needs the data check.
96
            if (false === array_key_exists('data', $rel)) {
97
                throw NormalizerException::badRequest(sprintf('The "data" member was missing from the payload for relationship "%s"', $key));
98
            }
99
100
            if (empty($rel['data'])) {
101
                $flattened[$key] = $relMeta->isOne() ? null : [];
102
                continue;
103
            }
104
105
            if (!is_array($rel['data'])) {
106
                throw NormalizerException::badRequest(sprintf('The "data" member is not valid in the payload for relationship "%s"', $key));
107
            }
108
109 View Code Duplication
            if (true === $relMeta->isOne() && true === $this->isSequentialArray($rel['data'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
                throw NormalizerException::badRequest(sprintf('The data payload for relationship "%s" is malformed. Data types of "one" must be an associative array, sequential found.', $key));
111
            }
112 View Code Duplication
            if (true === $relMeta->isMany() && false === $this->isSequentialArray($rel['data'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
                throw NormalizerException::badRequest(sprintf('The data payload for relationship "%s" is malformed. Data types of "many" must be a sequential array, associative found.', $key));
114
            }
115
            $flattened[$key] = $rel['data'];
116
        }
117
        return $flattened;
118
    }
119
120
    /**
121
     * {@inheritDoc}
122
     */
123
    protected function getRawPayload(RestPayload $payload)
124
    {
125
        $rawPayload = @json_decode($payload->getData(), true);
126
        if (!is_array($rawPayload)) {
127
            throw NormalizerException::badRequest('Unable to parse. Is the JSON valid?');
128
        }
129
        return $rawPayload;
130
    }
131
132
    /**
133
     * {@inheritDoc}
134
     */
135
    protected function validateRawPayload(array $rawPayload)
136
    {
137
        if (!isset($rawPayload['data']) || !is_array($rawPayload['data'])) {
138
            throw NormalizerException::badRequest('No "data" member was found in the payload. All payloads must be keyed with "data."');
139
        }
140
141
        if (empty($rawPayload['data'])) {
142
            return $rawPayload;
143
        }
144
        if (true === $this->isSequentialArray($rawPayload['data'])) {
145
            throw NormalizerException::badRequest('Normalizing multiple records is currently not supported.');
146
        }
147
        return $rawPayload;
148
    }
149
150
    /**
151
     * Determines if an array is sequential.
152
     *
153
     * @param   array   $arr
154
     * @return  bool
155
     */
156
    protected function isSequentialArray(array $arr)
157
    {
158
        if (empty($arr)) {
159
            return true;
160
        }
161
        return (range(0, count($arr) - 1) === array_keys($arr));
162
    }
163
}
164