-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRepositoryFactory.php
More file actions
93 lines (80 loc) · 2.5 KB
/
Copy pathRepositoryFactory.php
File metadata and controls
93 lines (80 loc) · 2.5 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
<?php
namespace PivotPHP\CycleORM;
use Cycle\ORM\ORM;
use Cycle\ORM\ORMInterface;
use Cycle\ORM\RepositoryInterface;
/**
* Repository Factory com cache e validação.
*/
class RepositoryFactory
{
private ORMInterface $orm;
/**
* @var array<string, RepositoryInterface<object>> Cache de repositories
*/
private array $repositories = [];
/**
* @var array<string, class-string<RepositoryInterface<object>>> Custom repositories
*/
private array $customRepositories = [];
/**
* @param ORMInterface $orm ORM do Cycle
*/
public function __construct(ORMInterface $orm)
{
$this->orm = $orm;
}
/**
* Obtém o repository de uma entidade, com cache.
*
* @param class-string|object $entityClass
*
* @return RepositoryInterface<object>
*/
public function getRepository(object|string $entityClass): RepositoryInterface /* <object> */
{
$key = is_object($entityClass) ? get_class($entityClass) : $entityClass;
if (!isset($this->repositories[$key])) {
$this->repositories[$key] = $this->orm->getRepository($entityClass);
}
return $this->repositories[$key];
}
/**
* Registra um repository customizado para uma entidade.
*
* @param class-string $entityClass
* @param class-string<RepositoryInterface<object>> $repositoryClass
*/
public function registerCustomRepository(string $entityClass, string $repositoryClass): void
{
if (!class_exists($repositoryClass)) {
throw new \InvalidArgumentException("Repository class {$repositoryClass} does not exist");
}
if (!is_subclass_of($repositoryClass, RepositoryInterface::class)) {
throw new \InvalidArgumentException(
"Repository class {$repositoryClass} must implement RepositoryInterface"
);
}
$this->customRepositories[$entityClass] = $repositoryClass;
}
/**
* Limpa o cache de repositories.
*/
public function clearCache(): void
{
$this->repositories = [];
}
/**
* Retorna estatísticas de uso dos repositories.
*
* @return array<string, int|string[]>
*/
public function getStats(): array
{
return [
'cached_repositories' => count($this->repositories),
'custom_repositories' => count($this->customRepositories),
'entities' => array_keys($this->repositories),
];
}
}