Completed
Push — master ( 0eab77...b2f729 )
by Paul
05:35
created

PageSubscriber::postLoad()   D

Complexity

Conditions 10
Paths 13

Size

Total Lines 37
Code Lines 26

Duplication

Lines 9
Ratio 24.32 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 9
loc 37
rs 4.8196
c 1
b 0
f 0
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 Gedmo\Translatable\TranslatableListener;
13
use Symfony\Bundle\FrameworkBundle\Routing\Router;
14
use Victoire\Bundle\APIBusinessEntityBundle\Resolver\APIBusinessEntityResolver;
15
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
16
use Victoire\Bundle\CoreBundle\Entity\EntityProxy;
17
use Victoire\Bundle\CoreBundle\Entity\View;
18
use Victoire\Bundle\CoreBundle\Entity\WebViewInterface;
19
use Victoire\Bundle\ORMBusinessEntityBundle\Entity\ORMBusinessEntity;
20
use Victoire\Bundle\PageBundle\Helper\UserCallableHelper;
21
use Victoire\Bundle\ViewReferenceBundle\Builder\ViewReferenceBuilder;
22
use Victoire\Bundle\ViewReferenceBundle\Connector\ViewReferenceRepository;
23
use Victoire\Bundle\ViewReferenceBundle\ViewReference\BusinessPageReference;
24
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
25
26
/**
27
 * This class listen Page Entity changes.
28
 */
29
class PageSubscriber implements EventSubscriber
30
{
31
    protected $router;
32
    protected $userClass;
33
    protected $userCallableHelper;
34
    protected $urlBuilder;
35
    protected $viewReferenceRepository;
36
    /**
37
     * @var APIBusinessEntityResolver
38
     */
39
    private $apiBusinessEntityResolver;
40
41
    /**
42
     * Constructor.
43
     *
44
     * @param Router                    $router                    @router
45
     * @param UserCallableHelper        $userCallableHelper        @victoire_page.user_callable
46
     * @param string                    $userClass                 %victoire_core.user_class%
47
     * @param ViewReferenceBuilder      $viewReferenceBuilder
48
     * @param ViewReferenceRepository   $viewReferenceRepository
49
     * @param TranslatableListener      $translatableListener
50
     * @param APIBusinessEntityResolver $apiBusinessEntityResolver
51
     *
52
     * @internal param ViewReferenceBuilder $urlBuilder @victoire_view_reference.builder
53
     */
54
    public function __construct(
55
        Router $router,
56
        UserCallableHelper $userCallableHelper,
57
        $userClass,
58
        ViewReferenceBuilder $viewReferenceBuilder,
59
        ViewReferenceRepository $viewReferenceRepository,
60
        TranslatableListener $translatableListener,
61
        APIBusinessEntityResolver $apiBusinessEntityResolver
62
    ) {
63
        $this->router = $router;
64
        $this->userClass = $userClass;
65
        $this->userCallableHelper = $userCallableHelper;
66
        $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...
67
        $this->viewReferenceRepository = $viewReferenceRepository;
68
        $this->translatableListener = $translatableListener;
0 ignored issues
show
Bug introduced by
The property translatableListener 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...
69
        $this->apiBusinessEntityResolver = $apiBusinessEntityResolver;
70
    }
71
72
    /**
73
     * bind to LoadClassMetadata method.
74
     *
75
     * @return string[] The subscribed events
76
     */
77
    public function getSubscribedEvents()
78
    {
79
        return [
80
            'loadClassMetadata',
81
            'postLoad',
82
            'onFlush',
83
        ];
84
    }
85
86
    /**
87
     * @param OnFlushEventArgs $eventArgs
88
     */
89 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...
90
    {
91
        /** @var EntityManager $entityManager */
92
        $entityManager = $eventArgs->getEntityManager();
93
        /** @var UnitOfWork $uow */
94
        $uow = $entityManager->getUnitOfWork();
95
96
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
97
            if ($entity instanceof View) {
98
                $entity->setAuthor($this->userCallableHelper->getCurrentUser());
99
            }
100
        }
101
    }
102
103
    /**
104
     * Insert enabled widgets in base widget DiscriminatorMap.
105
     *
106
     * @param LoadClassMetadataEventArgs $eventArgs
107
     */
108 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...
109
    {
110
        $metadata = $eventArgs->getClassMetadata();
111
112
        //set a relation between Page and User to define the page author
113
        $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...
114
115
        //Add author relation on view
116
        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...
117
            $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...
118
                'fieldName'    => 'author',
119
                'targetEntity' => $this->userClass,
120
                'cascade'      => ['persist'],
121
                'inversedBy'   => 'pages',
122
                'joinColumns'  => [
123
                    [
124
                        'name'                 => 'author_id',
125
                        'referencedColumnName' => 'id',
126
                        'onDelete'             => 'SET NULL',
127
                    ],
128
                ],
129
            ]);
130
        }
131
132
        // if $pages property exists, add the inversed side on User
133
        if ($metadata->name === $this->userClass && property_exists($this->userClass, 'pages')) {
134
            $metaBuilder->addOneToMany('pages', 'Victoire\Bundle\CoreBundle\Entity\View', 'author');
135
        }
136
    }
137
138
    /**
139
     * If entity is a View
140
     * it will find the ViewReference related to the current view and populate its url.
141
     *
142
     * @param LifecycleEventArgs $eventArgs
143
     */
144
    public function postLoad(LifecycleEventArgs $eventArgs)
145
    {
146
        $view = $eventArgs->getEntity();
147
148
        if ($view instanceof View) {
149
            $view->setReferences([$view->getCurrentLocale() => new ViewReference($view->getId())]);
150
            $viewReferences = $this->viewReferenceRepository->getReferencesByParameters([
151
                'viewId'     => $view->getId(),
152
                'templateId' => $view->getId(),
153
            ], true, false, 'OR');
154
            foreach ($viewReferences as $viewReference) {
155
                if ($viewReference->getLocale() === $view->getCurrentLocale()) {
156
                    if ($view instanceof WebViewInterface && $viewReference instanceof ViewReference) {
157
                        $view->setReference($viewReference, $viewReference->getLocale());
158
                        $view->setUrl($viewReference->getUrl());
159
                    }
160
                }
161
            }
162
            if ($view instanceof BusinessPage && ($businessEntity = $view->getEntityProxy()->getBusinessEntity()) && $view->getReference() instanceof BusinessPageReference) {
163
                $entityProxy = $view->getEntityProxy();
164
                $viewReference = $view->getReference();
165
166 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...
167
                    $entity = $eventArgs->getEntityManager()->getRepository($businessEntity->getClass())
168
                        ->findOneBy(['id' => $viewReference->getEntityId()]);
169
                } else {
170
                    $entityProxy = new EntityProxy();
171
                    $entityProxy->setBusinessEntity($businessEntity);
172
                    $entityProxy->setRessourceId($viewReference->getEntityId());
173
                    $entity = $this->apiBusinessEntityResolver->getBusinessEntity($entityProxy);
174
                }
175
176
                $entityProxy->setEntity($entity);
177
                $view->setEntityProxy($entityProxy);
178
            }
179
        }
180
    }
181
}
182