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

FilteredFieldResolver   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __invoke() 0 5 1
A load() 0 11 3
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