Passed
Pull Request — master (#14)
by Adrien
13:59
created

FilteredFieldResolver::load()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Api;
6
7
use Doctrine\ORM\EntityNotFoundException;
8
use Doctrine\Persistence\Proxy;
9
use GraphQL\Doctrine\DefaultFieldResolver;
10
use GraphQL\Type\Definition\ResolveInfo;
11
12
/**
13
 * A field resolver that will ensure that filtered entity are never returned via getter.
14
 */
15
final class FilteredFieldResolver
16
{
17
    private readonly DefaultFieldResolver $resolver;
18
19 11
    public function __construct()
20
    {
21 11
        $this->resolver = new DefaultFieldResolver();
0 ignored issues
show
Bug introduced by
The property resolver is declared read-only in Ecodev\Felix\Api\FilteredFieldResolver.
Loading history...
22
    }
23
24
    /**
25
     * @param mixed[] $args
26
     */
27 7
    public function __invoke(mixed $source, array $args, mixed $context, ResolveInfo $info): mixed
28
    {
29 7
        $value = $this->resolver->__invoke($source, $args, $context, $info);
30
31 7
        return $this->load($value);
32
    }
33
34
    /**
35
     * Try to load the entity from DB, but if it is filtered, it will return null.
36
     *
37
     * This mechanic is necessary to hide entities that should have been filtered by
38
     * AclFilter, but that are accessed via lazy-loaded by doctrine on a *-to-one relation.
39
     * This scenario is described in details on https://github.com/doctrine/doctrine2/issues/4543
40
     *
41
     * @param mixed $object object or any kind of value
42
     */
43 7
    private function load(mixed $object): mixed
44
    {
45 7
        if ($object instanceof Proxy) {
46
            try {
47 2
                $object->__load();
48 1
            } catch (EntityNotFoundException) {
49 1
                return null;
50
            }
51
        }
52
53 6
        return $object;
54
    }
55
}
56