Completed
Pull Request — master (#374)
by Leny
06:07
created

PageSubscriber::postLoad()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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