Completed
Push — 2.x ( a366d0...44eaeb )
by Aleksei
21s queued 15s
created

RoleResolver::resolveRole()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 14
nc 5
nop 1
dl 0
loc 26
rs 8.8333
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\ORM\Service\Implementation;
6
7
use Cycle\ORM\EntityProxyInterface;
8
use Cycle\ORM\Exception\ORMException;
9
use Cycle\ORM\Heap\HeapInterface;
10
use Cycle\ORM\SchemaInterface;
11
use Cycle\ORM\Service\RoleResolverInterface;
12
13
/**
14
 * @internal
15
 */
16
final class RoleResolver implements RoleResolverInterface
17
{
18
    private SchemaInterface $schema;
19
    private HeapInterface $heap;
20
21
    public function __construct(SchemaInterface $schema, HeapInterface $heap)
22
    {
23
        $this->schema = $schema;
24
        $this->heap = $heap;
25
    }
26
27
    public function resolveRole(object|string $entity): string
28
    {
29
        if (\is_object($entity)) {
30
            $node = $this->heap->get($entity);
31
            if ($node !== null) {
32
                return $node->getRole();
33
            }
34
35
            /** @var class-string $class */
36
            $class = $entity::class;
37
            if (!$this->schema->defines($class)) {
38
                $parentClass = \get_parent_class($entity);
39
40
                if ($parentClass === false
41
                    || !$entity instanceof EntityProxyInterface
42
                    || !$this->schema->defines($parentClass)
43
                ) {
44
                    throw new ORMException("Unable to resolve role of `$class`.");
45
                }
46
                $class = $parentClass;
47
            }
48
49
            $entity = $class;
50
        }
51
52
        return $this->schema->resolveAlias($entity) ?? throw new ORMException("Unable to resolve role `$entity`.");
53
    }
54
}
55