JsonApiDocumentParameterConverter::apply()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 10
cp 1
rs 9.6666
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Bundle\JsonApiBundle\Request;
5
6
use Mikemirten\Bundle\JsonApiBundle\Request\Exception\InvalidDocumentTypeException;
7
use Mikemirten\Bundle\JsonApiBundle\Request\Exception\InvalidMediaTypeException;
8
use Mikemirten\Component\JsonApi\Document\AbstractDocument;
9
use Mikemirten\Component\JsonApi\Document\NoDataDocument;
10
use Mikemirten\Component\JsonApi\Document\ResourceCollectionDocument;
11
use Mikemirten\Component\JsonApi\Document\SingleResourceDocument;
12
use Mikemirten\Component\JsonApi\Exception\InvalidDocumentException;
13
use Mikemirten\Component\JsonApi\Hydrator\DocumentHydrator;
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
15
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
19
/**
20
 * Parameter converter of request's body into a JsonAPI document
21
 *
22
 * @package Mikemirten\Bundle\JsonApiBundle\Request
23
 */
24
class JsonApiDocumentParameterConverter implements ParamConverterInterface
25
{
26
    /**
27
     * @var DocumentHydrator
28
     */
29
    protected $hydrator;
30
31
    /**
32
     * JsonApiDocumentParameterConverter constructor.
33
     *
34
     * @param DocumentHydrator $hydrator
35
     */
36 16
    public function __construct(DocumentHydrator $hydrator)
37
    {
38 16
        $this->hydrator = $hydrator;
39 16
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 12
    public function apply(Request $request, ParamConverter $configuration)
45
    {
46 12
        $content = $this->resolveRequestBody($request, $configuration);
47
48 10
        if ($content === null) {
49 1
            return false;
50
        }
51
52 9
        $document = $this->processDocument($content);
0 ignored issues
show
Bug introduced by
It seems like $content defined by $this->resolveRequestBod...equest, $configuration) on line 46 can also be of type resource; however, Mikemirten\Bundle\JsonAp...rter::processDocument() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
53 7
        $expected = $configuration->getClass();
54
55 7
        if ($expected === AbstractDocument::class || $document instanceof $expected) {
56 6
            $request->attributes->set($configuration->getName(), $document);
57 6
            return true;
58
        }
59
60 1
        throw new InvalidDocumentTypeException($document, $expected);
61
    }
62
63
    /**
64
     * Resolve request body
65
     *
66
     * @param  Request        $request
67
     * @param  ParamConverter $configuration
68
     * @throws BadRequestHttpException
69
     * @return string | null
70
     */
71 12
    protected function resolveRequestBody(Request $request, ParamConverter $configuration)
72
    {
73 12
        $isOptional = $configuration->isOptional();
74 12
        $isJsonApi  = $this->isContentTypeValid($request);
75
76 12
        if (! $isOptional && ! $isJsonApi) {
77 1
            throw new InvalidMediaTypeException($request);
78
        }
79
80 11
        $content = $request->getContent();
81
82 11
        if (! empty($content)) {
83 9
            return $content;
84
        }
85
86 2
        if (! $isOptional) {
87 1
            throw new BadRequestHttpException('Request body is empty');
88
        }
89 1
    }
90
91
    /**
92
     * Decode and hydrate document from raw content
93
     *
94
     * @param  string $content
95
     * @return AbstractDocument
96
     * @throws BadRequestHttpException
97
     */
98 9
    protected function processDocument(string $content): AbstractDocument
99
    {
100 9
        $decoded = $this->decodeContent($content);
101
102
        try {
103 8
            $document = $this->hydrator->hydrate($decoded);
104
        }
105 1
        catch (InvalidDocumentException $exception) {
106 1
            throw new BadRequestHttpException('Document hydration error: ' . $exception->getMessage(), $exception);
107
        }
108
109 7
        return $document;
110
    }
111
112
    /**
113
     * Is content type of request valid ?
114
     *
115
     * @param  Request $request
116
     * @return bool
117
     */
118 12
    protected function isContentTypeValid(Request $request): bool
119
    {
120 12
        $contentType = $request->headers->get('Content-Type', null, false);
121
122 12
        foreach ($contentType as $header)
0 ignored issues
show
Bug introduced by
The expression $contentType of type string|array<integer,string>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
123
        {
124 11
            if (strpos(ltrim($header), 'application/vnd.api+json') === 0) {
125 11
                return true;
126
            }
127
        }
128
129 1
        return false;
130
    }
131
132
    /**
133
     * Decode JSON
134
     *
135
     * @param  string $content
136
     * @return mixed
137
     * @throws BadRequestHttpException
138
     */
139 9
    protected function decodeContent(string $content): \stdClass
140
    {
141 9
        $decoded = json_decode($content);
142
143 9
        if (json_last_error() !== JSON_ERROR_NONE) {
144 1
            throw new BadRequestHttpException('Decoding error: ' . json_last_error_msg());
145
        }
146
147 8
        return $decoded;
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153 4
    public function supports(ParamConverter $configuration)
154
    {
155 4
        return in_array(
156 4
            $configuration->getClass(),
157
            [
158 4
                NoDataDocument::class,
159
                AbstractDocument::class,
160
                SingleResourceDocument::class,
161
                ResourceCollectionDocument::class
162
            ],
163 4
            true
164
        );
165
    }
166
}