PageSubscriber::postLoad()   D
last analyzed

Complexity

Conditions 10
Paths 13

Size

Total Lines 37
Code Lines 26

Duplication

Lines 9
Ratio 24.32 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 9
loc 37
rs 4.8196
cc 10
eloc 26
nc 13
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Victoire\Bundle\PageBundle\EventSubscriber;
4
5
use Doctrine\Common\EventSubscriber;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\Event\LifecycleEventArgs;
8
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
9
use Doctrine\ORM\Event\OnFlushEventArgs;
10
use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder;
11
use Doctrine\ORM\UnitOfWork;
12
use Symfony\Bundle\FrameworkBundle\Routing\Router;
13
use Victoire\Bundle\APIBusinessEntityBundle\Resolver\APIBusinessEntityResolver;
14
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
15
use Victoire\Bundle\CoreBundle\Entity\EntityProxy;
16
use Victoire\Bundle\CoreBundle\Entity\View;
17
use Victoire\Bundle\CoreBundle\Entity\WebViewInterface;
18
use Victoire\Bundle\ORMBusinessEntityBundle\Entity\ORMBusinessEntity;
19
use Victoire\Bundle\PageBundle\Helper\UserCallableHelper;
20
use Victoire\Bundle\ViewReferenceBundle\Builder\ViewReferenceBuilder;
21
use Victoire\Bundle\ViewReferenceBundle\Connector\ViewReferenceRepository;
22
use Victoire\Bundle\ViewReferenceBundle\ViewReference\BusinessPageReference;
23
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
24
25
/**
26
 * This class listen Page Entity changes.
27
 */
28
class PageSubscriber implements EventSubscriber
29
{
30
    protected $router;
31
    protected $userClass;
32
    protected $userCallableHelper;
33
    protected $urlBuilder;
34
    protected $viewReferenceRepository;
35
    protected $apiBusinessEntityResolver;
36
37
    /**
38
     * Constructor.
39
     *
40
     * @param Router                    $router                    @router
41
     * @param UserCallableHelper        $userCallableHelper        @victoire_page.user_callable
42
     * @param string                    $userClass                 %victoire_core.user_class%
43
     * @param ViewReferenceBuilder      $viewReferenceBuilder
44
     * @param ViewReferenceRepository   $viewReferenceRepository
45
     * @param APIBusinessEntityResolver $apiBusinessEntityResolver
46
     *
47
     * @internal param ViewReferenceBuilder $urlBuilder @victoire_view_reference.builder
48
     */
49
    public function __construct(
50
        Router $router,
51
        UserCallableHelper $userCallableHelper,
52
        $userClass,
53
        ViewReferenceBuilder $viewReferenceBuilder,
54
        ViewReferenceRepository $viewReferenceRepository,
55
        APIBusinessEntityResolver $apiBusinessEntityResolver
56
    ) {
57
        $this->router = $router;
58
        $this->userClass = $userClass;
59
        $this->userCallableHelper = $userCallableHelper;
60
        $this->viewReferenceBuilder = $viewReferenceBuilder;
0 ignored issues
show
Bug introduced by
The property viewReferenceBuilder does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
61
        $this->viewReferenceRepository = $viewReferenceRepository;
62
        $this->apiBusinessEntityResolver = $apiBusinessEntityResolver;
63
    }
64
65
    /**
66
     * bind to LoadClassMetadata method.
67
     *
68
     * @return string[] The subscribed events
69
     */
70
    public function getSubscribedEvents()
71
    {
72
        return [
73
            'loadClassMetadata',
74
            'postLoad',
75
            'onFlush',
76
        ];
77
    }
78
79
    /**
80
     * @param OnFlushEventArgs $eventArgs
81
     */
82 View Code Duplication
    public function onFlush(OnFlushEventArgs $eventArgs)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
83
    {
84
        /** @var EntityManager $entityManager */
85
        $entityManager = $eventArgs->getEntityManager();
86
        /** @var UnitOfWork $uow */
87
        $uow = $entityManager->getUnitOfWork();
88
89
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
90
            if ($entity instanceof View) {
91
                $entity->setAuthor($this->userCallableHelper->getCurrentUser());
92
            }
93
        }
94
    }
95
96
    /**
97
     * Insert enabled widgets in base widget DiscriminatorMap.
98
     *
99
     * @param LoadClassMetadataEventArgs $eventArgs
100
     */
101 View Code Duplication
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        $metadata = $eventArgs->getClassMetadata();
104
105
        //set a relation between Page and User to define the page author
106
        $metaBuilder = new ClassMetadataBuilder($metadata);
0 ignored issues
show
Documentation introduced by
$metadata is of type object<Doctrine\ORM\EntityManager>, but the function expects a object<Doctrine\ORM\Mapping\ClassMetadataInfo>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
107
108
        //Add author relation on view
109
        if ($this->userClass && $metadata->name === 'Victoire\Bundle\CoreBundle\Entity\View') {
0 ignored issues
show
Bug introduced by
The property name does not seem to exist in Doctrine\ORM\EntityManager.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
110
            $metadata->mapManyToOne([
0 ignored issues
show
Bug introduced by
The method mapManyToOne() does not seem to exist on object<Doctrine\ORM\EntityManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
111
                'fieldName'    => 'author',
112
                'targetEntity' => $this->userClass,
113
                'cascade'      => ['persist'],
114
                'inversedBy'   => 'pages',
115
                'joinColumns'  => [
116
                    [
117
                        'name'                 => 'author_id',
118
                        'referencedColumnName' => 'id',
119
                        'onDelete'             => 'SET NULL',
120
                    ],
121
                ],
122
            ]);
123
        }
124
125
        // if $pages property exists, add the inversed side on User
126
        if ($metadata->name === $this->userClass && property_exists($this->userClass, 'pages')) {
127
            $metaBuilder->addOneToMany('pages', 'Victoire\Bundle\CoreBundle\Entity\View', 'author');
128
        }
129
    }
130
131
    /**
132
     * If entity is a View
133
     * it will find the ViewReference related to the current view and populate its url.
134
     *
135
     * @param LifecycleEventArgs $eventArgs
136
     */
137
    public function postLoad(LifecycleEventArgs $eventArgs)
138
    {
139
        $view = $eventArgs->getEntity();
140
141
        if ($view instanceof View) {
142
            $view->setReferences([$view->getCurrentLocale() => new ViewReference($view->getId())]);
143
            $viewReferences = $this->viewReferenceRepository->getReferencesByParameters([
144
                'viewId'     => $view->getId(),
145
                'templateId' => $view->getId(),
146
            ], true, false, 'OR');
147
            foreach ($viewReferences as $viewReference) {
148
                if ($viewReference->getLocale() === $view->getCurrentLocale()) {
149
                    if ($view instanceof WebViewInterface && $viewReference instanceof ViewReference) {
150
                        $view->setReference($viewReference, $viewReference->getLocale());
151
                        $view->setUrl($viewReference->getUrl());
152
                    }
153
                }
154
            }
155
            if ($view instanceof BusinessPage && ($businessEntity = $view->getEntityProxy()->getBusinessEntity()) && $view->getReference() instanceof BusinessPageReference) {
156
                $entityProxy = $view->getEntityProxy();
157
                $viewReference = $view->getReference();
158
159 View Code Duplication
                if ($businessEntity->getType() === ORMBusinessEntity::TYPE) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
160
                    $entity = $eventArgs->getEntityManager()->getRepository($businessEntity->getClass())
161
                        ->findOneBy(['id' => $viewReference->getEntityId()]);
162
                } else {
163
                    $entityProxy = new EntityProxy();
164
                    $entityProxy->setBusinessEntity($businessEntity);
165
                    $entityProxy->setRessourceId($viewReference->getEntityId());
166
                    $entity = $this->apiBusinessEntityResolver->getBusinessEntity($entityProxy);
167
                }
168
169
                $entityProxy->setEntity($entity);
170
                $view->setEntityProxy($entityProxy);
171
            }
172
        }
173
    }
174
}
175