forked from doctrine/DoctrineBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LazyServiceEntityRepository.php
82 lines (64 loc) · 2.24 KB
/
LazyServiceEntityRepository.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
<?php
namespace Doctrine\Bundle\DoctrineBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use LogicException;
use Symfony\Component\VarExporter\LazyObjectInterface;
use function debug_backtrace;
use function sprintf;
use const DEBUG_BACKTRACE_IGNORE_ARGS;
/**
* @internal Extend {@see ServiceEntityRepository} instead.
*
* @template T of object
* @template-extends EntityRepository<T>
*/
class LazyServiceEntityRepository extends EntityRepository implements ServiceEntityRepositoryInterface
{
private ManagerRegistry $registry;
private string $entityClass;
/**
* @param string $entityClass The class name of the entity this repository manages
* @psalm-param class-string<T> $entityClass
*/
public function __construct(ManagerRegistry $registry, string $entityClass)
{
$this->registry = $registry;
$this->entityClass = $entityClass;
if ($this instanceof LazyObjectInterface) {
$this->initialize();
return;
}
unset($this->_em);
unset($this->_class);
unset($this->_entityName);
}
/** @return mixed */
public function __get(string $name)
{
$this->initialize();
$scope = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['class'] ?? null;
return (function () use ($name) {
return $this->$name;
})->bindTo($this, $scope)();
}
public function __isset(string $name): bool
{
$this->initialize();
$scope = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['class'] ?? null;
return (function () use ($name) {
return isset($this->$name);
})->bindTo($this, $scope)();
}
private function initialize(): void
{
$manager = $this->registry->getManagerForClass($this->entityClass);
if ($manager === null) {
throw new LogicException(sprintf(
'Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity’s metadata.',
$this->entityClass,
));
}
parent::__construct($manager, $manager->getClassMetadata($this->entityClass));
}
}