Passed
Push — master ( 20daf2...ac8071 )
by Dev
14:31
created

PageAdmin   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 401
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 229
c 6
b 1
f 0
dl 0
loc 401
ccs 0
cts 322
cp 0
rs 8.8798
wmc 44

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setLiipImage() 0 3 1
A setDefaultLocale() 0 3 1
A getObjectMetadata() 0 11 3
A preUpdate() 0 3 1
B configureFormFieldsBlockDetails() 0 63 5
B configureDatagridFilters() 0 40 7
A configureListFields() 0 22 1
A configureFormFieldsBlockTitle() 0 34 3
A configureFormFieldHost() 0 11 2
A configureFormFieldsBlockImages() 0 31 2
A getHosts() 0 3 1
A exists() 0 3 1
A configureFormFieldOtherProperties() 0 11 2
A configueFormFieldTranslations() 0 15 2
A configureFormFields() 0 7 1
B configureFormFieldBlockParams() 0 47 9
A configureFormFieldsBlockContent() 0 23 1

How to fix   Complexity   

Complex Class

Complex classes like PageAdmin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PageAdmin, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PiedWeb\CMSBundle\Admin;
4
5
use Sonata\AdminBundle\Admin\AbstractAdmin;
6
use Sonata\AdminBundle\Datagrid\DatagridMapper;
7
use Sonata\AdminBundle\Datagrid\ListMapper;
8
use Sonata\AdminBundle\Form\FormMapper;
9
use Sonata\AdminBundle\Form\Type\ModelAutocompleteType;
10
use Sonata\BlockBundle\Meta\Metadata;
11
use Sonata\Form\Type\CollectionType;
12
use Sonata\Form\Type\DateTimePickerType;
13
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
14
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
15
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
16
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
17
use Symfony\Component\Form\Extension\Core\Type\TextType;
18
19
class PageAdmin extends AbstractAdmin
20
{
21
    use AdminTrait;
22
23
    protected $datagridValues = [
24
        '_page' => 1,
25
        '_sort_order' => 'DESC',
26
        '_sort_by' => 'updatedAt',
27
        '_per_page' => 256,
28
    ];
29
30
    protected $perPageOptions = [16, 250, 1000];
31
32
    protected $maxPerPage = 1000;
33
34
    protected $liipImage;
35
36
    protected $defaultLocale;
37
38
    public function __construct($code, $class, $baseControllerName)
39
    {
40
        parent::__construct($code, $class, $baseControllerName);
41
        $this->listModes['tree'] = [
42
            'class' => 'fa fa-sitemap',
43
        ];
44
    }
45
46
    public function setDefaultLocale($defaultLocale)
47
    {
48
        $this->defaultLocale = $defaultLocale;
49
    }
50
51
    public function setLiipImage($liipImage)
52
    {
53
        $this->liipImage = $liipImage;
54
    }
55
56
    /**
57
     * Check if page entity's item $name exist.
58
     */
59
    protected function exists(string $name): bool
60
    {
61
        return method_exists($this->getContainer()->getParameter('pwc.entity_page'), 'get'.$name);
62
    }
63
64
    protected function configureFormFieldsBlockDetails(FormMapper $formMapper): FormMapper
65
    {
66
        $formMapper->with('admin.details', ['class' => 'col-md-5']);
67
68
        if ($this->exists('parentPage')) {
69
            $formMapper->add('parentPage', EntityType::class, [
70
                'class' => $this->getContainer()->getParameter('pwc.entity_page'),
71
                'label' => 'admin.page.parentPage.label',
72
                'required' => false,
73
            ]);
74
        }
75
76
        $this->configueFormFieldTranslations($formMapper);
77
78
        $formMapper->add('createdAt', DateTimePickerType::class, [
79
            'format' => DateTimeType::HTML5_FORMAT,
80
            'dp_side_by_side' => true,
81
            'dp_use_current' => true,
82
            'dp_use_seconds' => false,
83
            'dp_collapse' => true,
84
            'dp_calendar_weeks' => false,
85
            'dp_view_mode' => 'days',
86
            'dp_min_view_mode' => 'days',
87
            'label' => 'admin.page.createdAt.label',
88
        ]);
89
90
        if ($this->exists('name')) {
91
            $formMapper->add('name', TextType::class, [
92
                'label' => 'admin.page.name.label',
93
                'required' => false,
94
                'help_html' => true,
95
                'help' => 'admin.page.name.help',
96
            ]);
97
        }
98
99
        if ($this->exists('excrept')) {
100
            $formMapper->add('excrept', TextareaType::class, [
101
                'required' => false,
102
                'label' => 'admin.page.excrept.label',
103
                'help_html' => true,
104
                'help' => 'admin.page.excrept.help',
105
            ]);
106
        }
107
108
        if ($this->exists('relatedPages')) {
109
            $formMapper->add('relatedPages', ModelAutocompleteType::class, [
110
                'required' => false,
111
                'multiple' => true,
112
                'class' => $this->getContainer()->getParameter('pwc.entity_page'),
113
                'property' => 'title', // or any field in your media entity
114
                'label' => 'admin.page.relatedPage.label',
115
                'btn_add' => false,
116
                'to_string_callback' => function ($entity) {
117
                    return $entity->getTitle();
118
                },
119
            ]);
120
        }
121
122
        $this->configureFormFieldOtherProperties($formMapper);
123
124
        $formMapper->end();
125
126
        return $formMapper;
127
    }
128
129
    protected function configureFormFieldsBlockContent(FormMapper $formMapper): FormMapper
130
    {
131
        $formMapper->with('admin.page.mainContent.label', ['class' => 'col-md-7']);
132
        $formMapper->add('mainContent', TextareaType::class, [
133
            'attr' => [
134
                'style' => 'min-height: 80vh;font-size:125%; max-width:900px',
135
                'data-editor' => 'markdown',
136
                'data-gutter' => 0,
137
            ],
138
            'required' => false,
139
            'label' => ' ',
140
            'help_html' => true,
141
            'help' => 'admin.page.mainContent.help',
142
        ]);
143
        $formMapper->add('mainContentIsMarkdown', null, [
144
            'required' => false,
145
            'label' => 'admin.page.markdown.label',
146
            'help_html' => true,
147
            'help' => 'admin.page.markdown.help',
148
        ]);
149
        $formMapper->end();
150
151
        return $formMapper;
152
    }
153
154
    public function configureFormFieldOtherProperties(FormMapper $formMapper): FormMapper
155
    {
156
        return !$this->exists('otherProperties') ? $formMapper : $formMapper->add('otherProperties', null, [
157
            'required' => false,
158
            'attr' => [
159
                'style' => 'min-height:15vh',
160
                'data-editor' => 'yaml',
161
            ],
162
            'label' => 'admin.page.otherProperties.label',
163
            'help_html' => true,
164
            'help' => 'admin.page.otherProperties.help',
165
        ]);
166
    }
167
168
    protected function getHosts()
169
    {
170
        return array_keys($this->getContainer()->getParameter('pwc.apps'));
171
    }
172
173
    public function configureFormFieldHost(FormMapper $formMapper): FormMapper
174
    {
175
        if (null === $this->getSubject()->getHost()) {
176
            $this->getSubject()->setHost($this->getHosts()[0]);
177
        }
178
179
        return $formMapper->add('host', ChoiceType::class, [
180
            'choices' => array_combine($this->getHosts(), $this->getHosts()),
181
            'required' => false,
182
            'label' => 'admin.page.host.label',
183
            'empty_data' => $this->getHosts()[0],
184
        ]);
185
    }
186
187
    public function configueFormFieldTranslations(FormMapper $formMapper): FormMapper
188
    {
189
        return $formMapper->add('translations', ModelAutocompleteType::class, [
190
            'required' => false,
191
            'multiple' => true,
192
            'class' => $this->getContainer()->getParameter('pwc.entity_page'),
193
            'property' => 'slug',
194
            'label' => 'admin.page.translations.label',
195
            'help_html' => true,
196
            'help' => 'admin.page.translations.help',
197
            'btn_add' => false,
198
            'to_string_callback' => function ($entity) {
199
                return $entity->getLocale()
200
                    ? $entity->getLocale().' ('.$entity->getSlug().')'
201
                    : $entity->getSlug(); // switch for getLocale
202
                // todo : remove it in next release and leave only get locale
203
                // todo : add a clickable link to the other admin
204
            },
205
        ]);
206
    }
207
208
    protected function configureFormFieldsBlockTitle(FormMapper $formMapper): FormMapper
209
    {
210
        $formMapper
211
            ->with('admin.page.title.label', ['class' => 'col-md-7']);
212
213
        $formMapper->add('title', TextType::class, [
214
            'label' => 'admin.page.title.label',
215
            'help_html' => true,
216
            'help' => 'admin.page.title.help',
217
            'attr' => ['class' => 'titleToMeasure'],
218
        ]);
219
220
        // Method existance is checked on each element to permit to use admin without all page Trait.
221
        if ($this->exists('H1')) {
222
            $formMapper->add('h1', TextType::class, [
223
                'required' => false,
224
                'attr' => ['class' => 'input-lg'],
225
                'label' => 'admin.page.h1.label',
226
                'help_html' => true,
227
                'help' => 'admin.page.h1.help',
228
            ]);
229
        }
230
231
        if ($this->exists('MainImage')) {
232
            $formMapper->add('mainImage', \Sonata\AdminBundle\Form\Type\ModelListType::class, [
233
                'required' => false,
234
                'class' => $this->getContainer()->getParameter('pwc.entity_media'),
235
                'label' => 'admin.page.mainImage.label',
236
                'btn_edit' => false,
237
            ]);
238
        }
239
        $formMapper->end();
240
241
        return $formMapper;
242
    }
243
244
    protected function configureFormFieldBlockParams(FormMapper $formMapper)
245
    {
246
        $formMapper->with('admin.page.params.label', ['class' => 'col-md-5']);
247
248
        $formMapper->add('slug', TextType::class, [
249
            'label' => 'admin.page.slug.label',
250
            'help_html' => true,
251
            'help' => $this->getSubject() && $this->getSubject()->getSlug()
252
                ? '<span class="btn btn-link" onclick="toggleDisabled()" id="disabledLinkSlug">
253
                    <i class="fa fa-unlock"></i></span>
254
                    <script>function toggleDisabled() {
255
                        $(".slug_disabled").first().removeAttr("disabled");
256
                        $(".slug_disabled").first().focus();
257
                        $("#disabledLinkSlug").first().remove();
258
                    }</script>'
259
                : 'admin.page.slug.help',
260
            'attr' => [
261
                'class' => 'slug_disabled',
262
                ($this->getSubject() ? ($this->getSubject()->getSlug() ? 'disabled' : 't') : 't') => '',
263
            ],
264
        ]);
265
266
        if ($this->exists('Host') && count($this->getHosts()) > 1) {
267
            $this->configureFormFieldHost($formMapper);
268
        }
269
270
        if ($this->exists('Locale')) {
271
            $formMapper->add('locale', TextType::class, [
272
                'label' => 'admin.page.locale.label',
273
                'help_html' => true,
274
                'help' => 'admin.page.locale.help',
275
            ]);
276
        }
277
278
        if ($this->exists('metaRobots')) {
279
            $formMapper->add('metaRobots', ChoiceType::class, [
280
                'choices' => [
281
                    'admin.page.metaRobots.choice.noIndex' => 'noindex',
282
                ],
283
                'label' => 'admin.page.metaRobots.label',
284
                'required' => false,
285
            ]);
286
        }
287
288
        $formMapper->end();
289
290
        return $formMapper;
291
    }
292
293
    protected function configureFormFieldsBlockImages(FormMapper $formMapper): FormMapper
294
    {
295
        if ($this->exists('images')) {
296
            $formMapper->with('admin.page.images.label', ['class' => 'col-md-5']);
297
            $formMapper->add(
298
                'pageHasMedias',
299
                CollectionType::class,
300
                [
301
                    'by_reference' => false,
302
                    'required' => false,
303
                    'label' => ' ',
304
                    'type_options' => [
305
                        'delete' => true,
306
                    ],
307
                ],
308
                [
309
                    'allow_add' => false,
310
                    'allow_delete' => true,
311
                    'btn_add' => false,
312
                    'btn_catalogue' => false,
313
                    'edit' => 'inline',
314
                    'inline' => 'table',
315
                    'sortable' => 'position',
316
                    //'link_parameters' => ['context' => $context],
317
                    'admin_code' => 'piedweb.admin.pagehasmedia',
318
                ]
319
            );
320
            $formMapper->end();
321
        }
322
323
        return $formMapper;
324
    }
325
326
    protected function configureFormFields(FormMapper $formMapper)
327
    {
328
        $this->configureFormFieldsBlockTitle($formMapper);
329
        $this->configureFormFieldBlockParams($formMapper);
330
        $this->configureFormFieldsBlockContent($formMapper);
331
        $this->configureFormFieldsBlockDetails($formMapper);
332
        $this->configureFormFieldsBlockImages($formMapper);
333
    }
334
335
    protected function configureDatagridFilters(DatagridMapper $formMapper)
336
    {
337
        $formMapper->add('locale', null, ['label' => 'admin.page.locale.label']);
338
339
        if (count($this->getHosts()) > 1) {
340
            $formMapper->add('host', null, ['label' => 'admin.page.host.label']);
341
        }
342
343
        $formMapper->add('slug', null, ['label' => 'admin.page.slug.label']);
344
345
        $formMapper->add('title', null, ['label' => 'admin.page.title.label']);
346
347
        if ($this->exists('H1')) {
348
            $formMapper->add('h1', null, ['label' => 'admin.page.h1.label']);
349
        }
350
351
        $formMapper->add('mainContent', null, ['label' => 'admin.page.mainContent.label']);
352
353
        if ($this->exists('name')) {
354
            $formMapper->add('name', null, ['label' => 'admin.page.name.label']);
355
        }
356
357
        if ($this->exists('parentPage')) {
358
            $formMapper->add('parentPage', null, ['label' => 'admin.page.parentPage.label']);
359
        }
360
361
        if ($this->exists('metaRobots')) {
362
            $formMapper->add('metaRobots', null, [
363
                'choices' => [
364
                    'admin.page.metaRobots.choice.noIndex' => 'noindex',
365
                ],
366
                'label' => 'admin.page.metaRobots.label',
367
            ]);
368
        }
369
370
        if ($this->exists('author')) {
371
            $formMapper->add('author', null, [
372
                'label' => 'admin.page.author.label',
373
                'class' => $this->getContainer()->getParameter('pwc.entity_user'),
374
                'required' => false,
375
            ]);
376
        }
377
    }
378
379
    public function preUpdate($page)
380
    {
381
        $page->setUpdatedAt(new \Datetime());
382
    }
383
384
    protected function configureListFields(ListMapper $listMapper)
385
    {
386
        $listMapper->addIdentifier('title', 'html', [
387
            'label' => 'admin.page.title.label',
388
            'template' => '@PiedWebCMS/admin/base_list_field.html.twig',
389
        ]);
390
        $listMapper->add('updatedAt', null, [
391
            'format' => 'd/m à H:m',
392
            'label' => 'admin.page.updatedAt.label',
393
        ]);
394
        $listMapper->add('createdAt', null, [
395
            'format' => 'd/m/y',
396
            'label' => 'admin.page.createdAt.label',
397
        ]);
398
        $listMapper->add('_action', null, [
399
            'actions' => [
400
                'show' => [],
401
                'delete' => [],
402
            ],
403
            'row_align' => 'right',
404
            'header_class' => 'text-right',
405
            'label' => 'admin.action',
406
        ]);
407
    }
408
409
    public function getObjectMetadata($page)
410
    {
411
        $media = $page->getMainImage();
412
        if (null !== $media && false !== strpos($media->getMimeType(), 'image/')) {
413
            $fullPath = '/'.$media->getRelativeDir().'/'.$media->getMedia();
414
            $thumb = $this->liipImage->getBrowserPath($fullPath, 'thumb');
415
        } else {
416
            $thumb = self::$thumb;
417
        }
418
419
        return new Metadata($page->getTitle(), null, $thumb);
420
    }
421
}
422