1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\Foundry; |
4
|
|
|
|
5
|
|
|
use Doctrine\Persistence\ManagerRegistry; |
6
|
|
|
use Doctrine\Persistence\ObjectManager; |
7
|
|
|
use Doctrine\Persistence\ObjectRepository; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @author Kevin Bond <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
final class PersistenceManager |
13
|
|
|
{ |
14
|
|
|
private static ?ManagerRegistry $managerRegistry = null; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param object|string $objectOrClass |
18
|
|
|
* |
19
|
|
|
* @return RepositoryProxy|ObjectRepository |
20
|
|
|
*/ |
21
|
30 |
|
public static function repositoryFor($objectOrClass, bool $proxy = true): ObjectRepository |
22
|
|
|
{ |
23
|
30 |
|
if ($objectOrClass instanceof Proxy) { |
24
|
2 |
|
$objectOrClass = $objectOrClass->object(); |
25
|
|
|
} |
26
|
|
|
|
27
|
30 |
|
if (!\is_string($objectOrClass)) { |
28
|
8 |
|
$objectOrClass = \get_class($objectOrClass); |
29
|
|
|
} |
30
|
|
|
|
31
|
30 |
|
$repository = self::managerRegistry()->getRepository($objectOrClass); |
32
|
|
|
|
33
|
30 |
|
return $proxy ? new RepositoryProxy($repository) : $repository; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @return Proxy|object |
38
|
|
|
*/ |
39
|
58 |
|
public static function persist(object $object, bool $proxy = true): object |
40
|
|
|
{ |
41
|
58 |
|
$objectManager = self::objectManagerFor($object); |
42
|
58 |
|
$objectManager->persist($object); |
43
|
58 |
|
$objectManager->flush(); |
44
|
|
|
|
45
|
58 |
|
return $proxy ? self::proxy($object) : $object; |
46
|
|
|
} |
47
|
|
|
|
48
|
54 |
|
public static function proxy(object $object): Proxy |
49
|
|
|
{ |
50
|
54 |
|
if ($object instanceof Proxy) { |
51
|
40 |
|
return $object; |
52
|
|
|
} |
53
|
|
|
|
54
|
54 |
|
return new Proxy($object); |
55
|
|
|
} |
56
|
|
|
|
57
|
70 |
|
public static function register(ManagerRegistry $managerRegistry): void |
58
|
|
|
{ |
59
|
70 |
|
self::$managerRegistry = $managerRegistry; |
60
|
70 |
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param object|string $objectOrClass |
64
|
|
|
*/ |
65
|
62 |
|
public static function objectManagerFor($objectOrClass): ObjectManager |
66
|
|
|
{ |
67
|
62 |
|
$class = \is_string($objectOrClass) ? $objectOrClass : \get_class($objectOrClass); |
68
|
|
|
|
69
|
62 |
|
if (!$objectManager = self::managerRegistry()->getManagerForClass($class)) { |
70
|
2 |
|
throw new \RuntimeException(\sprintf('No object manager registered for "%s".', $class)); |
71
|
|
|
} |
72
|
|
|
|
73
|
58 |
|
return $objectManager; |
74
|
|
|
} |
75
|
|
|
|
76
|
72 |
|
private static function managerRegistry(): ManagerRegistry |
77
|
|
|
{ |
78
|
72 |
|
if (null === self::$managerRegistry) { |
79
|
2 |
|
throw new \RuntimeException('ManagerRegistry not registered...'); // todo improve |
80
|
|
|
} |
81
|
|
|
|
82
|
70 |
|
return self::$managerRegistry; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|