Completed
Pull Request — dev (#19)
by Arnaud
02:52
created

ExtraConfigurationSubscriber   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 29.63%

Importance

Changes 15
Bugs 5 Features 3
Metric Value
wmc 18
c 15
b 5
f 3
lcom 1
cbo 11
dl 0
loc 167
ccs 24
cts 81
cp 0.2963
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 7 1
A __construct() 0 10 1
A adminCreate() 0 19 4
C actionCreate() 0 87 12
1
<?php
2
3
namespace LAG\AdminBundle\Event\Subscriber;
4
5
use Doctrine\Bundle\DoctrineBundle\Registry;
6
use Doctrine\Common\Persistence\Mapping\MappingException;
7
use Doctrine\ORM\EntityManager;
8
use LAG\AdminBundle\Admin\Behaviors\TranslationKeyTrait;
9
use LAG\AdminBundle\Application\Configuration\ApplicationConfiguration;
10
use LAG\AdminBundle\Configuration\Factory\ConfigurationFactory;
11
use LAG\AdminBundle\Event\AdminEvent;
12
use LAG\AdminBundle\Utils\FieldTypeGuesser;
13
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
14
15
/**
16
 * Add extra default configuration for actions and fields. Bind to ADMIN_CREATE and ACTION_CREATE events
17
 */
18
class ExtraConfigurationSubscriber implements EventSubscriberInterface
19
{
20
    use TranslationKeyTrait;
21
22
    /**
23
     * @var bool
24
     */
25
    protected $enableExtraConfiguration;
26
27
    /**
28
     * @var EntityManager
29
     */
30
    protected $entityManager;
31
32
    /**
33
     * @var ApplicationConfiguration
34
     */
35
    protected $applicationConfiguration;
36
37
    /**
38
     * @return array
39
     */
40 1
    public static function getSubscribedEvents()
41
    {
42
        return [
43 1
            AdminEvent::ADMIN_CREATE => 'adminCreate',
44 1
            AdminEvent::ACTION_CREATE => 'actionCreate',
45 1
        ];
46
    }
47
48
    /**
49
     * ExtraConfigurationSubscriber constructor
50
     *
51
     * @param bool $enableExtraConfiguration
52
     * @param Registry $doctrine
53
     * @param ConfigurationFactory $configurationFactory
54
     */
55 1
    public function __construct(
56
        $enableExtraConfiguration = true,
57
        Registry $doctrine,
58
        ConfigurationFactory $configurationFactory
59
    ) {
60 1
        $this->enableExtraConfiguration = $enableExtraConfiguration;
61
        // entity manager can be closed. Scrutinizer recommands to inject registry instead
62 1
        $this->entityManager = $doctrine->getManager();
63 1
        $this->applicationConfiguration = $configurationFactory->getApplicationConfiguration();
64 1
    }
65
66
    /**
67
     * Adding default CRUD if none is defined
68
     *
69
     * @param AdminEvent $event
70
     */
71 1
    public function adminCreate(AdminEvent $event)
72
    {
73 1
        if (!$this->enableExtraConfiguration) {
74 1
            return;
75
        }
76 1
        $configuration = $event->getConfiguration();
77
78
        // if no actions are defined, we set default CRUD action
79 1
        if (!array_key_exists('actions', $configuration) || !count($configuration['actions'])) {
80 1
            $configuration['actions'] = [
81 1
                'create' => [],
82 1
                'list' => [],
83 1
                'edit' => [],
84 1
                'delete' => [],
85 1
                'batch' => []
86 1
            ];
87 1
            $event->setConfiguration($configuration);
88 1
        }
89 1
    }
90
91
    /**
92
     * Add default linked actions and default menu actions
93
     *
94
     * @param AdminEvent $event
95
     * @throws MappingException
96
     */
97
    public function actionCreate(AdminEvent $event)
98
    {
99
        // add configuration only if extra configuration is enabled
100
        if (!$this->enableExtraConfiguration) {
101
            return;
102
        }
103
        // action configuration array
104
        $configuration = $event->getConfiguration();
105
        // current action admin
106
        $admin = $event->getAdmin();
107
        // allowed actions according to the admin
108
        $keys = $admin
109
            ->getConfiguration()
110
            ->getParameter('actions');
111
        $allowedActions = array_keys($keys);
112
113
        // if no field was provided in configuration, we try to take fields from doctrine metadata
114
        if (empty($configuration['fields']) || !count($configuration['fields'])) {
115
            $fields = [];
116
            $guesser = new FieldTypeGuesser();
117
            $metadata = $this
118
                ->entityManager
119
                ->getMetadataFactory()
120
                ->getMetadataFor($admin->getConfiguration()->getParameter('entity'));
121
            $fieldsName = $metadata->getFieldNames();
122
123
            foreach ($fieldsName as $name) {
124
                $type = $metadata->getTypeOfField($name);
125
                // get field type from doctrine type
126
                $fieldConfiguration = $guesser->getTypeAndOptions($type);
127
128
                // if a field configuration was found, we take it
129
                if (count($fieldConfiguration)) {
130
                    $fields[$name] = $fieldConfiguration;
131
                }
132
            }
133
            if (count($fields)) {
134
                // adding new fields to action configuration
135
                $configuration['fields'] = $fields;
136
            }
137
        }
138
        // configured linked actions
139
        if (array_key_exists('_actions', $configuration['fields'])
140
            && $configuration['fields']['_actions'] === null
141
        ) {
142
            // in list view, we add by default and an edit and a delete button
143
            if ($event->getActionName() == 'list') {
144
145
                $translationPattern = $this
146
                    ->applicationConfiguration
147
                    ->getParameter('translation')['pattern']
148
                ;
149
                
150
                
151
                if (in_array('edit', $allowedActions)) {
152
                    $configuration['fields']['_actions']['type'] = 'collection';
153
                    $configuration['fields']['_actions']['options']['_edit'] = [
154
                        'type' => 'action',
155
                        'options' => [
156
                            'title' => $this->getTranslationKey($translationPattern, 'edit', $event->getAdmin()->getName()),
157
                            'route' => $admin->generateRouteName('edit'),
158
                            'parameters' => [
159
                                'id' => false
160
                            ],
161
                            'icon' => 'pencil'
162
                        ]
163
                    ];
164
                }
165
                if (in_array('delete', $allowedActions)) {
166
                    $configuration['fields']['_actions']['type'] = 'collection';
167
                    $configuration['fields']['_actions']['options']['_delete'] = [
168
                        'type' => 'action',
169
                        'options' => [
170
                            'title' => $this->getTranslationKey($translationPattern, 'delete', $event->getAdmin()->getName()),
171
                            'route' => $admin->generateRouteName('delete'),
172
                            'parameters' => [
173
                                'id' => false
174
                            ],
175
                            'icon' => 'remove'
176
                        ]
177
                    ];
178
                }
179
            }
180
        }
181
        // reset action configuration
182
        $event->setConfiguration($configuration);
183
    }
184
}
185