Completed
Push — master ( 186982...2975e7 )
by Rafael
05:12
created

NodeDeferredListener   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 41
ccs 0
cts 20
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 4 1
A __construct() 0 3 1
A postReadField() 0 12 4
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\EventListener\GraphQL;
12
13
use Doctrine\ORM\Proxy\Proxy;
14
use GraphQL\Deferred;
15
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
16
use Ynlo\GraphQLBundle\Events\GraphQLEvents;
17
use Ynlo\GraphQLBundle\Events\GraphQLFieldEvent;
18
use Ynlo\GraphQLBundle\Model\NodeInterface;
19
use Ynlo\GraphQLBundle\Resolver\DeferredBuffer;
20
21
/**
22
 * NodeDeferredListener
23
 */
24
class NodeDeferredListener implements EventSubscriberInterface
25
{
26
    /**
27
     * @var DeferredBuffer
28
     */
29
    private $deferredBuffer;
30
31
    /**
32
     *
33
     * @param DeferredBuffer $deferredBuffer
34
     */
35
    public function __construct(DeferredBuffer $deferredBuffer)
36
    {
37
        $this->deferredBuffer = $deferredBuffer;
38
    }
39
40
    /**
41
     * @inheritDoc
42
     */
43
    public static function getSubscribedEvents()
44
    {
45
        return [
46
            GraphQLEvents::POST_READ_FIELD => 'postReadField',
47
        ];
48
    }
49
50
    /**
51
     * @param GraphQLFieldEvent $event
52
     */
53
    public function postReadField(GraphQLFieldEvent $event)
54
    {
55
        $value = $event->getValue();
56
        if ($value instanceof Proxy && $value instanceof NodeInterface && !$value->__isInitialized()) {
57
            $this->deferredBuffer->add($value);
58
59
            $event->setValue(
60
                new Deferred(
61
                    function () use ($value) {
62
                        $this->deferredBuffer->loadBuffer();
63
64
                        return $this->deferredBuffer->getLoadedEntity($value);
65
                    }
66
                )
67
            );
68
        }
69
    }
70
}