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

Reference   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 22
c 2
b 1
f 1
dl 0
loc 53
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A toNative() 0 4 1
A fromNative() 0 14 4
A __construct() 0 9 2
A supportsFromNative() 0 9 4
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