forked from utopia-php/database
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelect.php
More file actions
104 lines (89 loc) · 2.59 KB
/
Select.php
File metadata and controls
104 lines (89 loc) · 2.59 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
namespace Utopia\Database\Validator\Query;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
class Select extends Base
{
/**
* @var array<int|string, mixed>
*/
protected array $schema = [];
/**
* List of internal attributes
*
* @var array<string>
*/
protected const INTERNAL_ATTRIBUTES = [
'$id',
'$sequence',
'$createdAt',
'$updatedAt',
'$permissions',
'$collection',
];
/**
* @param array<Document> $attributes
*/
public function __construct(array $attributes = [])
{
foreach ($attributes as $attribute) {
$this->schema[$attribute->getAttribute('key', $attribute->getAttribute('$id'))] = $attribute->getArrayCopy();
}
}
/**
* Is valid.
*
* Returns true if method is TYPE_SELECT selections are valid
*
* Otherwise, returns false
*
* @param Query $value
* @return bool
*/
public function isValid($value): bool
{
if (!$value instanceof Query) {
return false;
}
if ($value->getMethod() !== Query::TYPE_SELECT) {
return false;
}
$internalKeys = \array_map(
fn ($attr) => $attr['$id'],
Database::INTERNAL_ATTRIBUTES
);
if (\count($value->getValues()) === 0) {
$this->message = 'No attributes selected';
return false;
}
if (\count($value->getValues()) !== \count(\array_unique($value->getValues()))) {
$this->message = 'Duplicate attributes selected';
return false;
}
foreach ($value->getValues() as $attribute) {
if (\str_contains($attribute, '.')) {
//special symbols with `dots`
if (isset($this->schema[$attribute])) {
continue;
}
// For relationships, just validate the top level.
// Will validate each nested level during the recursive calls.
$attribute = \explode('.', $attribute)[0];
}
// Skip internal attributes
if (\in_array($attribute, $internalKeys)) {
continue;
}
if (!isset($this->schema[$attribute]) && $attribute !== '*') {
$this->message = 'Attribute not found in schema: ' . $attribute;
return false;
}
}
return true;
}
public function getMethodType(): string
{
return self::METHOD_TYPE_SELECT;
}
}