Adapter::buildUrl()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 4
1
<?php
2
3
namespace As3\Modlr\Api\JsonApiOrg;
4
5
use As3\Modlr\Api\AbstractAdapter;
6
use As3\Modlr\Api\AdapterException;
7
use As3\Modlr\Metadata\EntityMetadata;
8
use As3\Modlr\Rest;
9
10
/**
11
 * Adapter for handling API operations using the JSON API specification.
12
 *
13
 * @author Jacob Bare <[email protected]>
14
 */
15
final class Adapter extends AbstractAdapter
16
{
17
    /**
18
     * {@inheritDoc}
19
     */
20
    public function buildUrl(EntityMetadata $metadata, $identifier, $relFieldKey = null, $isRelatedLink = false)
21
    {
22
        $url = sprintf('%s://%s%s/%s/%s',
23
            $this->config->getScheme(),
24
            $this->config->getHost(),
25
            $this->config->getRootEndpoint(),
26
            $metadata->type,
27
            $identifier
28
        );
29
30
        if (null !== $relFieldKey) {
31
            if (false === $isRelatedLink) {
32
                $url .= '/relationships';
33
            }
34
            $url .= sprintf('/%s', $relFieldKey);
35
        }
36
        return $url;
37
    }
38
39
    /**
40
     * {@inheritDoc}
41
     */
42
    public function processRequest(Rest\RestRequest $request)
43
    {
44
        $this->request = $request;
45
        switch ($request->getMethod()) {
46
            case 'GET':
47
                return $this->handleGetRequest($request);
48 View Code Duplication
            case 'POST':
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...
49
                // @todo Must validate JSON content type
50
                if (false === $request->hasIdentifier()) {
51
                    if (true === $request->hasPayload()) {
52
                        return $this->createRecord($request->getEntityType(), $request->getPayload(), $request->getFieldset(), $request->getInclusions());
0 ignored issues
show
Bug introduced by
It seems like $request->getPayload() can be null; however, createRecord() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Unused Code introduced by
The call to Adapter::createRecord() has too many arguments starting with $request->getFieldset().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
53
                    }
54
                    throw AdapterException::requestPayloadNotFound('Unable to create new entity.');
55
                }
56
                throw AdapterException::badRequest('Creating a new record while providing an id is not supported.');
57 View Code Duplication
            case 'PATCH':
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...
58
                // @todo Must validate JSON content type
59
                if (false === $request->hasIdentifier()) {
60
                    throw AdapterException::badRequest('No identifier found. You must specify an ID in the URL.');
61
                }
62
                if (false === $request->hasPayload()) {
63
                    throw AdapterException::requestPayloadNotFound('Unable to update entity.');
64
                }
65
                return $this->updateRecord($request->getEntityType(), $request->getIdentifier(), $request->getPayload(), $request->getFieldset(), $request->getInclusions());
0 ignored issues
show
Bug introduced by
It seems like $request->getPayload() can be null; however, updateRecord() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Unused Code introduced by
The call to Adapter::updateRecord() has too many arguments starting with $request->getFieldset().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
            case 'DELETE':
67
                if (false === $request->hasIdentifier()) {
68
                    throw AdapterException::badRequest('No identifier found. You must specify an ID in the URL.');
69
                }
70
                return $this->deleteRecord($request->getEntityType(), $request->getIdentifier());
71
                throw AdapterException::badRequest('No DELETE request handler found.');
0 ignored issues
show
Unused Code introduced by
throw \As3\Modlr\Api\Ada...quest handler found.'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
72
            default:
73
                throw AdapterException::badRequest(sprintf('The request method "%s" is not supported.', $request->getMethod()));
74
        }
75
    }
76
77
    /**
78
     * {@inheritDoc}
79
     */
80
    protected function createRestResponse($status, Rest\RestPayload $payload = null)
81
    {
82
        $restResponse = new Rest\RestResponse($status, $payload);
83
        $restResponse->addHeader('content-type', 'application/json');
84
        return $restResponse;
85
    }
86
87
    /**
88
     * Validates that the payload type key matches the endpoint type key.
89
     * Also handles proper type keys for polymorphic endpoints.
90
     *
91
     * @param   string  $payloadTypeKey
92
     * @param   string  $endpointTypeKey
93
     * @throws  AdpaterException
94
     */
95
    protected function validatePayloadType($payloadTypeKey, $endpointTypeKey)
96
    {
97
        $metadata = $this->getStore()->getMetadataForType($endpointTypeKey);
98
99
        if (false === $metadata->isPolymorphic() && $payloadTypeKey === $endpointTypeKey) {
100
            return;
101
        }
102
103
        if (true === $metadata->isPolymorphic() && in_array($payloadTypeKey, $metadata->ownedTypes)) {
104
            return;
105
        }
106
        $expected = (true === $metadata->isPolymorphic()) ? implode(', ', $metadata->ownedTypes) : $endpointTypeKey;
107
        throw AdapterException::badRequest(sprintf('The payload "type" member does not match the API endpoint. Expected one of "%s" but received "%s"', $expected, $payloadTypeKey));
108
    }
109
110
    /**
111
     * {@inheritDoc}
112
     */
113
    protected function validateCreatePayload($typeKey, array $normalized)
114
    {
115
        if (isset($normalized['id'])) {
116
            throw AdapterException::badRequest('An "id" member was found in the payload. Client-side ID generation is currently not supported.');
117
        }
118
119
        if (!isset($normalized['type'])) {
120
            throw AdapterException::badRequest('An "type" member was found in the payload. All creation payloads must contain the model type.');
121
        }
122
123
        $this->validatePayloadType($normalized['type'], $typeKey);
124
        return $normalized;
125
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130
    protected function validateUpdatePayload($typeKey, $identifier, array $normalized)
131
    {
132
        // @todo Does the type still need to be validated here? Yes, most likely - need to compare the endpoint versus the type.
133
        if (!isset($normalized['id'])) {
134
            throw AdapterException::badRequest('No "id" member was found in the payload.');
135
        }
136
        if ($identifier !== $normalized['id']) {
137
            throw AdapterException::badRequest('The request URI id does not match the payload id.');
138
        }
139
        if (!isset($normalized['type'])) {
140
            throw AdapterException::badRequest('An "type" member was found in the payload. All creation payloads must contain the model type.');
141
        }
142
        $this->validatePayloadType($normalized['type'], $typeKey);
143
144
        return $normalized;
145
    }
146
147
    /**
148
     * Handles a GET request.
149
     *
150
     * @param   Rest\RestRequest     $request
151
     * @return  Rest\RestResponse
152
     * @throws  AdapterException
153
     */
154
    private function handleGetRequest(Rest\RestRequest $request)
155
    {
156
        if (true === $request->hasIdentifier()) {
157
            if (false === $request->isRelationship() && false === $request->hasFilters()) {
158
                return $this->findRecord($request->getEntityType(), $request->getIdentifier());
159
            }
160
            if (true === $request->isRelationshipRetrieve()) {
161
                return $this->findRelationship($request->getEntityType(), $request->getIdentifier(), $request->getRelationshipFieldKey());
162
            }
163
            throw AdapterException::badRequest('No GET handler found.');
164
        } else {
165
            if (true === $request->isAutocomplete()) {
166
                // @todo Eventually add pagination (limit/skip)
167
                return $this->autocomplete($request->getEntityType(), $request->getAutocompleteKey(), $request->getAutocompleteValue());
168
            }
169
            if (true === $request->isQuery()) {
170
                return $this->findQuery($request->getEntityType(), $request->getQueryCriteria(), $request->getFieldset(), $request->getSorting(), $request->getPagination(), $request->getInclusions());
171
            }
172
            return $this->findAll($request->getEntityType(), [], $request->getFieldset(), $request->getSorting(), $request->getPagination(), $request->getInclusions());
173
        }
174
        throw AdapterException::badRequest('No GET handler found.');
0 ignored issues
show
Unused Code introduced by
throw \As3\Modlr\Api\Ada...o GET handler found.'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
175
    }
176
177
}
178