EntityIDType::serialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 6
rs 10
ccs 3
cts 3
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQL\Doctrine\Definition;
6
7
use Doctrine\ORM\EntityManager;
8
use GraphQL\Doctrine\Utils;
9
use GraphQL\Error\Error;
10
use GraphQL\Language\AST\IntValueNode;
11
use GraphQL\Language\AST\Node;
12
use GraphQL\Language\AST\StringValueNode;
13
use GraphQL\Type\Definition\ScalarType;
14
15
/**
16
 * A specialized ID type that allows to fetch entity from DB.
17
 */
18
final class EntityIDType extends ScalarType
19
{
20
    /**
21
     * @param class-string $className The entity class name
22
     */
23 20
    public function __construct(
24
        private readonly EntityManager $entityManager,
25
        private readonly string $className,
26
        string $typeName,
27
    ) {
28 20
        $this->name = $typeName;
29 20
        $this->description = 'Automatically generated type to be used as input where an object of type `' . Utils::getTypeName($className) . '` is needed';
30
31 20
        parent::__construct();
32
    }
33
34
    /**
35
     * Serializes an internal value to include in a response.
36
     *
37
     * @param object $value
38
     */
39 1
    public function serialize($value): string
40
    {
41 1
        $id = $this->entityManager->getClassMetadata($this->className)->getIdentifierValues($value);
42
43
        // @phpstan-ignore-next-line
44 1
        return (string) reset($id);
45
    }
46
47
    /**
48
     * Parses an externally provided value (query variable) to use as an input.
49
     */
50 4
    public function parseValue(mixed $value): EntityID
51
    {
52 4
        if (!is_string($value) && !is_int($value)) {
53 1
            throw new Error('EntityID cannot represent value: ' . \GraphQL\Utils\Utils::printSafe($value));
54
        }
55
56 3
        return $this->createEntityID((string) $value);
57
    }
58
59
    /**
60
     * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input.
61
     */
62 4
    public function parseLiteral(Node $valueNode, ?array $variables = null): EntityID
63
    {
64 4
        if ($valueNode instanceof StringValueNode || $valueNode instanceof IntValueNode) {
65 3
            return $this->createEntityID((string) $valueNode->value);
66
        }
67
68
        // Intentionally without message, as all information already in wrapped Exception
69 1
        throw new Error();
70
    }
71
72
    /**
73
     * Create EntityID to retrieve entity from DB later on.
74
     */
75 6
    private function createEntityID(string $id): EntityID
76
    {
77 6
        return new EntityID($this->entityManager, $this->className, $id);
78
    }
79
}
80