ArrayRefLookup::setArray()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2018 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Schema;
9
10
/**
11
 * A schema `$ref` lookup that searches arrays.
12
 *
13
 * @see https://swagger.io/docs/specification/using-ref/
14
 */
15
class ArrayRefLookup {
16
    /**
17
     * @var array|\ArrayAccess
18
     */
19
    private $array;
20
21
    /**
22
     * ArrayRefLookup constructor.
23
     *
24
     * @param array|\ArrayAccess $array The array that is searched.
25
     */
26 44
    public function __construct($array) {
27 44
        $this->array = $array;
28 44
    }
29
30
    /**
31
     * Lookup a schema based on a JSON ref.
32
     *
33
     * @param string $ref A valid JSON ref.
34
     * @return mixed|null Returns the value at the reference or **null** if the reference isn't found.
35
     * @see https://swagger.io/docs/specification/using-ref/
36
     */
37 42
    public function __invoke(string $ref) {
38 42
        $urlParts = parse_url($ref);
39 42
        if (!empty($urlParts['host']) || !empty($urlParts['path'])) {
40 2
            throw new \InvalidArgumentException("Only local schema references are supported. ($ref)", 400);
41
        }
42 40
        $fragment = $urlParts['fragment'] ?? '';
43 40
        if (strlen($fragment) === 0 || $fragment[0] !== '/') {
44 3
            throw new \InvalidArgumentException("Relative schema references are not supported. ($ref)", 400);
45
        }
46
47 37
        if ($fragment === '/') {
48 1
            return $this->array;
49
        }
50 36
        $parts = Schema::explodeRef(substr($fragment, 1));
51
52 36
        $value = $this->array;
53 36
        foreach ($parts as $key) {
54 36
            if (!is_string($value) && isset($value[$key])) {
55 34
                $value = $value[$key];
56
            } else {
57 36
                return null;
58
            }
59
        }
60 33
        return $value;
61
    }
62
63
    /**
64
     * Get the array.
65
     *
66
     * @return array|\ArrayAccess Returns the array.
67
     */
68 5
    public function getArray() {
69 5
        return $this->array;
70
    }
71
72
    /**
73
     * Set the array.
74
     *
75
     * @param array|\ArrayAccess $array
76
     * @return $this
77
     */
78 1
    public function setArray($array) {
79 1
        $this->array = $array;
80 1
        return $this;
81
    }
82
}
83