Completed
Push — master ( fcd315...e54b6a )
by John
02:20
created

OpenApiParameter::__construct()   B

Complexity

Conditions 8
Paths 96

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 7.7777
c 0
b 0
f 0
cc 8
eloc 14
nc 96
nop 1
1
<?php declare(strict_types = 1);
2
/*
3
 * This file is part of the KleijnWeb\ApiDescriptions package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace KleijnWeb\ApiDescriptions\Description\OpenApi;
9
10
use KleijnWeb\ApiDescriptions\Description\Parameter;
11
use KleijnWeb\ApiDescriptions\Description\Schema;
12
13
/**
14
 * @author John Kleijn <[email protected]>
15
 */
16
class OpenApiParameter extends Parameter
17
{
18
    /**
19
     * OpenApiParameter constructor.
20
     *
21
     * @param \stdClass $definition
22
     */
23
    public function __construct(\stdClass $definition)
24
    {
25
        $this->name             = $definition->name;
26
        $this->in               = $definition->in;
27
        $this->collectionFormat = isset($definition->collectionFormat) ? $definition->collectionFormat : null;
28
        $this->required         = isset($definition->required) && $definition->required;
29
        $this->enum             = isset($definition->enum) ? $definition->enum : null;
30
        $this->pattern          = isset($definition->pattern) ? $definition->pattern : null;
31
32
        if ($this->isIn(self::IN_BODY)) {
33
            $definition->schema       = isset($definition->schema) ? $definition->schema : (object)[];
34
            $definition->schema->type = 'object';
35
        }
36
        if (isset($definition->schema)) {
37
            $this->schema = Schema::get($definition->schema);
38
        } else {
39
            $this->schema = $this->createSchema($definition);
40
        }
41
    }
42
43
    /**
44
     * @param \stdClass $definition
45
     *
46
     * @return Schema
47
     */
48
    protected function createSchema(\stdClass $definition): Schema
49
    {
50
        // Remove non-JSON-Schema properties
51
        $schemaDefinition     = clone $definition;
52
        $swaggerPropertyNames = [
53
            'name',
54
            'in',
55
            'description',
56
            'required',
57
            'allowEmptyValue',
58
            'collectionFormat'
59
        ];
60
        foreach ($swaggerPropertyNames as $propertyName) {
61
            if (property_exists($schemaDefinition, $propertyName)) {
62
                unset($schemaDefinition->$propertyName);
63
            }
64
        }
65
66
        return Schema::get($schemaDefinition);
67
    }
68
}
69