Passed
Pull Request — master (#54)
by Vincent
06:15
created

ClassMetadataTrait::getClassMetadata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component 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\ApiComponentBundle\Utility;
15
16
use ApiPlatform\Core\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\ApiComponentBundle\Exception\BadMethodCallException;
22
23
/**
24
 * @author Vincent Chalamon <[email protected]>
25
 *
26
 * @internal
27
 */
28
trait ClassMetadataTrait
29
{
30
    use ClassInfoTrait;
31
32
    private ?ManagerRegistry $registry;
33
34
    /**
35
     * @required
36
     */
37 9
    protected function initRegistry(ManagerRegistry $registry): void
38
    {
39 9
        $this->registry = $registry;
40 9
    }
41
42 7
    protected function getClassMetadata(object $data): ClassMetadata
43
    {
44 7
        return $this->getEntityManager($data)->getClassMetadata($this->getObjectClass($data));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getEntityM...>getObjectClass($data)) returns the type Doctrine\Persistence\Mapping\ClassMetadata which includes types incompatible with the type-hinted return Doctrine\ORM\Mapping\ClassMetadata.
Loading history...
45
    }
46
47 7
    private function getEntityManager(object $data): EntityManagerInterface
48
    {
49 7
        if (!$this->registry) {
50
            throw new BadMethodCallException('initRegistry should be called first. Registry property does not exist');
51
        }
52
53 7
        $em = $this->registry->getManagerForClass($this->getObjectClass($data));
54 7
        if (!$em instanceof EntityManagerInterface) {
55
            throw ORMInvalidArgumentException::invalidObject(__CLASS__ . '::' . __FUNCTION__, $data);
56
        }
57
58 7
        return $em;
59
    }
60
}
61