Completed
Pull Request — master (#465)
by Leny
08:51
created

PageSubscriber::postLoad()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 22
rs 8.6737
cc 6
eloc 15
nc 5
nop 1
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\CoreBundle\Entity\View;
15
use Victoire\Bundle\CoreBundle\Entity\WebViewInterface;
16
use Victoire\Bundle\PageBundle\Helper\UserCallableHelper;
17
use Victoire\Bundle\ViewReferenceBundle\Builder\ViewReferenceBuilder;
18
use Victoire\Bundle\ViewReferenceBundle\Connector\ViewReferenceRepository;
19
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
20
21
/**
22
 * This class listen Page Entity changes.
23
 */
24
class PageSubscriber implements EventSubscriber
25
{
26
    protected $router;
27
    protected $userClass;
28
    protected $userCallableHelper;
29
    protected $urlBuilder;
30
    protected $viewReferenceRepository;
31
32
    /**
33
     * Constructor.
34
     *
35
     * @param Router                  $router                  @router
36
     * @param UserCallableHelper      $userCallableHelper      @victoire_page.user_callable
37
     * @param string                  $userClass               %victoire_core.user_class%
38
     * @param ViewReferenceBuilder    $viewReferenceBuilder
39
     * @param ViewReferenceRepository $viewReferenceRepository
40
     * @param TranslatableListener    $translatableListener
41
     *
42
     * @internal param ViewReferenceBuilder $urlBuilder @victoire_view_reference.builder
43
     */
44
    public function __construct(
45
        Router $router,
46
        UserCallableHelper $userCallableHelper,
47
        $userClass,
48
        ViewReferenceBuilder $viewReferenceBuilder,
49
        ViewReferenceRepository $viewReferenceRepository,
50
        TranslatableListener $translatableListener
51
    ) {
52
        $this->router = $router;
53
        $this->userClass = $userClass;
54
        $this->userCallableHelper = $userCallableHelper;
55
        $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...
56
        $this->viewReferenceRepository = $viewReferenceRepository;
57
        $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...
58
    }
59
60
    /**
61
     * bind to LoadClassMetadata method.
62
     *
63
     * @return string[] The subscribed events
64
     */
65
    public function getSubscribedEvents()
66
    {
67
        return [
68
            'loadClassMetadata',
69
            'postLoad',
70
            'onFlush',
71
        ];
72
    }
73
74
    /**
75
     * @param OnFlushEventArgs $eventArgs
76
     */
77
    public function onFlush(OnFlushEventArgs $eventArgs)
78
    {
79
        /** @var EntityManager $entityManager */
80
        $entityManager = $eventArgs->getEntityManager();
81
        /** @var UnitOfWork $uow */
82
        $uow = $entityManager->getUnitOfWork();
83
84
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
85
            if ($entity instanceof View) {
86
                $entity->setAuthor($this->userCallableHelper->getCurrentUser());
87
            }
88
        }
89
    }
90
91
    /**
92
     * Insert enabled widgets in base widget DiscriminatorMap.
93
     *
94
     * @param LoadClassMetadataEventArgs $eventArgs
95
     */
96
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
97
    {
98
        $metadata = $eventArgs->getClassMetadata();
99
100
        //set a relation between Page and User to define the page author
101
        $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...
102
103
        //Add author relation on view
104 View Code Duplication
        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...
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...
105
            $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...
106
                'fieldName'    => 'author',
107
                'targetEntity' => $this->userClass,
108
                'cascade'      => ['persist'],
109
                'inversedBy'   => 'pages',
110
                'joinColumns'  => [
111
                    [
112
                        'name'                 => 'author_id',
113
                        'referencedColumnName' => 'id',
114
                        'onDelete'             => 'SET NULL',
115
                    ],
116
                ],
117
            ]);
118
        }
119
120
        // if $pages property exists, add the inversed side on User
121
        if ($metadata->name === $this->userClass && property_exists($this->userClass, 'pages')) {
122
            $metaBuilder->addOneToMany('pages', 'Victoire\Bundle\CoreBundle\Entity\View', 'author');
123
        }
124
    }
125
126
    /**
127
     * If entity is a View
128
     * it will find the ViewReference related to the current view and populate its url.
129
     *
130
     * @param LifecycleEventArgs $eventArgs
131
     */
132
    public function postLoad(LifecycleEventArgs $eventArgs)
133
    {
134
        $entity = $eventArgs->getEntity();
135
136
        if ($entity instanceof View) {
137
            $entity->setReferences([$entity->getCurrentLocale() => new ViewReference($entity->getId())]);
138
            $viewReferences = $this->viewReferenceRepository->getReferencesByParameters([
139
                'viewId'     => $entity->getId(),
140
                'templateId' => $entity->getId(),
141
            ], true, false, 'OR');
142
            foreach ($viewReferences as $viewReference) {
143
                if ($entity instanceof WebViewInterface && $viewReference instanceof ViewReference) {
144
                    $entity->setReference($viewReference, $viewReference->getLocale());
145
                    $entity->setUrl($viewReference->getUrl());
146
                } elseif ($entity instanceof BusinessTemplate) {
0 ignored issues
show
Bug introduced by
The class Victoire\Bundle\PageBund...criber\BusinessTemplate does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
147
                    $entity->setReferences([
148
                        $entity->getCurrentLocale() => $this->viewReferenceBuilder->buildViewReference($entity, $eventArgs->getEntityManager()),
149
                    ]);
150
                }
151
            }
152
        }
153
    }
154
}
155