1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Silverback API Components Bundle Project |
5
|
|
|
* |
6
|
|
|
* (c) Daniel West <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Silverback\ApiComponentsBundle\Utility; |
15
|
|
|
|
16
|
|
|
use ApiPlatform\Util\ClassInfoTrait; |
17
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
18
|
|
|
use Doctrine\ORM\Mapping\ClassMetadata; |
19
|
|
|
use Doctrine\ORM\ORMInvalidArgumentException; |
20
|
|
|
use Doctrine\Persistence\ManagerRegistry; |
21
|
|
|
use Silverback\ApiComponentsBundle\Exception\BadMethodCallException; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @author Vincent Chalamon <[email protected]> |
25
|
|
|
* |
26
|
|
|
* @internal |
27
|
|
|
*/ |
28
|
|
|
trait ClassMetadataTrait |
29
|
|
|
{ |
30
|
|
|
use ClassInfoTrait; |
31
|
|
|
|
32
|
|
|
protected ?ManagerRegistry $registry; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @required |
36
|
|
|
*/ |
37
|
|
|
protected function initRegistry(ManagerRegistry $registry): void |
38
|
|
|
{ |
39
|
|
|
$this->registry = $registry; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string|object $data |
44
|
|
|
*/ |
45
|
|
|
protected function getClassMetadata($data): ClassMetadata |
46
|
|
|
{ |
47
|
|
|
return $this->getEntityManager($data)->getClassMetadata($this->getObjectClassFromStringOrObject($data)); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param string|object $data |
52
|
|
|
*/ |
53
|
|
|
protected function getEntityManager($data): EntityManagerInterface |
54
|
|
|
{ |
55
|
|
|
if (!$this->registry) { |
56
|
|
|
throw new BadMethodCallException('initRegistry should be called first. Registry property does not exist'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$em = $this->registry->getManagerForClass($this->getObjectClassFromStringOrObject($data)); |
60
|
|
|
if (!$em instanceof EntityManagerInterface) { |
61
|
|
|
throw ORMInvalidArgumentException::invalidObject(__CLASS__ . '::' . __FUNCTION__, $data); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $em; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param string|object $object |
69
|
|
|
*/ |
70
|
|
|
private function getObjectClassFromStringOrObject($object): string |
71
|
|
|
{ |
72
|
|
|
return \is_string($object) ? $object : $this->getObjectClass($object); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|