Failed Conditions
Pull Request — master (#11)
by Adrien
15:48 queued 12:33
created

FilteredFieldResolver   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
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 45
ccs 12
cts 12
cp 1
rs 10
wmc 5
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;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 17 at column 21
Loading history...
18
19 7
    public function __construct()
20
    {
21 7
        $this->resolver = new DefaultFieldResolver();
22 7
    }
23
24
    /**
25
     * @param mixed $source
26
     * @param mixed[] $args
27
     * @param mixed $context
28
     *
29
     * @return null|mixed
30
     */
31 7
    public function __invoke($source, array $args, $context, ResolveInfo $info)
32
    {
33 7
        $value = $this->resolver->__invoke($source, $args, $context, $info);
34
35 7
        return $this->load($value);
36
    }
37
38
    /**
39
     * Try to load the entity from DB, but if it is filtered, it will return null.
40
     *
41
     * This mechanic is necessary to hide entities that should have been filtered by
42
     * AclFilter, but that are accessed via lazy-loaded by doctrine on a *-to-one relation.
43
     * This scenario is described in details on https://github.com/doctrine/doctrine2/issues/4543
44
     *
45
     * @param mixed $object or any kind of value
46
     *
47
     * @return mixed
48
     */
49 7
    private function load($object)
50
    {
51 7
        if ($object instanceof Proxy) {
52
            try {
53 2
                $object->__load();
54 1
            } catch (EntityNotFoundException) {
55 1
                return null;
56
            }
57
        }
58
59 6
        return $object;
60
    }
61
}
62