Passed
Pull Request — master (#50)
by Daniel
07:55
created

ClassMetadataTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 5
eloc 11
c 1
b 1
f 0
dl 0
loc 28
ccs 10
cts 12
cp 0.8333
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A initRegistry() 0 3 1
A getEntityManager() 0 12 3
A getClassMetadata() 0 3 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 9
    private function initRegistry(ManagerRegistry $registry): void
35
    {
36 9
        $this->registry = $registry;
37 9
    }
38
39 7
    private function getClassMetadata(object $data): ClassMetadata
40
    {
41 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...
42
    }
43
44 7
    private function getEntityManager(object $data): EntityManagerInterface
45
    {
46 7
        if (!$this->registry) {
47
            throw new BadMethodCallException('initRegistry should be called first. Registry property does not exist');
48
        }
49
50 7
        $em = $this->registry->getManagerForClass($this->getObjectClass($data));
51 7
        if (!$em instanceof EntityManagerInterface) {
52
            throw ORMInvalidArgumentException::invalidObject(__CLASS__ . '::' . __FUNCTION__, $data);
53
        }
54
55 7
        return $em;
56
    }
57
}
58