Passed
Branch v2 (d444af)
by Pieter
02:38
created

PhpPrimitive   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 30
c 1
b 0
f 1
dl 0
loc 57
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A convert() 0 20 5
A getSchemaForFilter() 0 12 4
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