|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Cycle\Factory; |
|
6
|
|
|
|
|
7
|
|
|
use Closure; |
|
8
|
|
|
use Cycle\ORM\ORMInterface; |
|
9
|
|
|
use Cycle\ORM\RepositoryInterface; |
|
10
|
|
|
use Cycle\ORM\SchemaInterface; |
|
11
|
|
|
use Yiisoft\Di\Container; |
|
12
|
|
|
use Yiisoft\Di\Support\ServiceProvider; |
|
13
|
|
|
|
|
14
|
|
|
use function is_string; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* This provider provides factories to the container for creating Cycle entity repositories. |
|
18
|
|
|
* Repository list is compiled based on data from the database schema. |
|
19
|
|
|
*/ |
|
20
|
|
|
final class RepositoryProvider extends ServiceProvider |
|
21
|
|
|
{ |
|
22
|
|
|
public function register(Container $container): void |
|
23
|
|
|
{ |
|
24
|
|
|
/** @var ORMInterface */ |
|
25
|
|
|
$orm = $container->get(ORMInterface::class); |
|
26
|
|
|
/** @psalm-suppress InaccessibleMethod */ |
|
27
|
|
|
$container->setMultiple($this->getRepositoryFactories($orm)); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @return array<string, Closure> Repository name as key and factory as value |
|
32
|
|
|
*/ |
|
33
|
|
|
private function getRepositoryFactories(ORMInterface $orm): array |
|
34
|
|
|
{ |
|
35
|
|
|
$schema = $orm->getSchema(); |
|
36
|
|
|
$result = []; |
|
37
|
|
|
$roles = []; |
|
38
|
|
|
foreach ($schema->getRoles() as $role) { |
|
39
|
|
|
$repository = $schema->define($role, SchemaInterface::REPOSITORY); |
|
40
|
|
|
if (is_string($repository)) { |
|
41
|
|
|
$roles[$repository][] = $role; |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
foreach ($roles as $repo => $role) { |
|
45
|
|
|
if (count($role) === 1) { |
|
46
|
|
|
$result[$repo] = $this->makeRepositoryFactory($orm, current($role)); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
return $result; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @psalm-pure |
|
54
|
|
|
*/ |
|
55
|
|
|
private function makeRepositoryFactory(ORMInterface $orm, string $role): Closure |
|
56
|
|
|
{ |
|
57
|
|
|
return static fn (): RepositoryInterface => $orm->getRepository($role); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|