Completed
Branch v2 (cda8c7)
by Pieter
03:41
created

PhpPrimitive::convert()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 20
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 16
c 1
b 0
f 1
nc 7
nop 1
dl 0
loc 20
rs 9.4222
1
<?php
2
namespace W2w\Lib\Apie\ValueObjects;
3
4
use erasys\OpenApi\Spec\v3\Schema;
5
use W2w\Lib\Apie\Exceptions\InvalidReturnTypeOfApiResourceException;
6
7
class PhpPrimitive implements ValueObjectInterface
8
{
9
    const STRING = 'STRING';
10
11
    const BOOL = 'BOOL';
12
13
    const INT = 'INT';
14
15
    const FLOAT = 'FLOAT';
16
17
    use StringEnumTrait;
18
19
    /**
20
     * Returns Schema used in OpenApi Spec.
21
     *
22
     * @return Schema
23
     */
24
    public function getSchemaForFilter(): Schema
25
    {
26
        switch ($this->toNative()) {
27
            case self::BOOL:
28
                return new Schema(['type' => 'boolean']);
29
            case self::INT:
30
                return new Schema(['type' => 'number', 'format' => 'int32']);
31
            case self::FLOAT:
32
                return new Schema(['type' => 'number', 'format' => 'double']);
33
        }
34
35
        return new Schema(['type' => 'string', 'minimum' => 1]);
36
    }
37
38
    /**
39
     * Converts value to the primitive.
40
     *
41
     * @param string $value
42
     * @return int|float|string|bool
43
     */
44
    public function convert(string $value)
45
    {
46
        switch ($this->toNative()) {
47
            case self::BOOL:
48
                $filter = FILTER_VALIDATE_BOOLEAN;
49
                break;
50
            case self::INT:
51
                $filter = FILTER_VALIDATE_INT;
52
                break;
53
            case self::FLOAT:
54
                $filter = FILTER_VALIDATE_FLOAT;
55
                break;
56
            default:
57
                return $value;
58
        }
59
        $res = filter_var($value, $filter, FILTER_NULL_ON_FAILURE);
60
        if (is_null($res)) {
61
            throw new InvalidReturnTypeOfApiResourceException(null, $value, strtolower($this->toNative()));
62
        }
63
        return $res;
64
65
    }
66
67
}
68