Completed
Push — refonte ( 2f5034...acd42b )
by Arnaud
02:23
created

AdminSubscriber::translateMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace LAG\AdminBundle\Event\Subscriber;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use LAG\AdminBundle\Configuration\AdminConfiguration;
7
use LAG\AdminBundle\Event\AdminEvent;
8
use LAG\AdminBundle\Event\AdminEvents;
9
use LAG\AdminBundle\Event\EntityEvent;
10
use LAG\AdminBundle\Event\MenuEvent;
11
use LAG\AdminBundle\Event\ViewEvent;
12
use LAG\AdminBundle\Exception\Exception;
13
use LAG\AdminBundle\Factory\ActionFactory;
14
use LAG\AdminBundle\Factory\DataProviderFactory;
15
use LAG\AdminBundle\Factory\ViewFactory;
16
use LAG\AdminBundle\LAGAdminBundle;
17
use LAG\AdminBundle\Utils\StringUtils;
18
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
19
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
20
use Symfony\Component\HttpFoundation\Session\Session;
21
use Symfony\Component\HttpFoundation\Session\SessionInterface;
22
use Symfony\Component\Translation\TranslatorInterface;
23
24
class AdminSubscriber implements EventSubscriberInterface
25
{
26
    /**
27
     * @var ActionFactory
28
     */
29
    private $actionFactory;
30
31
    /**
32
     * @var ViewFactory
33
     */
34
    private $viewFactory;
35
36
    /**
37
     * @var EventDispatcherInterface
38
     */
39
    private $eventDispatcher;
40
41
    /**
42
     * @var DataProviderFactory
43
     */
44
    private $dataProviderFactory;
45
46
    /**
47
     * @var Session
48
     */
49
    private $session;
50
51
    /**
52
     * @var TranslatorInterface
53
     */
54
    private $translator;
55
56
    /**
57
     * @return array
58
     */
59
    public static function getSubscribedEvents()
60
    {
61
        return [
62
            AdminEvents::HANDLE_REQUEST => 'handleRequest',
63
            AdminEvents::VIEW => 'createView',
64
            AdminEvents::ENTITY_LOAD => 'loadEntities',
65
            AdminEvents::ENTITY_SAVE => 'saveEntity',
66
        ];
67
    }
68
69
    /**
70
     * AdminSubscriber constructor.
71
     *
72
     * @param ActionFactory            $actionFactory
73
     * @param ViewFactory              $viewFactory
74
     * @param DataProviderFactory      $dataProviderFactory
75
     * @param EventDispatcherInterface $eventDispatcher
76
     * @param SessionInterface         $session
77
     * @param TranslatorInterface      $translator
78
     */
79
    public function __construct(
80
        ActionFactory $actionFactory,
81
        ViewFactory $viewFactory,
82
        DataProviderFactory $dataProviderFactory,
83
        EventDispatcherInterface $eventDispatcher,
84
        SessionInterface $session,
85
        TranslatorInterface $translator
86
    ) {
87
        $this->actionFactory = $actionFactory;
88
        $this->viewFactory = $viewFactory;
89
        $this->eventDispatcher = $eventDispatcher;
90
        $this->dataProviderFactory = $dataProviderFactory;
91
        $this->session = $session;
0 ignored issues
show
Documentation Bug introduced by
$session is of type object<Symfony\Component...ssion\SessionInterface>, but the property $session was declared to be of type object<Symfony\Component...dation\Session\Session>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
92
        $this->translator = $translator;
93
    }
94
95
    /**
96
     * Define the current action according to the routing configuration.
97
     *
98
     * @param AdminEvent $event
99
     *
100
     * @throws Exception
101
     */
102
    public function handleRequest(AdminEvent $event)
103
    {
104
        $actionName = $event->getRequest()->get('_action');
105
106
        if (null === $actionName) {
107
            throw new Exception('The _action was not found in the request');
108
        }
109
        $admin = $event->getAdmin();
110
        $action = $this->actionFactory->create($actionName, $admin->getName(), $admin->getConfiguration());
111
112
        $event->setAction($action);
113
    }
114
115
    /**
116
     * Create a view using the view factory.
117
     *
118
     * @param ViewEvent $event
119
     */
120
    public function createView(ViewEvent $event)
121
    {
122
        $admin = $event->getAdmin();
123
        $action = $admin->getAction();
124
        $menuEvent = new MenuEvent($admin->getAction()->getConfiguration()->getParameter('menus'));
125
        $this->eventDispatcher->dispatch(AdminEvents::MENU, $menuEvent);
126
127
        $view = $this->viewFactory->create(
128
            $event->getRequest(),
129
            $action->getName(),
130
            $admin->getName(),
131
            $admin->getConfiguration(),
132
            $action->getConfiguration(),
133
            $admin->getEntities(),
134
            $admin->getForms()
135
        );
136
137
        $event->setView($view);
138
    }
139
140
    /**
141
     * Load entities into the event data to pass them to the Admin.
142
     *
143
     * @param EntityEvent $event
144
     *
145
     * @throws Exception
146
     */
147
    public function loadEntities(EntityEvent $event)
148
    {
149
        $admin = $event->getAdmin();
150
        $configuration = $admin->getConfiguration();
151
        $actionConfiguration = $admin->getAction()->getConfiguration();
152
153
        $dataProvider = $this->dataProviderFactory->get($configuration->getParameter('data_provider'));
154
        $strategy = $actionConfiguration->getParameter('load_strategy');
155
        $class = $configuration->getParameter('entity');
156
157
        if (LAGAdminBundle::LOAD_STRATEGY_NONE === $strategy) {
158
            return;
159
        } else if (LAGAdminBundle::LOAD_STRATEGY_MULTIPLE === $strategy) {
160
            $entities = $dataProvider->getCollection($admin, $event->getFilters());
161
            $event->setEntities($entities);
162
        } else if (LAGAdminBundle::LOAD_STRATEGY_UNIQUE === $strategy) {
163
            $requirements = $actionConfiguration->getParameter('route_requirements');
164
            $identifier = null;
165
166
            foreach ($requirements as $name => $requirement) {
167
                if (null !== $event->getRequest()->get($name)) {
168
                    $identifier = $event->getRequest()->get($name);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $identifier is correct as $event->getRequest()->get($name) (which targets Symfony\Component\HttpFoundation\Request::get()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
169
                    break;
170
                }
171
            }
172
173
            if (null === $identifier) {
174
                throw new Exception('Unable to find a identifier for the class "'.$class.'"');
175
            }
176
            $entity = $dataProvider->getItem($admin, $identifier);
177
178
            $event->setEntities(new ArrayCollection([
179
                $entity,
180
            ]));
181
        }
182
183
    }
184
185
    /**
186
     * Save an entity.
187
     *
188
     * @param EntityEvent $event
189
     */
190
    public function saveEntity(EntityEvent $event)
191
    {
192
        $admin = $event->getAdmin();
193
        $configuration = $admin->getConfiguration();
194
195
        // Save the entity changes using the configured data provider
196
        $dataProvider = $this
197
            ->dataProviderFactory
198
            ->get($configuration->getParameter('data_provider'))
199
        ;
200
        $dataProvider->saveItem($admin);
201
202
        // Inform the user that the save is successful
203
        $this->translateMessage('save_success', $configuration);
204
205
        $this
206
            ->session
207
            ->getFlashBag()
208
            ->add('success', $this->translator->trans($message))
0 ignored issues
show
Bug introduced by
The variable $message does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
209
        ;
210
    }
211
212
    private function translateMessage(string $message, AdminConfiguration $configuration): string
213
    {
214
        $pattern = $configuration->get('translation_pattern');
215
        $message = StringUtils::getTranslationKey($pattern, $admin->getName(), $message);
0 ignored issues
show
Bug introduced by
The variable $admin does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Unused Code introduced by
$message is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
216
    }
217
}
218