Repository navigation
Expand file tree
/
Copy pathRepository.php
More file actions
116 lines (96 loc) · 2.88 KB
/
Copy pathRepository.php
File metadata and controls
116 lines (96 loc) · 2.88 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
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace Utopia\Database\Repository;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
abstract class Repository
{
/** @var array<Scope> */
private array $globalScopes = [];
public function __construct(
protected Database $db,
) {
}
abstract public function collection(): string;
public function addScope(Scope $scope): void
{
$this->globalScopes[] = $scope;
}
public function clearScopes(): void
{
$this->globalScopes = [];
}
/**
* @param array<Query> $queries
* @return array<Query>
*/
protected function applyScopes(array $queries): array
{
foreach ($this->globalScopes as $scope) {
$queries = \array_merge($queries, $scope->apply());
}
return $queries;
}
/**
* @param array<Query> $queries
* @return array<Document>
*/
public function withoutScopes(array $queries = []): array
{
return $this->db->find($this->collection(), $queries);
}
public function findById(string $id): Document
{
return $this->db->getDocument($this->collection(), $id);
}
/**
* @param array<Query> $queries
* @return array<Document>
*/
public function findAll(array $queries = []): array
{
return $this->db->find($this->collection(), $this->applyScopes($queries));
}
public function findOneBy(string $attribute, mixed $value): Document
{
$values = \is_array($value) ? $value : [$value];
$equal = [];
foreach ($values as $item) {
if (\is_array($item) || \is_bool($item) || \is_float($item) || \is_int($item) || \is_string($item) || $item === null) {
$equal[] = $item;
}
}
$results = $this->db->find($this->collection(), $this->applyScopes([
Query::equal($attribute, $equal),
Query::limit(1),
]));
return $results[0] ?? new Document();
}
/**
* @param array<Query> $queries
*/
public function count(array $queries = []): int
{
return $this->db->count($this->collection(), $this->applyScopes($queries));
}
public function create(Document $document): Document
{
return $this->db->createDocument($this->collection(), $document);
}
public function update(string $id, Document $document): Document
{
return $this->db->updateDocument($this->collection(), $id, $document);
}
public function delete(string $id): bool
{
return $this->db->deleteDocument($this->collection(), $id);
}
/**
* @param array<Query> $baseQueries
* @return array<Document>
*/
public function matching(Specification $spec, array $baseQueries = []): array
{
return $this->findAll(\array_merge($baseQueries, $spec->toQueries()));
}
}