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