Issues (12)

src/Swagger/SwaggerRequestBody.php (1 issue)

1
<?php
2
3
namespace ByJG\ApiTools\Swagger;
4
5
use ByJG\ApiTools\Base\Body;
6
use ByJG\ApiTools\Exception\InvalidDefinitionException;
7
use ByJG\ApiTools\Exception\NotMatchedException;
8
use ByJG\ApiTools\Exception\RequiredArgumentNotFound;
9
10
class SwaggerRequestBody extends Body
11
{
12
    /**
13
     * @inheritDoc
14
     */
15
    public function match(mixed $body): bool
16
    {
17
        $hasFormData = false;
18
        foreach ($this->structure as $parameter) {
19
            if ($parameter['in'] === "body") {
20
                if (isset($parameter['required']) && $parameter['required'] === true && empty($body)) {
21
                    throw new RequiredArgumentNotFound('The body is required but it is empty');
22
                }
23
                return $this->matchSchema($this->name, $parameter['schema'], $body) ?? false;
24
            }
25
            if ($parameter['in'] === "formData") {
26
                $hasFormData = true;
27
                if (isset($parameter['required']) && $parameter['required'] === true && !isset($body[$parameter['name']])) {
28
                    throw new RequiredArgumentNotFound("The formData parameter '{$parameter['name']}' is required but it isn't found. ");
29
                }
30
                if (!$this->matchTypes($parameter['name'], $parameter, ($body[$parameter['name']] ?? null))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->matchTypes($param...meter['name']] ?? null) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
31
                    throw new NotMatchedException("The formData parameter '{$parameter['name']}' not match with the specification");
32
                }
33
            }
34
        }
35
36
        if (!empty($body) && !$hasFormData) {
37
            throw new InvalidDefinitionException('Body is passed but there is no request body definition');
38
        }
39
40
        return false;
41
    }
42
}
43