forked from tobyzerner/json-api-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayField.php
86 lines (67 loc) · 2.09 KB
/
ArrayField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Tobyz\JsonApiServer\Schema\Field;
use Tobyz\JsonApiServer\Context;
class ArrayField extends Field
{
private int $minItems = 0;
private ?int $maxItems = null;
private bool $uniqueItems = false;
private ?Attribute $items = null;
public function __construct(string $name)
{
parent::__construct($name);
$this->validate(function (mixed $value, callable $fail, Context $context): void {
if ($value === null) {
return;
}
if (!is_array($value)) {
$fail('must be an array');
return;
}
if (count($value) < $this->minItems) {
$fail(sprintf('must contain at least %d values', $this->minItems));
}
if ($this->maxItems !== null && count($value) > $this->maxItems) {
$fail(sprintf('must contain no more than %d values', $this->maxItems));
}
if ($this->uniqueItems && $value !== array_unique($value)) {
$fail('must contain unique values');
}
if ($this->items) {
foreach ($value as $item) {
$this->items->validateValue($item, $fail, $context);
}
}
});
}
public function minItems(int $minItems): static
{
$this->minItems = $minItems;
return $this;
}
public function maxItems(?int $maxItems): static
{
$this->maxItems = $maxItems;
return $this;
}
public function uniqueItems(bool $uniqueItems = true): static
{
$this->uniqueItems = $uniqueItems;
return $this;
}
public function items(Attribute $schema): static
{
$this->items = $schema;
return $this;
}
public function getSchema(): array
{
return parent::getSchema() + [
'type' => 'array',
'minItems' => $this->minItems,
'maxItems' => $this->maxItems,
'uniqueItems' => $this->uniqueItems,
'items' => $this->items?->getSchema(),
];
}
}