Passed
Push — master ( 5cd32c...1a1aa9 )
by Rafael
05:46
created

SimpleIDEncoder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 88.24%

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 50
ccs 15
cts 17
cp 0.8824
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 6 1
A decode() 0 15 3
A __construct() 0 4 1
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Encoder;
12
13
use Doctrine\Bundle\DoctrineBundle\Registry;
14
use Doctrine\Common\Util\ClassUtils;
15
use Doctrine\ORM\EntityManagerInterface;
16
use Ynlo\GraphQLBundle\Definition\Registry\DefinitionRegistry;
17
use Ynlo\GraphQLBundle\Model\NodeInterface;
18
19
class SimpleIDEncoder implements IDEncoderInterface
20
{
21
    private const DIVIDER = ':';
22
23
    /**
24
     * @var Registry
25
     */
26
    protected $doctrine;
27
28
    /**
29
     * @var DefinitionRegistry
30
     */
31
    protected $definitionRegistry;
32
33
34 22
    public function __construct(DefinitionRegistry $definitionRegistry, Registry $registry)
35
    {
36 22
        $this->doctrine = $registry;
37 22
        $this->definitionRegistry = $definitionRegistry;
38 22
    }
39
40
    /**
41
     * {@inheritDoc}
42
     */
43 19
    public function encode(NodeInterface $node): ?string
44
    {
45 19
        $class = ClassUtils::getClass($node);
46 19
        $nodeType = $this->definitionRegistry->getEndpoint()->getTypeForClass($class);
47
48 19
        return sprintf('%s%s%s', $nodeType, self::DIVIDER, $node->getId());
49
    }
50
51
    /**
52
     * {@inheritDoc}
53
     */
54 12
    public function decode($globalId): ?NodeInterface
55
    {
56 12
        if (strpos($globalId, self::DIVIDER) > 1) {
57 12
            list($nodeType, $databaseId) = explode(self::DIVIDER, $globalId);
58
59 12
            $class = $this->definitionRegistry->getEndpoint()->getClassForType($nodeType);
60 12
            $manager = $this->doctrine->getManager();
61 12
            if ($manager instanceof EntityManagerInterface) {
0 ignored issues
show
introduced by
$manager is always a sub-type of Doctrine\ORM\EntityManagerInterface.
Loading history...
62 12
                return $manager->getReference($class, $databaseId);
63
            }
64
65
            throw new \UnexpectedValueException('Not supported doctrine manager.');
66
        }
67
68
        return null;
69
    }
70
}
71