Test Setup Failed
Push — main ( e03535...dde247 )
by Pieter
03:39
created

Reference::toNative()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
4
namespace Apie\OpenapiSchema\Spec;
5
6
use Apie\OpenapiSchema\Exceptions\InvalidReferenceValue;
7
use Apie\TypeJuggling\Exceptions\MissingValueException;
8
use Apie\TypeJuggling\StringLiteral;
9
use Apie\ValueObjects\Exceptions\InvalidValueForValueObjectException;
10
use Apie\ValueObjects\ValueObjectInterface;
11
12
class Reference implements ValueObjectInterface
13
{
14
    /**
15
     * @var string
16
     */
17
    private $ref;
18
19
    /**
20
     * @see https://swagger.io/specification/#components-object
21
     * @see https://swagger.io/specification/#reference-object
22
     */
23
    public function __construct(string $ref)
24
    {
25
        if (!preg_match(
26
            '@#/components/((x-[^/]+)|schemas|responses|parameters|examples|requestBodies|headers|securitySchemes|links|callbacks)/[a-zA-Z0-9\.\-_]+$@',
27
            $ref
28
        )) {
29
            throw new InvalidReferenceValue($ref);
30
        }
31
        $this->ref = $ref;
32
    }
33
34
    public static function fromNative($value)
35
    {
36
        if ($value instanceof ValueObjectInterface) {
37
            $value = $value->toNative();
38
        }
39
        if (!is_array($value)) {
40
            throw new InvalidValueForValueObjectException($value, __CLASS__);
41
        }
42
43
        $literal = new StringLiteral('$ref');
44
        if (!isset($value['$ref'])) {
45
            throw new MissingValueException('$ref');
46
        }
47
        return new Reference($literal->toNative($value['$ref']));
48
    }
49
50
    public static function supportsFromNative($value): bool
51
    {
52
        if ($value instanceof ValueObjectInterface) {
53
            $value = $value->toNative();
54
        }
55
        if (!is_array($value)) {
56
            return false;
57
        }
58
        return isset($value['$ref']) && (new StringLiteral('$ref'))->supportsFromNative($value['$ref']);
59
    }
60
61
    public function toNative()
62
    {
63
        return [
64
            '$ref' => $this->ref
65
        ];
66
    }
67
}
68