Completed
Push — 3.x ( 31e7c2...dbd908 )
by Jordi Sala
03:57
created

AbstractAdmin::createObjectSecurity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\AdminBundle\Admin;
15
16
use Doctrine\Common\Util\ClassUtils;
17
use Knp\Menu\FactoryInterface;
18
use Knp\Menu\ItemInterface;
19
use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
20
use Sonata\AdminBundle\Builder\FormContractorInterface;
21
use Sonata\AdminBundle\Builder\ListBuilderInterface;
22
use Sonata\AdminBundle\Builder\RouteBuilderInterface;
23
use Sonata\AdminBundle\Builder\ShowBuilderInterface;
24
use Sonata\AdminBundle\Datagrid\DatagridInterface;
25
use Sonata\AdminBundle\Datagrid\DatagridMapper;
26
use Sonata\AdminBundle\Datagrid\ListMapper;
27
use Sonata\AdminBundle\Datagrid\Pager;
28
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
29
use Sonata\AdminBundle\Filter\Persister\FilterPersisterInterface;
30
use Sonata\AdminBundle\Form\FormMapper;
31
use Sonata\AdminBundle\Form\Type\ModelHiddenType;
32
use Sonata\AdminBundle\Manipulator\ObjectManipulator;
33
use Sonata\AdminBundle\Model\ModelManagerInterface;
34
use Sonata\AdminBundle\Object\Metadata;
35
use Sonata\AdminBundle\Route\RouteCollection;
36
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
37
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
38
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
39
use Sonata\AdminBundle\Show\ShowMapper;
40
use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface;
41
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
42
use Sonata\Form\Validator\Constraints\InlineConstraint;
43
use Sonata\Form\Validator\ErrorElement;
44
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
45
use Symfony\Component\Form\Form;
46
use Symfony\Component\Form\FormBuilderInterface;
47
use Symfony\Component\Form\FormEvent;
48
use Symfony\Component\Form\FormEvents;
49
use Symfony\Component\HttpFoundation\Request;
50
use Symfony\Component\PropertyAccess\PropertyPath;
51
use Symfony\Component\Routing\Generator\UrlGeneratorInterface as RoutingUrlGeneratorInterface;
52
use Symfony\Component\Security\Acl\Model\DomainObjectInterface;
53
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
54
use Symfony\Component\Translation\TranslatorInterface;
55
use Symfony\Component\Validator\Mapping\GenericMetadata;
56
use Symfony\Component\Validator\Validator\ValidatorInterface;
57
58
/**
59
 * @author Thomas Rabaix <[email protected]>
60
 */
61
abstract class AbstractAdmin implements AdminInterface, DomainObjectInterface, AdminTreeInterface
62
{
63
    public const CONTEXT_MENU = 'menu';
64
    public const CONTEXT_DASHBOARD = 'dashboard';
65
66
    public const CLASS_REGEX =
67
        '@
68
        (?:([A-Za-z0-9]*)\\\)?        # vendor name / app name
69
        (Bundle\\\)?                  # optional bundle directory
70
        ([A-Za-z0-9]+?)(?:Bundle)?\\\ # bundle name, with optional suffix
71
        (
72
            Entity|Document|Model|PHPCR|CouchDocument|Phpcr|
73
            Doctrine\\\Orm|Doctrine\\\Phpcr|Doctrine\\\MongoDB|Doctrine\\\CouchDB
74
        )\\\(.*)@x';
75
76
    public const MOSAIC_ICON_CLASS = 'fa fa-th-large fa-fw';
77
78
    /**
79
     * The list FieldDescription constructed from the configureListField method.
80
     *
81
     * @var FieldDescriptionInterface[]
82
     */
83
    protected $listFieldDescriptions = [];
84
85
    /**
86
     * The show FieldDescription constructed from the configureShowFields method.
87
     *
88
     * @var FieldDescriptionInterface[]
89
     */
90
    protected $showFieldDescriptions = [];
91
92
    /**
93
     * The list FieldDescription constructed from the configureFormField method.
94
     *
95
     * @var FieldDescriptionInterface[]
96
     */
97
    protected $formFieldDescriptions = [];
98
99
    /**
100
     * The filter FieldDescription constructed from the configureFilterField method.
101
     *
102
     * @var FieldDescriptionInterface[]
103
     */
104
    protected $filterFieldDescriptions = [];
105
106
    /**
107
     * NEXT_MAJOR: Remove this property.
108
     *
109
     * The number of result to display in the list.
110
     *
111
     * @deprecated since sonata-project/admin-bundle 3.67.
112
     *
113
     * @var int
114
     */
115
    protected $maxPerPage = 32;
116
117
    /**
118
     * The maximum number of page numbers to display in the list.
119
     *
120
     * @var int
121
     */
122
    protected $maxPageLinks = 25;
123
124
    /**
125
     * The base route name used to generate the routing information.
126
     *
127
     * @var string
128
     */
129
    protected $baseRouteName;
130
131
    /**
132
     * The base route pattern used to generate the routing information.
133
     *
134
     * @var string
135
     */
136
    protected $baseRoutePattern;
137
138
    /**
139
     * The base name controller used to generate the routing information.
140
     *
141
     * @var string
142
     */
143
    protected $baseControllerName;
144
145
    /**
146
     * The label class name  (used in the title/breadcrumb ...).
147
     *
148
     * @var string
149
     */
150
    protected $classnameLabel;
151
152
    /**
153
     * The translation domain to be used to translate messages.
154
     *
155
     * @var string
156
     */
157
    protected $translationDomain = 'messages';
158
159
    /**
160
     * Options to set to the form (ie, validation_groups).
161
     *
162
     * @var array
163
     */
164
    protected $formOptions = [];
165
166
    /**
167
     * NEXT_MAJOR: Remove this property.
168
     *
169
     * Default values to the datagrid.
170
     *
171
     * @deprecated since sonata-project/admin-bundle 3.67, use configureDefaultSortValues() instead.
172
     *
173
     * @var array
174
     */
175
    protected $datagridValues = [
176
        '_page' => 1,
177
        '_per_page' => 32,
178
    ];
179
180
    /**
181
     * NEXT_MAJOR: Remove this property.
182
     *
183
     * Predefined per page options.
184
     *
185
     * @deprecated since sonata-project/admin-bundle 3.67.
186
     *
187
     * @var array
188
     */
189
    protected $perPageOptions = [16, 32, 64, 128, 256];
190
191
    /**
192
     * Pager type.
193
     *
194
     * @var string
195
     */
196
    protected $pagerType = Pager::TYPE_DEFAULT;
197
198
    /**
199
     * The code related to the admin.
200
     *
201
     * @var string
202
     */
203
    protected $code;
204
205
    /**
206
     * The label.
207
     *
208
     * @var string
209
     */
210
    protected $label;
211
212
    /**
213
     * Whether or not to persist the filters in the session.
214
     *
215
     * NEXT_MAJOR: remove this property
216
     *
217
     * @var bool
218
     *
219
     * @deprecated since sonata-project/admin-bundle 3.34, to be removed in 4.0.
220
     */
221
    protected $persistFilters = false;
222
223
    /**
224
     * Array of routes related to this admin.
225
     *
226
     * @var RouteCollection
227
     */
228
    protected $routes;
229
230
    /**
231
     * The subject only set in edit/update/create mode.
232
     *
233
     * @var object|null
234
     */
235
    protected $subject;
236
237
    /**
238
     * Define a Collection of child admin, ie /admin/order/{id}/order-element/{childId}.
239
     *
240
     * @var array
241
     */
242
    protected $children = [];
243
244
    /**
245
     * Reference the parent admin.
246
     *
247
     * @var AdminInterface|null
248
     */
249
    protected $parent;
250
251
    /**
252
     * The base code route refer to the prefix used to generate the route name.
253
     *
254
     * NEXT_MAJOR: remove this attribute.
255
     *
256
     * @deprecated This attribute is deprecated since sonata-project/admin-bundle 3.24 and will be removed in 4.0
257
     *
258
     * @var string
259
     */
260
    protected $baseCodeRoute = '';
261
262
    /**
263
     * NEXT_MAJOR: should be default array and private.
264
     *
265
     * @var string|array
266
     */
267
    protected $parentAssociationMapping;
268
269
    /**
270
     * Reference the parent FieldDescription related to this admin
271
     * only set for FieldDescription which is associated to an Sub Admin instance.
272
     *
273
     * @var FieldDescriptionInterface
274
     */
275
    protected $parentFieldDescription;
276
277
    /**
278
     * If true then the current admin is part of the nested admin set (from the url).
279
     *
280
     * @var bool
281
     */
282
    protected $currentChild = false;
283
284
    /**
285
     * The uniqid is used to avoid clashing with 2 admin related to the code
286
     * ie: a Block linked to a Block.
287
     *
288
     * @var string
289
     */
290
    protected $uniqid;
291
292
    /**
293
     * The Entity or Document manager.
294
     *
295
     * @var ModelManagerInterface
296
     */
297
    protected $modelManager;
298
299
    /**
300
     * The current request object.
301
     *
302
     * @var Request|null
303
     */
304
    protected $request;
305
306
    /**
307
     * The translator component.
308
     *
309
     * NEXT_MAJOR: remove this property
310
     *
311
     * @var \Symfony\Component\Translation\TranslatorInterface
312
     *
313
     * @deprecated since sonata-project/admin-bundle 3.9, to be removed with 4.0
314
     */
315
    protected $translator;
316
317
    /**
318
     * The related form contractor.
319
     *
320
     * @var FormContractorInterface
321
     */
322
    protected $formContractor;
323
324
    /**
325
     * The related list builder.
326
     *
327
     * @var ListBuilderInterface
328
     */
329
    protected $listBuilder;
330
331
    /**
332
     * The related view builder.
333
     *
334
     * @var ShowBuilderInterface
335
     */
336
    protected $showBuilder;
337
338
    /**
339
     * The related datagrid builder.
340
     *
341
     * @var DatagridBuilderInterface
342
     */
343
    protected $datagridBuilder;
344
345
    /**
346
     * @var RouteBuilderInterface
347
     */
348
    protected $routeBuilder;
349
350
    /**
351
     * The datagrid instance.
352
     *
353
     * @var DatagridInterface|null
354
     */
355
    protected $datagrid;
356
357
    /**
358
     * The router instance.
359
     *
360
     * @var RouteGeneratorInterface|null
361
     */
362
    protected $routeGenerator;
363
364
    /**
365
     * The generated breadcrumbs.
366
     *
367
     * NEXT_MAJOR : remove this property
368
     *
369
     * @var array
370
     */
371
    protected $breadcrumbs = [];
372
373
    /**
374
     * @var SecurityHandlerInterface
375
     */
376
    protected $securityHandler;
377
378
    /**
379
     * @var ValidatorInterface
380
     */
381
    protected $validator;
382
383
    /**
384
     * The configuration pool.
385
     *
386
     * @var Pool
387
     */
388
    protected $configurationPool;
389
390
    /**
391
     * @var ItemInterface
392
     */
393
    protected $menu;
394
395
    /**
396
     * @var FactoryInterface
397
     */
398
    protected $menuFactory;
399
400
    /**
401
     * @var array<string, bool>
402
     */
403
    protected $loaded = [
404
        'view_fields' => false, // NEXT_MAJOR: Remove this unused value.
405
        'view_groups' => false, // NEXT_MAJOR: Remove this unused value.
406
        'routes' => false,
407
        'tab_menu' => false,
408
        'show' => false,
409
        'list' => false,
410
        'form' => false,
411
        'datagrid' => false,
412
    ];
413
414
    /**
415
     * @var string[]
416
     */
417
    protected $formTheme = [];
418
419
    /**
420
     * @var string[]
421
     */
422
    protected $filterTheme = [];
423
424
    /**
425
     * @var array<string, string>
426
     *
427
     * @deprecated since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead
428
     */
429
    protected $templates = [];
430
431
    /**
432
     * @var AdminExtensionInterface[]
433
     */
434
    protected $extensions = [];
435
436
    /**
437
     * @var LabelTranslatorStrategyInterface
438
     */
439
    protected $labelTranslatorStrategy;
440
441
    /**
442
     * Setting to true will enable preview mode for
443
     * the entity and show a preview button in the
444
     * edit/create forms.
445
     *
446
     * @var bool
447
     */
448
    protected $supportsPreviewMode = false;
449
450
    /**
451
     * Roles and permissions per role.
452
     *
453
     * @var array 'role' => ['permission', 'permission']
454
     */
455
    protected $securityInformation = [];
456
457
    protected $cacheIsGranted = [];
458
459
    /**
460
     * Action list for the search result.
461
     *
462
     * @var string[]
463
     */
464
    protected $searchResultActions = ['edit', 'show'];
465
466
    protected $listModes = [
467
        'list' => [
468
            'class' => 'fa fa-list fa-fw',
469
        ],
470
        'mosaic' => [
471
            'class' => self::MOSAIC_ICON_CLASS,
472
        ],
473
    ];
474
475
    /**
476
     * The Access mapping.
477
     *
478
     * @var array [action1 => requiredRole1, action2 => [requiredRole2, requiredRole3]]
479
     */
480
    protected $accessMapping = [];
481
482
    /**
483
     * @var MutableTemplateRegistryInterface
484
     */
485
    private $templateRegistry;
486
487
    /**
488
     * The class name managed by the admin class.
489
     *
490
     * @var string
491
     */
492
    private $class;
493
494
    /**
495
     * The subclasses supported by the admin class.
496
     *
497
     * @var array<string, string>
498
     */
499
    private $subClasses = [];
500
501
    /**
502
     * The list collection.
503
     *
504
     * @var FieldDescriptionCollection|null
505
     */
506
    private $list;
507
508
    /**
509
     * @var FieldDescriptionCollection|null
510
     */
511
    private $show;
512
513
    /**
514
     * @var Form|null
515
     */
516
    private $form;
517
518
    /**
519
     * The cached base route name.
520
     *
521
     * @var string
522
     */
523
    private $cachedBaseRouteName;
524
525
    /**
526
     * The cached base route pattern.
527
     *
528
     * @var string
529
     */
530
    private $cachedBaseRoutePattern;
531
532
    /**
533
     * The form group disposition.
534
     *
535
     * NEXT_MAJOR: must have `[]` as default value and remove the possibility to
536
     * hold boolean values.
537
     *
538
     * @var array|bool
539
     */
540
    private $formGroups = false;
541
542
    /**
543
     * The form tabs disposition.
544
     *
545
     * NEXT_MAJOR: must have `[]` as default value and remove the possibility to
546
     * hold boolean values.
547
     *
548
     * @var array|bool
549
     */
550
    private $formTabs = false;
551
552
    /**
553
     * The view group disposition.
554
     *
555
     * NEXT_MAJOR: must have `[]` as default value and remove the possibility to
556
     * hold boolean values.
557
     *
558
     * @var array|bool
559
     */
560
    private $showGroups = false;
561
562
    /**
563
     * The view tab disposition.
564
     *
565
     * NEXT_MAJOR: must have `[]` as default value and remove the possibility to
566
     * hold boolean values.
567
     *
568
     * @var array|bool
569
     */
570
    private $showTabs = false;
571
572
    /**
573
     * The manager type to use for the admin.
574
     *
575
     * @var string
576
     */
577
    private $managerType;
578
579
    /**
580
     * The breadcrumbsBuilder component.
581
     *
582
     * @var BreadcrumbsBuilderInterface
583
     */
584
    private $breadcrumbsBuilder;
585
586
    /**
587
     * Component responsible for persisting filters.
588
     *
589
     * @var FilterPersisterInterface|null
590
     */
591
    private $filterPersister;
592
593
    /**
594
     * @param string      $code
595
     * @param string      $class
596
     * @param string|null $baseControllerName
597
     */
598
    public function __construct($code, $class, $baseControllerName = null)
599
    {
600
        if (!\is_string($code)) {
601
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
602
                'Passing other type than string as argument 1 for method %s() is deprecated since'
603
                .' sonata-project/admin-bundle 3.65. It will accept only string in version 4.0.',
604
                __METHOD__
605
            ), E_USER_DEPRECATED);
606
        }
607
        $this->code = $code;
608
        if (!\is_string($class)) {
609
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
610
                'Passing other type than string as argument 2 for method %s() is deprecated since'
611
                .' sonata-project/admin-bundle 3.65. It will accept only string in version 4.0.',
612
                __METHOD__
613
            ), E_USER_DEPRECATED);
614
        }
615
        $this->class = $class;
616
        if (null !== $baseControllerName && !\is_string($baseControllerName)) {
617
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
618
                'Passing other type than string or null as argument 3 for method %s() is deprecated since'
619
                .' sonata-project/admin-bundle 3.65. It will accept only string and null in version 4.0.',
620
                __METHOD__
621
            ), E_USER_DEPRECATED);
622
        }
623
        $this->baseControllerName = $baseControllerName;
624
625
        // NEXT_MAJOR: Remove this line.
626
        $this->predefinePerPageOptions();
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...edefinePerPageOptions() has been deprecated with message: since sonata-project/admin-bundle 3.67, to be removed in 4.0. Predefine per page options.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
627
628
        // NEXT_MAJOR: Remove this line.
629
        $this->datagridValues['_per_page'] = $this->maxPerPage;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$datagridValues has been deprecated with message: since sonata-project/admin-bundle 3.67, use configureDefaultSortValues() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$maxPerPage has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
630
    }
631
632
    /**
633
     * {@inheritdoc}
634
     */
635
    public function getExportFormats()
636
    {
637
        return [
638
            'json', 'xml', 'csv', 'xls',
639
        ];
640
    }
641
642
    /**
643
     * @return array
644
     */
645
    public function getExportFields()
646
    {
647
        $fields = $this->getModelManager()->getExportFields($this->getClass());
648
649
        foreach ($this->getExtensions() as $extension) {
650
            if (method_exists($extension, 'configureExportFields')) {
651
                $fields = $extension->configureExportFields($this, $fields);
652
            }
653
        }
654
655
        return $fields;
656
    }
657
658
    public function getDataSourceIterator()
659
    {
660
        $datagrid = $this->getDatagrid();
661
        $datagrid->buildPager();
662
663
        $fields = [];
664
665
        foreach ($this->getExportFields() as $key => $field) {
666
            $label = $this->getTranslationLabel($field, 'export', 'label');
667
            $transLabel = $this->trans($label);
668
669
            // NEXT_MAJOR: Remove this hack, because all field labels will be translated with the major release
670
            // No translation key exists
671
            if ($transLabel === $label) {
672
                $fields[$key] = $field;
673
            } else {
674
                $fields[$transLabel] = $field;
675
            }
676
        }
677
678
        return $this->getModelManager()->getDataSourceIterator($datagrid, $fields);
0 ignored issues
show
Bug introduced by
It seems like $datagrid defined by $this->getDatagrid() on line 660 can be null; however, Sonata\AdminBundle\Model...getDataSourceIterator() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
679
    }
680
681
    public function validate(ErrorElement $errorElement, $object)
682
    {
683
    }
684
685
    /**
686
     * define custom variable.
687
     */
688
    public function initialize()
689
    {
690
        if (!$this->classnameLabel) {
691
            /* NEXT_MAJOR: remove cast to string, null is not supposed to be
692
            supported but was documented as such */
693
            $this->classnameLabel = substr(
694
                (string) $this->getClass(),
695
                strrpos((string) $this->getClass(), '\\') + 1
696
            );
697
        }
698
699
        // NEXT_MAJOR: Remove this line.
700
        $this->baseCodeRoute = $this->getCode();
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...ctAdmin::$baseCodeRoute has been deprecated with message: This attribute is deprecated since sonata-project/admin-bundle 3.24 and will be removed in 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
701
702
        $this->configure();
703
    }
704
705
    public function configure()
706
    {
707
    }
708
709
    public function update($object)
710
    {
711
        $this->preUpdate($object);
712
        foreach ($this->extensions as $extension) {
713
            $extension->preUpdate($this, $object);
714
        }
715
716
        $result = $this->getModelManager()->update($object);
717
        // BC compatibility
718
        if (null !== $result) {
719
            $object = $result;
720
        }
721
722
        $this->postUpdate($object);
723
        foreach ($this->extensions as $extension) {
724
            $extension->postUpdate($this, $object);
725
        }
726
727
        return $object;
728
    }
729
730
    public function create($object)
731
    {
732
        $this->prePersist($object);
733
        foreach ($this->extensions as $extension) {
734
            $extension->prePersist($this, $object);
735
        }
736
737
        $result = $this->getModelManager()->create($object);
738
        // BC compatibility
739
        if (null !== $result) {
740
            $object = $result;
741
        }
742
743
        $this->postPersist($object);
744
        foreach ($this->extensions as $extension) {
745
            $extension->postPersist($this, $object);
746
        }
747
748
        $this->createObjectSecurity($object);
749
750
        return $object;
751
    }
752
753
    public function delete($object)
754
    {
755
        $this->preRemove($object);
756
        foreach ($this->extensions as $extension) {
757
            $extension->preRemove($this, $object);
758
        }
759
760
        $this->getSecurityHandler()->deleteObjectSecurity($this, $object);
761
        $this->getModelManager()->delete($object);
762
763
        $this->postRemove($object);
764
        foreach ($this->extensions as $extension) {
765
            $extension->postRemove($this, $object);
766
        }
767
    }
768
769
    /**
770
     * @param object $object
771
     */
772
    public function preValidate($object)
0 ignored issues
show
Unused Code introduced by
The parameter $object is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
773
    {
774
    }
775
776
    public function preUpdate($object)
777
    {
778
    }
779
780
    public function postUpdate($object)
781
    {
782
    }
783
784
    public function prePersist($object)
785
    {
786
    }
787
788
    public function postPersist($object)
789
    {
790
    }
791
792
    public function preRemove($object)
793
    {
794
    }
795
796
    public function postRemove($object)
797
    {
798
    }
799
800
    public function preBatchAction($actionName, ProxyQueryInterface $query, array &$idx, $allElements)
801
    {
802
    }
803
804
    public function getFilterParameters()
805
    {
806
        $parameters = [];
807
808
        // build the values array
809
        if ($this->hasRequest()) {
810
            $filters = $this->request->query->get('filter', []);
811
            if (isset($filters['_page'])) {
812
                $filters['_page'] = (int) $filters['_page'];
813
            }
814
            if (isset($filters['_per_page'])) {
815
                $filters['_per_page'] = (int) $filters['_per_page'];
816
            }
817
818
            // if filter persistence is configured
819
            // NEXT_MAJOR: remove `$this->persistFilters !== false` from the condition
820
            if (false !== $this->persistFilters && null !== $this->filterPersister) {
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$persistFilters has been deprecated with message: since sonata-project/admin-bundle 3.34, to be removed in 4.0.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
821
                // if reset filters is asked, remove from storage
822
                if ('reset' === $this->request->query->get('filters')) {
823
                    $this->filterPersister->reset($this->getCode());
824
                }
825
826
                // if no filters, fetch from storage
827
                // otherwise save to storage
828
                if (empty($filters)) {
829
                    $filters = $this->filterPersister->get($this->getCode());
830
                } else {
831
                    $this->filterPersister->set($this->getCode(), $filters);
832
                }
833
            }
834
835
            $parameters = array_merge(
836
                $this->getModelManager()->getDefaultSortValues($this->getClass()),
837
                $this->datagridValues, // NEXT_MAJOR: Remove this line.
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$datagridValues has been deprecated with message: since sonata-project/admin-bundle 3.67, use configureDefaultSortValues() instead.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
838
                $this->getDefaultSortValues(),
839
                $this->getDefaultFilterValues(),
840
                $filters
841
            );
842
843
            if (!$this->determinedPerPageValue($parameters['_per_page'])) {
844
                $parameters['_per_page'] = $this->getMaxPerPage();
845
            }
846
847
            // always force the parent value
848
            if ($this->isChild() && $this->getParentAssociationMapping()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getParentAssociationMapping() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
849
                $name = str_replace('.', '__', $this->getParentAssociationMapping());
850
                $parameters[$name] = ['value' => $this->request->get($this->getParent()->getIdParameter())];
851
            }
852
        }
853
854
        return $parameters;
855
    }
856
857
    /**
858
     * NEXT_MAJOR: Change the visibility to protected (similar to buildShow, buildForm, ...).
859
     */
860
    public function buildDatagrid()
861
    {
862
        if ($this->loaded['datagrid']) {
863
            return;
864
        }
865
866
        $this->loaded['datagrid'] = true;
867
868
        $filterParameters = $this->getFilterParameters();
869
870
        // transform _sort_by from a string to a FieldDescriptionInterface for the datagrid.
871
        if (isset($filterParameters['_sort_by']) && \is_string($filterParameters['_sort_by'])) {
872
            if ($this->hasListFieldDescription($filterParameters['_sort_by'])) {
873
                $filterParameters['_sort_by'] = $this->getListFieldDescription($filterParameters['_sort_by']);
874
            } else {
875
                $filterParameters['_sort_by'] = $this->getModelManager()->getNewFieldDescriptionInstance(
876
                    $this->getClass(),
877
                    $filterParameters['_sort_by'],
878
                    []
879
                );
880
881
                $this->getListBuilder()->buildField(null, $filterParameters['_sort_by'], $this);
882
            }
883
        }
884
885
        // initialize the datagrid
886
        $this->datagrid = $this->getDatagridBuilder()->getBaseDatagrid($this, $filterParameters);
887
888
        $this->datagrid->getPager()->setMaxPageLinks($this->maxPageLinks);
889
890
        $mapper = new DatagridMapper($this->getDatagridBuilder(), $this->datagrid, $this);
891
892
        // build the datagrid filter
893
        $this->configureDatagridFilters($mapper);
894
895
        // ok, try to limit to add parent filter
896
        if ($this->isChild() && $this->getParentAssociationMapping() && !$mapper->has($this->getParentAssociationMapping())) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getParentAssociationMapping() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
897
            $mapper->add($this->getParentAssociationMapping(), null, [
898
                'show_filter' => false,
899
                'label' => false,
900
                'field_type' => ModelHiddenType::class,
901
                'field_options' => [
902
                    'model_manager' => $this->getModelManager(),
903
                ],
904
                'operator_type' => HiddenType::class,
905
            ], null, null, [
906
                'admin_code' => $this->getParent()->getCode(),
907
            ]);
908
        }
909
910
        foreach ($this->getExtensions() as $extension) {
911
            $extension->configureDatagridFilters($mapper);
912
        }
913
    }
914
915
    /**
916
     * Returns the name of the parent related field, so the field can be use to set the default
917
     * value (ie the parent object) or to filter the object.
918
     *
919
     * @throws \InvalidArgumentException
920
     *
921
     * @return string|null
922
     */
923
    public function getParentAssociationMapping()
924
    {
925
        // NEXT_MAJOR: remove array check
926
        if (\is_array($this->parentAssociationMapping) && $this->isChild()) {
927
            $parent = $this->getParent()->getCode();
928
929
            if (\array_key_exists($parent, $this->parentAssociationMapping)) {
930
                return $this->parentAssociationMapping[$parent];
931
            }
932
933
            throw new \InvalidArgumentException(sprintf(
934
                'There\'s no association between %s and %s.',
935
                $this->getCode(),
936
                $this->getParent()->getCode()
937
            ));
938
        }
939
940
        // NEXT_MAJOR: remove this line
941
        return $this->parentAssociationMapping;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->parentAssociationMapping; of type string|array adds the type array to the return on line 941 which is incompatible with the return type documented by Sonata\AdminBundle\Admin...arentAssociationMapping of type string|null.
Loading history...
942
    }
943
944
    /**
945
     * @param string $code
946
     * @param string $value
947
     */
948
    final public function addParentAssociationMapping($code, $value)
949
    {
950
        $this->parentAssociationMapping[$code] = $value;
951
    }
952
953
    /**
954
     * Returns the baseRoutePattern used to generate the routing information.
955
     *
956
     * @throws \RuntimeException
957
     *
958
     * @return string the baseRoutePattern used to generate the routing information
959
     */
960
    public function getBaseRoutePattern()
961
    {
962
        if (null !== $this->cachedBaseRoutePattern) {
963
            return $this->cachedBaseRoutePattern;
964
        }
965
966
        if ($this->isChild()) { // the admin class is a child, prefix it with the parent route pattern
967
            $baseRoutePattern = $this->baseRoutePattern;
968
            if (!$this->baseRoutePattern) {
969
                preg_match(self::CLASS_REGEX, $this->class, $matches);
970
971
                if (!$matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
972
                    throw new \RuntimeException(sprintf(
973
                        'Please define a default `baseRoutePattern` value for the admin class `%s`',
974
                        static::class
975
                    ));
976
                }
977
                $baseRoutePattern = $this->urlize($matches[5], '-');
978
            }
979
980
            $this->cachedBaseRoutePattern = sprintf(
981
                '%s/%s/%s',
982
                $this->getParent()->getBaseRoutePattern(),
983
                $this->getParent()->getRouterIdParameter(),
984
                $baseRoutePattern
985
            );
986
        } elseif ($this->baseRoutePattern) {
987
            $this->cachedBaseRoutePattern = $this->baseRoutePattern;
988
        } else {
989
            preg_match(self::CLASS_REGEX, $this->class, $matches);
990
991
            if (!$matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
992
                throw new \RuntimeException(sprintf(
993
                    'Please define a default `baseRoutePattern` value for the admin class `%s`',
994
                    static::class
995
                ));
996
            }
997
998
            $this->cachedBaseRoutePattern = sprintf(
999
                '/%s%s/%s',
1000
                empty($matches[1]) ? '' : $this->urlize($matches[1], '-').'/',
1001
                $this->urlize($matches[3], '-'),
1002
                $this->urlize($matches[5], '-')
1003
            );
1004
        }
1005
1006
        return $this->cachedBaseRoutePattern;
1007
    }
1008
1009
    /**
1010
     * Returns the baseRouteName used to generate the routing information.
1011
     *
1012
     * @throws \RuntimeException
1013
     *
1014
     * @return string the baseRouteName used to generate the routing information
1015
     */
1016
    public function getBaseRouteName()
1017
    {
1018
        if (null !== $this->cachedBaseRouteName) {
1019
            return $this->cachedBaseRouteName;
1020
        }
1021
1022
        if ($this->isChild()) { // the admin class is a child, prefix it with the parent route name
1023
            $baseRouteName = $this->baseRouteName;
1024
            if (!$this->baseRouteName) {
1025
                preg_match(self::CLASS_REGEX, $this->class, $matches);
1026
1027
                if (!$matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1028
                    throw new \RuntimeException(sprintf(
1029
                        'Cannot automatically determine base route name,'
1030
                        .' please define a default `baseRouteName` value for the admin class `%s`',
1031
                        static::class
1032
                    ));
1033
                }
1034
                $baseRouteName = $this->urlize($matches[5]);
1035
            }
1036
1037
            $this->cachedBaseRouteName = sprintf(
1038
                '%s_%s',
1039
                $this->getParent()->getBaseRouteName(),
1040
                $baseRouteName
1041
            );
1042
        } elseif ($this->baseRouteName) {
1043
            $this->cachedBaseRouteName = $this->baseRouteName;
1044
        } else {
1045
            preg_match(self::CLASS_REGEX, $this->class, $matches);
1046
1047
            if (!$matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1048
                throw new \RuntimeException(sprintf(
1049
                    'Cannot automatically determine base route name,'
1050
                    .' please define a default `baseRouteName` value for the admin class `%s`',
1051
                    static::class
1052
                ));
1053
            }
1054
1055
            $this->cachedBaseRouteName = sprintf(
1056
                'admin_%s%s_%s',
1057
                empty($matches[1]) ? '' : $this->urlize($matches[1]).'_',
1058
                $this->urlize($matches[3]),
1059
                $this->urlize($matches[5])
1060
            );
1061
        }
1062
1063
        return $this->cachedBaseRouteName;
1064
    }
1065
1066
    /**
1067
     * urlize the given word.
1068
     *
1069
     * @param string $word
1070
     * @param string $sep  the separator
1071
     *
1072
     * @return string
1073
     */
1074
    public function urlize($word, $sep = '_')
1075
    {
1076
        return strtolower(preg_replace('/[^a-z0-9_]/i', $sep.'$1', $word));
1077
    }
1078
1079
    public function getClass()
1080
    {
1081
        if ($this->hasActiveSubClass()) {
1082
            if ($this->hasParentFieldDescription()) {
1083
                throw new \RuntimeException('Feature not implemented: an embedded admin cannot have subclass');
1084
            }
1085
1086
            $subClass = $this->getRequest()->query->get('subclass');
1087
1088
            if (!$this->hasSubClass($subClass)) {
1089
                throw new \RuntimeException(sprintf('Subclass "%s" is not defined.', $subClass));
1090
            }
1091
1092
            return $this->getSubClass($subClass);
1093
        }
1094
1095
        // see https://github.com/sonata-project/SonataCoreBundle/commit/247eeb0a7ca7211142e101754769d70bc402a5b4
1096
        if ($this->subject && \is_object($this->subject)) {
1097
            return ClassUtils::getClass($this->subject);
1098
        }
1099
1100
        return $this->class;
1101
    }
1102
1103
    public function getSubClasses()
1104
    {
1105
        return $this->subClasses;
1106
    }
1107
1108
    /**
1109
     * NEXT_MAJOR: remove this method.
1110
     */
1111
    public function addSubClass($subClass)
1112
    {
1113
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1114
            'Method "%s" is deprecated since sonata-project/admin-bundle 3.30 and will be removed in 4.0.',
1115
            __METHOD__
1116
        ), E_USER_DEPRECATED);
1117
1118
        if (!\in_array($subClass, $this->subClasses, true)) {
1119
            $this->subClasses[] = $subClass;
1120
        }
1121
    }
1122
1123
    public function setSubClasses(array $subClasses)
1124
    {
1125
        $this->subClasses = $subClasses;
1126
    }
1127
1128
    public function hasSubClass($name)
1129
    {
1130
        return isset($this->subClasses[$name]);
1131
    }
1132
1133
    public function hasActiveSubClass()
1134
    {
1135
        if (\count($this->subClasses) > 0 && $this->request) {
1136
            return null !== $this->getRequest()->query->get('subclass');
1137
        }
1138
1139
        return false;
1140
    }
1141
1142
    public function getActiveSubClass()
1143
    {
1144
        if (!$this->hasActiveSubClass()) {
1145
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1146
                'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52'
1147
                .' and will throw an exception in 4.0.'
1148
                .' Use %s::hasActiveSubClass() to know if there is an active subclass.',
1149
                __METHOD__,
1150
                __CLASS__
1151
            ), E_USER_DEPRECATED);
1152
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare string as return type
1153
            // throw new \LogicException(sprintf(
1154
            //    'Admin "%s" has no active subclass.',
1155
            //    static::class
1156
            // ));
1157
1158
            return null;
1159
        }
1160
1161
        return $this->getSubClass($this->getActiveSubclassCode());
1162
    }
1163
1164
    public function getActiveSubclassCode()
1165
    {
1166
        if (!$this->hasActiveSubClass()) {
1167
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1168
                'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52'
1169
                .' and will throw an exception in 4.0.'
1170
                .' Use %s::hasActiveSubClass() to know if there is an active subclass.',
1171
                __METHOD__,
1172
                __CLASS__
1173
            ), E_USER_DEPRECATED);
1174
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare string as return type
1175
            // throw new \LogicException(sprintf(
1176
            //    'Admin "%s" has no active subclass.',
1177
            //    static::class
1178
            // ));
1179
1180
            return null;
1181
        }
1182
1183
        $subClass = $this->getRequest()->query->get('subclass');
1184
1185
        if (!$this->hasSubClass($subClass)) {
1186
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1187
                'Calling %s() when there is no active subclass is deprecated since sonata-project/admin-bundle 3.52'
1188
                .' and will throw an exception in 4.0.'
1189
                .' Use %s::hasActiveSubClass() to know if there is an active subclass.',
1190
                __METHOD__,
1191
                __CLASS__
1192
            ), E_USER_DEPRECATED);
1193
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare string as return type
1194
            // throw new \LogicException(sprintf(
1195
            //    'Admin "%s" has no active subclass.',
1196
            //    static::class
1197
            // ));
1198
1199
            return null;
1200
        }
1201
1202
        return $subClass;
1203
    }
1204
1205
    public function getBatchActions()
1206
    {
1207
        $actions = [];
1208
1209
        if ($this->hasRoute('delete') && $this->hasAccess('delete')) {
1210
            $actions['delete'] = [
1211
                'label' => 'action_delete',
1212
                'translation_domain' => 'SonataAdminBundle',
1213
                'ask_confirmation' => true, // by default always true
1214
            ];
1215
        }
1216
1217
        $actions = $this->configureBatchActions($actions);
1218
1219
        foreach ($this->getExtensions() as $extension) {
1220
            // NEXT_MAJOR: remove method check
1221
            if (method_exists($extension, 'configureBatchActions')) {
1222
                $actions = $extension->configureBatchActions($this, $actions);
1223
            }
1224
        }
1225
1226
        foreach ($actions  as $name => &$action) {
1227
            if (!\array_key_exists('label', $action)) {
1228
                $action['label'] = $this->getTranslationLabel($name, 'batch', 'label');
1229
            }
1230
1231
            if (!\array_key_exists('translation_domain', $action)) {
1232
                $action['translation_domain'] = $this->getTranslationDomain();
1233
            }
1234
        }
1235
1236
        return $actions;
1237
    }
1238
1239
    public function getRoutes()
1240
    {
1241
        $this->buildRoutes();
1242
1243
        return $this->routes;
1244
    }
1245
1246
    public function getRouterIdParameter()
1247
    {
1248
        return sprintf('{%s}', $this->getIdParameter());
1249
    }
1250
1251
    public function getIdParameter()
1252
    {
1253
        $parameter = 'id';
1254
1255
        for ($i = 0; $i < $this->getChildDepth(); ++$i) {
1256
            $parameter = sprintf('child%s', ucfirst($parameter));
1257
        }
1258
1259
        return $parameter;
1260
    }
1261
1262
    public function hasRoute($name)
1263
    {
1264
        if (!$this->routeGenerator) {
1265
            throw new \RuntimeException('RouteGenerator cannot be null');
1266
        }
1267
1268
        return $this->routeGenerator->hasAdminRoute($this, $name);
1269
    }
1270
1271
    /**
1272
     * @param string      $name
1273
     * @param string|null $adminCode
1274
     *
1275
     * @return bool
1276
     */
1277
    public function isCurrentRoute($name, $adminCode = null)
1278
    {
1279
        if (!$this->hasRequest()) {
1280
            return false;
1281
        }
1282
1283
        $request = $this->getRequest();
1284
        $route = $request->get('_route');
1285
1286
        if ($adminCode) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $adminCode of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1287
            $admin = $this->getConfigurationPool()->getAdminByAdminCode($adminCode);
1288
        } else {
1289
            $admin = $this;
1290
        }
1291
1292
        if (!$admin) {
1293
            return false;
1294
        }
1295
1296
        return sprintf('%s_%s', $admin->getBaseRouteName(), $name) === $route;
1297
    }
1298
1299
    public function generateObjectUrl($name, $object, array $parameters = [], $referenceType = RoutingUrlGeneratorInterface::ABSOLUTE_PATH)
1300
    {
1301
        $parameters['id'] = $this->getUrlSafeIdentifier($object);
1302
1303
        return $this->generateUrl($name, $parameters, $referenceType);
1304
    }
1305
1306
    public function generateUrl($name, array $parameters = [], $referenceType = RoutingUrlGeneratorInterface::ABSOLUTE_PATH)
1307
    {
1308
        return $this->routeGenerator->generateUrl($this, $name, $parameters, $referenceType);
1309
    }
1310
1311
    public function generateMenuUrl($name, array $parameters = [], $referenceType = RoutingUrlGeneratorInterface::ABSOLUTE_PATH)
1312
    {
1313
        return $this->routeGenerator->generateMenuUrl($this, $name, $parameters, $referenceType);
1314
    }
1315
1316
    final public function setTemplateRegistry(MutableTemplateRegistryInterface $templateRegistry)
1317
    {
1318
        $this->templateRegistry = $templateRegistry;
1319
    }
1320
1321
    /**
1322
     * @param array<string, string> $templates
1323
     */
1324
    public function setTemplates(array $templates)
1325
    {
1326
        // NEXT_MAJOR: Remove this line
1327
        $this->templates = $templates;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin\AbstractAdmin::$templates has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1328
1329
        $this->getTemplateRegistry()->setTemplates($templates);
1330
    }
1331
1332
    /**
1333
     * @param string $name
1334
     * @param string $template
1335
     */
1336
    public function setTemplate($name, $template)
1337
    {
1338
        // NEXT_MAJOR: Remove this line
1339
        $this->templates[$name] = $template;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin\AbstractAdmin::$templates has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1340
1341
        $this->getTemplateRegistry()->setTemplate($name, $template);
1342
    }
1343
1344
    /**
1345
     * @deprecated since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead
1346
     *
1347
     * @return array<string, string>
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1348
     */
1349
    public function getTemplates()
1350
    {
1351
        return $this->getTemplateRegistry()->getTemplates();
1352
    }
1353
1354
    /**
1355
     * @deprecated since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead
1356
     *
1357
     * @param string $name
1358
     *
1359
     * @return string|null
1360
     */
1361
    public function getTemplate($name)
1362
    {
1363
        return $this->getTemplateRegistry()->getTemplate($name);
1364
    }
1365
1366
    public function getNewInstance()
1367
    {
1368
        $object = $this->getModelManager()->getModelInstance($this->getClass());
1369
1370
        $this->appendParentObject($object);
1371
1372
        foreach ($this->getExtensions() as $extension) {
1373
            $extension->alterNewInstance($this, $object);
1374
        }
1375
1376
        return $object;
1377
    }
1378
1379
    public function getFormBuilder()
1380
    {
1381
        $this->formOptions['data_class'] = $this->getClass();
1382
1383
        $formBuilder = $this->getFormContractor()->getFormBuilder(
1384
            $this->getUniqid(),
1385
            $this->formOptions
1386
        );
1387
1388
        $this->defineFormBuilder($formBuilder);
1389
1390
        return $formBuilder;
1391
    }
1392
1393
    /**
1394
     * This method is being called by the main admin class and the child class,
1395
     * the getFormBuilder is only call by the main admin class.
1396
     */
1397
    public function defineFormBuilder(FormBuilderInterface $formBuilder)
1398
    {
1399
        if (!$this->hasSubject()) {
1400
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1401
                'Calling %s() when there is no subject is deprecated since sonata-project/admin-bundle 3.65'
1402
                .' and will throw an exception in 4.0. Use %s::setSubject() to set the subject.',
1403
                __METHOD__,
1404
                __CLASS__
1405
            ), E_USER_DEPRECATED);
1406
            // NEXT_MAJOR : remove the previous `trigger_error()` call and uncomment the following exception
1407
            // throw new \LogicException(sprintf(
1408
            //    'Admin "%s" has no subject.',
1409
            //    static::class
1410
            // ));
1411
        }
1412
1413
        $mapper = new FormMapper($this->getFormContractor(), $formBuilder, $this);
1414
1415
        $this->configureFormFields($mapper);
1416
1417
        foreach ($this->getExtensions() as $extension) {
1418
            $extension->configureFormFields($mapper);
1419
        }
1420
1421
        $this->attachInlineValidator();
1422
    }
1423
1424
    public function attachAdminClass(FieldDescriptionInterface $fieldDescription)
1425
    {
1426
        $pool = $this->getConfigurationPool();
1427
1428
        $adminCode = $fieldDescription->getOption('admin_code');
1429
1430
        if (null !== $adminCode) {
1431
            if (!$pool->hasAdminByAdminCode($adminCode)) {
1432
                return;
1433
            }
1434
1435
            $admin = $pool->getAdminByAdminCode($adminCode);
1436
        } else {
1437
            // NEXT_MAJOR: Remove the check and use `getTargetModel`.
1438
            if (method_exists($fieldDescription, 'getTargetModel')) {
1439
                $targetModel = $fieldDescription->getTargetModel();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sonata\AdminBundle\Admin\FieldDescriptionInterface as the method getTargetModel() does only exist in the following implementations of said interface: Sonata\AdminBundle\Tests...\Admin\FieldDescription, Sonata\AdminBundle\Tests...\Admin\FieldDescription.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1440
            } else {
1441
                $targetModel = $fieldDescription->getTargetEntity();
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...face::getTargetEntity() has been deprecated with message: since sonata-project/admin-bundle 3.69. Use `getTargetModel()` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1442
            }
1443
1444
            if (!$pool->hasAdminByClass($targetModel)) {
1445
                return;
1446
            }
1447
1448
            $admin = $pool->getAdminByClass($targetModel);
1449
        }
1450
1451
        if ($this->hasRequest()) {
1452
            $admin->setRequest($this->getRequest());
1453
        }
1454
1455
        $fieldDescription->setAssociationAdmin($admin);
0 ignored issues
show
Bug introduced by
It seems like $admin can also be of type false or null; however, Sonata\AdminBundle\Admin...::setAssociationAdmin() does only seem to accept object<Sonata\AdminBundle\Admin\AdminInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1456
    }
1457
1458
    public function getObject($id)
1459
    {
1460
        $object = $this->getModelManager()->find($this->getClass(), $id);
1461
        foreach ($this->getExtensions() as $extension) {
1462
            $extension->alterObject($this, $object);
0 ignored issues
show
Bug introduced by
It seems like $object defined by $this->getModelManager()...$this->getClass(), $id) on line 1460 can also be of type null; however, Sonata\AdminBundle\Admin...nterface::alterObject() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1463
        }
1464
1465
        return $object;
1466
    }
1467
1468
    public function getForm()
1469
    {
1470
        $this->buildForm();
1471
1472
        return $this->form;
1473
    }
1474
1475
    public function getList()
1476
    {
1477
        $this->buildList();
1478
1479
        return $this->list;
1480
    }
1481
1482
    /**
1483
     * @final since sonata-project/admin-bundle 3.63.0
1484
     */
1485
    public function createQuery($context = 'list')
1486
    {
1487
        if (\func_num_args() > 0) {
1488
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1489
                'The $context argument of %s is deprecated since 3.3, to be removed in 4.0.',
1490
                __METHOD__
1491
            ), E_USER_DEPRECATED);
1492
        }
1493
1494
        $query = $this->getModelManager()->createQuery($this->getClass());
1495
1496
        $query = $this->configureQuery($query);
1497
        foreach ($this->extensions as $extension) {
1498
            $extension->configureQuery($this, $query, $context);
1499
        }
1500
1501
        return $query;
1502
    }
1503
1504
    public function getDatagrid()
1505
    {
1506
        $this->buildDatagrid();
1507
1508
        return $this->datagrid;
1509
    }
1510
1511
    public function buildTabMenu($action, ?AdminInterface $childAdmin = null)
1512
    {
1513
        if ($this->loaded['tab_menu']) {
1514
            return $this->menu;
1515
        }
1516
1517
        $this->loaded['tab_menu'] = true;
1518
1519
        $menu = $this->menuFactory->createItem('root');
1520
        $menu->setChildrenAttribute('class', 'nav navbar-nav');
1521
        $menu->setExtra('translation_domain', $this->translationDomain);
1522
1523
        // Prevents BC break with KnpMenuBundle v1.x
1524
        if (method_exists($menu, 'setCurrentUri')) {
1525
            $menu->setCurrentUri($this->getRequest()->getBaseUrl().$this->getRequest()->getPathInfo());
0 ignored issues
show
Bug introduced by
The method setCurrentUri() does not exist on Knp\Menu\ItemInterface. Did you maybe mean setCurrent()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1526
        }
1527
1528
        $this->configureTabMenu($menu, $action, $childAdmin);
1529
1530
        foreach ($this->getExtensions() as $extension) {
1531
            $extension->configureTabMenu($this, $menu, $action, $childAdmin);
1532
        }
1533
1534
        $this->menu = $menu;
1535
1536
        return $this->menu;
1537
    }
1538
1539
    public function buildSideMenu($action, ?AdminInterface $childAdmin = null)
1540
    {
1541
        return $this->buildTabMenu($action, $childAdmin);
1542
    }
1543
1544
    /**
1545
     * @param string $action
1546
     *
1547
     * @return ItemInterface
1548
     */
1549
    public function getSideMenu($action, ?AdminInterface $childAdmin = null)
1550
    {
1551
        if ($this->isChild()) {
1552
            return $this->getParent()->getSideMenu($action, $this);
1553
        }
1554
1555
        $this->buildSideMenu($action, $childAdmin);
1556
1557
        return $this->menu;
1558
    }
1559
1560
    /**
1561
     * Returns the root code.
1562
     *
1563
     * @return string the root code
1564
     */
1565
    public function getRootCode()
1566
    {
1567
        return $this->getRoot()->getCode();
1568
    }
1569
1570
    /**
1571
     * Returns the master admin.
1572
     *
1573
     * @return AbstractAdmin the root admin class
1574
     */
1575
    public function getRoot()
1576
    {
1577
        if (!$this->hasParentFieldDescription()) {
1578
            return $this;
1579
        }
1580
1581
        return $this->getParentFieldDescription()->getAdmin()->getRoot();
1582
    }
1583
1584
    public function setBaseControllerName($baseControllerName)
1585
    {
1586
        $this->baseControllerName = $baseControllerName;
1587
    }
1588
1589
    public function getBaseControllerName()
1590
    {
1591
        return $this->baseControllerName;
1592
    }
1593
1594
    /**
1595
     * @param string $label
1596
     */
1597
    public function setLabel($label)
1598
    {
1599
        $this->label = $label;
1600
    }
1601
1602
    public function getLabel()
1603
    {
1604
        return $this->label;
1605
    }
1606
1607
    /**
1608
     * @param bool $persist
1609
     *
1610
     * NEXT_MAJOR: remove this method
1611
     *
1612
     * @deprecated since sonata-project/admin-bundle 3.34, to be removed in 4.0.
1613
     */
1614
    public function setPersistFilters($persist)
1615
    {
1616
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1617
            'The %s method is deprecated since version 3.34 and will be removed in 4.0.',
1618
            __METHOD__
1619
        ), E_USER_DEPRECATED);
1620
1621
        $this->persistFilters = $persist;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$persistFilters has been deprecated with message: since sonata-project/admin-bundle 3.34, to be removed in 4.0.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1622
    }
1623
1624
    public function setFilterPersister(?FilterPersisterInterface $filterPersister = null)
1625
    {
1626
        $this->filterPersister = $filterPersister;
1627
        // NEXT_MAJOR remove the deprecated property will be removed. Needed for persisted filter condition.
1628
        $this->persistFilters = true;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$persistFilters has been deprecated with message: since sonata-project/admin-bundle 3.34, to be removed in 4.0.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1629
    }
1630
1631
    /**
1632
     * NEXT_MAJOR: Remove this method.
1633
     *
1634
     * @deprecated since sonata-project/admin-bundle 3.67, to be removed in 4.0.
1635
     *
1636
     * @param int $maxPerPage
1637
     */
1638
    public function setMaxPerPage($maxPerPage)
1639
    {
1640
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1641
            'The method %s is deprecated since sonata-project/admin-bundle 3.67 and will be removed in 4.0.',
1642
            __METHOD__
1643
        ), E_USER_DEPRECATED);
1644
1645
        $this->maxPerPage = $maxPerPage;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$maxPerPage has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1646
    }
1647
1648
    /**
1649
     * @return int
1650
     */
1651
    public function getMaxPerPage()
1652
    {
1653
        // NEXT_MAJOR: Remove this line and uncomment the following.
1654
        return $this->maxPerPage;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$maxPerPage has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1655
        // $sortValues = $this->getModelManager()->getDefaultSortValues($this->class);
1656
1657
        // return $sortValues['_per_page'] ?? 25;
1658
    }
1659
1660
    /**
1661
     * @param int $maxPageLinks
1662
     */
1663
    public function setMaxPageLinks($maxPageLinks)
1664
    {
1665
        $this->maxPageLinks = $maxPageLinks;
1666
    }
1667
1668
    /**
1669
     * @return int
1670
     */
1671
    public function getMaxPageLinks()
1672
    {
1673
        return $this->maxPageLinks;
1674
    }
1675
1676
    public function getFormGroups()
1677
    {
1678
        if (!\is_array($this->formGroups) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) {
1679
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1680
                'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.'
1681
                .' It will return only array in version 4.0.',
1682
                __METHOD__
1683
            ), E_USER_DEPRECATED);
1684
        }
1685
1686
        return $this->formGroups;
1687
    }
1688
1689
    public function setFormGroups(array $formGroups)
1690
    {
1691
        $this->formGroups = $formGroups;
1692
    }
1693
1694
    public function removeFieldFromFormGroup($key)
1695
    {
1696
        foreach ($this->formGroups as $name => $formGroup) {
0 ignored issues
show
Bug introduced by
The expression $this->formGroups of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1697
            unset($this->formGroups[$name]['fields'][$key]);
1698
1699
            if (empty($this->formGroups[$name]['fields'])) {
1700
                unset($this->formGroups[$name]);
1701
            }
1702
        }
1703
    }
1704
1705
    /**
1706
     * @param string $group
1707
     */
1708
    public function reorderFormGroup($group, array $keys)
1709
    {
1710
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.
1711
        $formGroups = $this->getFormGroups('sonata_deprecation_mute');
1712
        $formGroups[$group]['fields'] = array_merge(array_flip($keys), $formGroups[$group]['fields']);
1713
        $this->setFormGroups($formGroups);
0 ignored issues
show
Bug introduced by
It seems like $formGroups defined by $this->getFormGroups('sonata_deprecation_mute') on line 1711 can also be of type boolean; however, Sonata\AdminBundle\Admin...tAdmin::setFormGroups() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1714
    }
1715
1716
    public function getFormTabs()
1717
    {
1718
        if (!\is_array($this->formTabs) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) {
1719
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1720
                'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.'
1721
                .' It will return only array in version 4.0.',
1722
                __METHOD__
1723
            ), E_USER_DEPRECATED);
1724
        }
1725
1726
        return $this->formTabs;
1727
    }
1728
1729
    public function setFormTabs(array $formTabs)
1730
    {
1731
        $this->formTabs = $formTabs;
1732
    }
1733
1734
    public function getShowTabs()
1735
    {
1736
        if (!\is_array($this->showTabs) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) {
1737
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1738
                'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.'
1739
                .' It will return only array in version 4.0.',
1740
                __METHOD__
1741
            ), E_USER_DEPRECATED);
1742
        }
1743
1744
        return $this->showTabs;
1745
    }
1746
1747
    public function setShowTabs(array $showTabs)
1748
    {
1749
        $this->showTabs = $showTabs;
1750
    }
1751
1752
    public function getShowGroups()
1753
    {
1754
        if (!\is_array($this->showGroups) && 'sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) {
1755
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1756
                'Returning other type than array in method %s() is deprecated since sonata-project/admin-bundle 3.65.'
1757
                .' It will return only array in version 4.0.',
1758
                __METHOD__
1759
            ), E_USER_DEPRECATED);
1760
        }
1761
1762
        return $this->showGroups;
1763
    }
1764
1765
    public function setShowGroups(array $showGroups)
1766
    {
1767
        $this->showGroups = $showGroups;
1768
    }
1769
1770
    public function reorderShowGroup($group, array $keys)
1771
    {
1772
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.
1773
        $showGroups = $this->getShowGroups('sonata_deprecation_mute');
1774
        $showGroups[$group]['fields'] = array_merge(array_flip($keys), $showGroups[$group]['fields']);
1775
        $this->setShowGroups($showGroups);
0 ignored issues
show
Bug introduced by
It seems like $showGroups defined by $this->getShowGroups('sonata_deprecation_mute') on line 1773 can also be of type boolean; however, Sonata\AdminBundle\Admin...tAdmin::setShowGroups() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1776
    }
1777
1778
    public function setParentFieldDescription(FieldDescriptionInterface $parentFieldDescription)
1779
    {
1780
        $this->parentFieldDescription = $parentFieldDescription;
1781
    }
1782
1783
    public function getParentFieldDescription()
1784
    {
1785
        if (!$this->hasParentFieldDescription()) {
1786
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1787
                'Calling %s() when there is no parent field description is deprecated since'
1788
                .' sonata-project/admin-bundle 3.66 and will throw an exception in 4.0.'
1789
                .' Use %s::hasParentFieldDescription() to know if there is a parent field description.',
1790
                __METHOD__,
1791
                __CLASS__
1792
            ), E_USER_DEPRECATED);
1793
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare FieldDescriptionInterface as return type
1794
            // throw new \LogicException(sprintf(
1795
            //    'Admin "%s" has no parent field description.',
1796
            //    static::class
1797
            // ));
1798
1799
            return null;
1800
        }
1801
1802
        return $this->parentFieldDescription;
1803
    }
1804
1805
    public function hasParentFieldDescription()
1806
    {
1807
        return $this->parentFieldDescription instanceof FieldDescriptionInterface;
1808
    }
1809
1810
    public function setSubject($subject)
1811
    {
1812
        if (\is_object($subject) && !is_a($subject, $this->getClass(), true)) {
1813
            $message = <<<'EOT'
1814
You are trying to set entity an instance of "%s",
1815
which is not the one registered with this admin class ("%s").
1816
This is deprecated since 3.5 and will no longer be supported in 4.0.
1817
EOT;
1818
1819
            // NEXT_MAJOR : throw an exception instead
1820
            @trigger_error(sprintf($message, \get_class($subject), $this->getClass()), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1821
        }
1822
1823
        $this->subject = $subject;
1824
    }
1825
1826
    public function getSubject()
1827
    {
1828
        if (!$this->hasSubject()) {
1829
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1830
                'Calling %s() when there is no subject is deprecated since sonata-project/admin-bundle 3.66'
1831
                .' and will throw an exception in 4.0. Use %s::hasSubject() to know if there is a subject.',
1832
                __METHOD__,
1833
                __CLASS__
1834
            ), E_USER_DEPRECATED);
1835
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and update the return type
1836
            // throw new \LogicException(sprintf(
1837
            //    'Admin "%s" has no subject.',
1838
            //    static::class
1839
            // ));
1840
1841
            return null;
1842
        }
1843
1844
        return $this->subject;
1845
    }
1846
1847
    public function hasSubject()
1848
    {
1849
        if (null === $this->subject && $this->hasRequest() && !$this->hasParentFieldDescription()) {
1850
            $id = $this->request->get($this->getIdParameter());
1851
1852
            if (null !== $id) {
1853
                $this->subject = $this->getObject($id);
1854
            }
1855
        }
1856
1857
        return null !== $this->subject;
1858
    }
1859
1860
    public function getFormFieldDescriptions()
1861
    {
1862
        $this->buildForm();
1863
1864
        return $this->formFieldDescriptions;
1865
    }
1866
1867
    public function getFormFieldDescription($name)
1868
    {
1869
        $this->buildForm();
1870
1871
        if (!$this->hasFormFieldDescription($name)) {
1872
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1873
                'Calling %s() when there is no form field description is deprecated since'
1874
                .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.'
1875
                .' Use %s::hasFormFieldDescription() to know if there is a form field description.',
1876
                __METHOD__,
1877
                __CLASS__
1878
            ), E_USER_DEPRECATED);
1879
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare FieldDescriptionInterface as return type
1880
            // throw new \LogicException(sprintf(
1881
            //    'Admin "%s" has no form field description for the field %s.',
1882
            //    static::class,
1883
            //    $name
1884
            // ));
1885
1886
            return null;
1887
        }
1888
1889
        return $this->formFieldDescriptions[$name];
1890
    }
1891
1892
    /**
1893
     * Returns true if the admin has a FieldDescription with the given $name.
1894
     *
1895
     * @param string $name
1896
     *
1897
     * @return bool
1898
     */
1899
    public function hasFormFieldDescription($name)
1900
    {
1901
        $this->buildForm();
1902
1903
        return \array_key_exists($name, $this->formFieldDescriptions) ? true : false;
1904
    }
1905
1906
    public function addFormFieldDescription($name, FieldDescriptionInterface $fieldDescription)
1907
    {
1908
        $this->formFieldDescriptions[$name] = $fieldDescription;
1909
    }
1910
1911
    /**
1912
     * remove a FieldDescription.
1913
     *
1914
     * @param string $name
1915
     */
1916
    public function removeFormFieldDescription($name)
1917
    {
1918
        unset($this->formFieldDescriptions[$name]);
1919
    }
1920
1921
    /**
1922
     * build and return the collection of form FieldDescription.
1923
     *
1924
     * @return FieldDescriptionInterface[] collection of form FieldDescription
1925
     */
1926
    public function getShowFieldDescriptions()
1927
    {
1928
        $this->buildShow();
1929
1930
        return $this->showFieldDescriptions;
1931
    }
1932
1933
    /**
1934
     * Returns the form FieldDescription with the given $name.
1935
     *
1936
     * @param string $name
1937
     *
1938
     * @return FieldDescriptionInterface
1939
     */
1940
    public function getShowFieldDescription($name)
1941
    {
1942
        $this->buildShow();
1943
1944
        if (!$this->hasShowFieldDescription($name)) {
1945
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1946
                'Calling %s() when there is no show field description is deprecated since'
1947
                .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.'
1948
                .' Use %s::hasFormFieldDescription() to know if there is a show field description.',
1949
                __METHOD__,
1950
                __CLASS__
1951
            ), E_USER_DEPRECATED);
1952
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare FieldDescriptionInterface as return type
1953
            // throw new \LogicException(sprintf(
1954
            //    'Admin "%s" has no show field description for the field %s.',
1955
            //    static::class,
1956
            //    $name
1957
            // ));
1958
1959
            return null;
1960
        }
1961
1962
        return $this->showFieldDescriptions[$name];
1963
    }
1964
1965
    public function hasShowFieldDescription($name)
1966
    {
1967
        $this->buildShow();
1968
1969
        return \array_key_exists($name, $this->showFieldDescriptions);
1970
    }
1971
1972
    public function addShowFieldDescription($name, FieldDescriptionInterface $fieldDescription)
1973
    {
1974
        $this->showFieldDescriptions[$name] = $fieldDescription;
1975
    }
1976
1977
    public function removeShowFieldDescription($name)
1978
    {
1979
        unset($this->showFieldDescriptions[$name]);
1980
    }
1981
1982
    public function getListFieldDescriptions()
1983
    {
1984
        $this->buildList();
1985
1986
        return $this->listFieldDescriptions;
1987
    }
1988
1989
    public function getListFieldDescription($name)
1990
    {
1991
        $this->buildList();
1992
1993
        if (!$this->hasListFieldDescription($name)) {
1994
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1995
                'Calling %s() when there is no list field description is deprecated since'
1996
                .' sonata-project/admin-bundle 3.66 and will throw an exception in 4.0.'
1997
                .' Use %s::hasListFieldDescription(\'%s\') to know if there is a list field description.',
1998
                __METHOD__,
1999
                __CLASS__,
2000
                $name
2001
            ), E_USER_DEPRECATED);
2002
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare FieldDescriptionInterface as return type
2003
            // throw new \LogicException(sprintf(
2004
            //    'Admin "%s" has no list field description for %s.',
2005
            //    static::class,
2006
            //    $name
2007
            // ));
2008
2009
            return null;
2010
        }
2011
2012
        return $this->listFieldDescriptions[$name];
2013
    }
2014
2015
    public function hasListFieldDescription($name)
2016
    {
2017
        $this->buildList();
2018
2019
        return \array_key_exists($name, $this->listFieldDescriptions) ? true : false;
2020
    }
2021
2022
    public function addListFieldDescription($name, FieldDescriptionInterface $fieldDescription)
2023
    {
2024
        $this->listFieldDescriptions[$name] = $fieldDescription;
2025
    }
2026
2027
    public function removeListFieldDescription($name)
2028
    {
2029
        unset($this->listFieldDescriptions[$name]);
2030
    }
2031
2032
    public function getFilterFieldDescription($name)
2033
    {
2034
        $this->buildDatagrid();
2035
2036
        if (!$this->hasFilterFieldDescription($name)) {
2037
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2038
                'Calling %s() when there is no filter field description is deprecated since'
2039
                .' sonata-project/admin-bundle 3.69 and will throw an exception in 4.0.'
2040
                .' Use %s::hasFilterFieldDescription() to know if there is a filter field description.',
2041
                __METHOD__,
2042
                __CLASS__
2043
            ), E_USER_DEPRECATED);
2044
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare FieldDescriptionInterface as return type
2045
            // throw new \LogicException(sprintf(
2046
            //    'Admin "%s" has no filter field description for the field %s.',
2047
            //    static::class,
2048
            //    $name
2049
            // ));
2050
2051
            return null;
2052
        }
2053
2054
        return $this->filterFieldDescriptions[$name];
2055
    }
2056
2057
    public function hasFilterFieldDescription($name)
2058
    {
2059
        $this->buildDatagrid();
2060
2061
        return \array_key_exists($name, $this->filterFieldDescriptions) ? true : false;
2062
    }
2063
2064
    public function addFilterFieldDescription($name, FieldDescriptionInterface $fieldDescription)
2065
    {
2066
        $this->filterFieldDescriptions[$name] = $fieldDescription;
2067
    }
2068
2069
    public function removeFilterFieldDescription($name)
2070
    {
2071
        unset($this->filterFieldDescriptions[$name]);
2072
    }
2073
2074
    public function getFilterFieldDescriptions()
2075
    {
2076
        $this->buildDatagrid();
2077
2078
        return $this->filterFieldDescriptions;
2079
    }
2080
2081
    public function addChild(AdminInterface $child)
2082
    {
2083
        $parentAdmin = $this;
2084
        while ($parentAdmin->isChild() && $parentAdmin->getCode() !== $child->getCode()) {
2085
            $parentAdmin = $parentAdmin->getParent();
2086
        }
2087
2088
        if ($parentAdmin->getCode() === $child->getCode()) {
2089
            throw new \RuntimeException(sprintf(
2090
                'Circular reference detected! The child admin `%s` is already in the parent tree of the `%s` admin.',
2091
                $child->getCode(),
2092
                $this->getCode()
2093
            ));
2094
        }
2095
2096
        $this->children[$child->getCode()] = $child;
2097
2098
        $child->setParent($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Sonata\AdminBundle\Admin\AbstractAdmin>, but the function expects a object<self>.

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...
2099
2100
        // NEXT_MAJOR: remove $args and add $field parameter to this function on next Major
2101
2102
        $args = \func_get_args();
2103
2104
        if (isset($args[1])) {
2105
            $child->addParentAssociationMapping($this->getCode(), $args[1]);
2106
        } else {
2107
            @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2108
                'Calling "addChild" without second argument is deprecated since sonata-project/admin-bundle 3.35 and will not be allowed in 4.0.',
2109
                E_USER_DEPRECATED
2110
            );
2111
        }
2112
    }
2113
2114
    public function hasChild($code)
2115
    {
2116
        return isset($this->children[$code]);
2117
    }
2118
2119
    public function getChildren()
2120
    {
2121
        return $this->children;
2122
    }
2123
2124
    public function getChild($code)
2125
    {
2126
        if (!$this->hasChild($code)) {
2127
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2128
                'Calling %s() when there is no child is deprecated since sonata-project/admin-bundle 3.69'
2129
                .' and will throw an exception in 4.0. Use %s::hasChild() to know if the child exists.',
2130
                __METHOD__,
2131
                __CLASS__
2132
            ), E_USER_DEPRECATED);
2133
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare AdminInterface as return type
2134
            // throw new \LogicException(sprintf(
2135
            //    'Admin "%s" has no child for the code %s.',
2136
            //    static::class,
2137
            //    $code
2138
            // ));
2139
2140
            return null;
2141
        }
2142
2143
        return $this->children[$code];
2144
    }
2145
2146
    public function setParent(AdminInterface $parent)
2147
    {
2148
        $this->parent = $parent;
2149
    }
2150
2151
    public function getParent()
2152
    {
2153
        if (!$this->isChild()) {
2154
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2155
                'Calling %s() when there is no parent is deprecated since sonata-project/admin-bundle 3.66'
2156
                .' and will throw an exception in 4.0. Use %s::isChild() to know if there is a parent.',
2157
                __METHOD__,
2158
                __CLASS__
2159
            ), E_USER_DEPRECATED);
2160
            // NEXT_MAJOR : remove the previous `trigger_error()` call, the `return null` statement, uncomment the following exception and declare AdminInterface as return type
2161
            // throw new \LogicException(sprintf(
2162
            //    'Admin "%s" has no parent.',
2163
            //    static::class
2164
            // ));
2165
2166
            return null;
2167
        }
2168
2169
        return $this->parent;
2170
    }
2171
2172
    final public function getRootAncestor()
2173
    {
2174
        $parent = $this;
2175
2176
        while ($parent->isChild()) {
2177
            $parent = $parent->getParent();
2178
        }
2179
2180
        return $parent;
2181
    }
2182
2183
    final public function getChildDepth()
2184
    {
2185
        $parent = $this;
2186
        $depth = 0;
2187
2188
        while ($parent->isChild()) {
2189
            $parent = $parent->getParent();
2190
            ++$depth;
2191
        }
2192
2193
        return $depth;
2194
    }
2195
2196
    final public function getCurrentLeafChildAdmin()
2197
    {
2198
        $child = $this->getCurrentChildAdmin();
2199
2200
        if (null === $child) {
2201
            return null;
2202
        }
2203
2204
        for ($c = $child; null !== $c; $c = $child->getCurrentChildAdmin()) {
2205
            $child = $c;
2206
        }
2207
2208
        return $child;
2209
    }
2210
2211
    public function isChild()
2212
    {
2213
        return $this->parent instanceof AdminInterface;
2214
    }
2215
2216
    /**
2217
     * Returns true if the admin has children, false otherwise.
2218
     *
2219
     * @return bool if the admin has children
2220
     */
2221
    public function hasChildren()
2222
    {
2223
        return \count($this->children) > 0;
2224
    }
2225
2226
    public function setUniqid($uniqid)
2227
    {
2228
        $this->uniqid = $uniqid;
2229
    }
2230
2231
    public function getUniqid()
2232
    {
2233
        if (!$this->uniqid) {
2234
            $this->uniqid = sprintf('s%s', uniqid());
2235
        }
2236
2237
        return $this->uniqid;
2238
    }
2239
2240
    /**
2241
     * Returns the classname label.
2242
     *
2243
     * @return string the classname label
2244
     */
2245
    public function getClassnameLabel()
2246
    {
2247
        return $this->classnameLabel;
2248
    }
2249
2250
    public function getPersistentParameters()
2251
    {
2252
        $parameters = [];
2253
2254
        foreach ($this->getExtensions() as $extension) {
2255
            $params = $extension->getPersistentParameters($this);
2256
2257
            if (!\is_array($params)) {
2258
                throw new \RuntimeException(sprintf(
2259
                    'The %s::getPersistentParameters must return an array',
2260
                    \get_class($extension)
2261
                ));
2262
            }
2263
2264
            $parameters = array_merge($parameters, $params);
2265
        }
2266
2267
        return $parameters;
2268
    }
2269
2270
    /**
2271
     * @param string $name
2272
     *
2273
     * @return mixed|null
2274
     */
2275
    public function getPersistentParameter($name)
2276
    {
2277
        $parameters = $this->getPersistentParameters();
2278
2279
        return $parameters[$name] ?? null;
2280
    }
2281
2282
    public function getBreadcrumbs($action)
2283
    {
2284
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2285
            'The %s method is deprecated since version 3.2 and will be removed in 4.0.'
2286
            .' Use %s::getBreadcrumbs instead.',
2287
            __METHOD__,
2288
            BreadcrumbsBuilder::class
2289
        ), E_USER_DEPRECATED);
2290
2291
        return $this->getBreadcrumbsBuilder()->getBreadcrumbs($this, $action);
2292
    }
2293
2294
    /**
2295
     * Generates the breadcrumbs array.
2296
     *
2297
     * Note: the method will be called by the top admin instance (parent => child)
2298
     *
2299
     * @param string $action
2300
     *
2301
     * @return array
2302
     */
2303
    public function buildBreadcrumbs($action, ?ItemInterface $menu = null)
2304
    {
2305
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2306
            'The %s method is deprecated since version 3.2 and will be removed in 4.0.',
2307
            __METHOD__
2308
        ), E_USER_DEPRECATED);
2309
2310
        if (isset($this->breadcrumbs[$action])) {
2311
            return $this->breadcrumbs[$action];
2312
        }
2313
2314
        return $this->breadcrumbs[$action] = $this->getBreadcrumbsBuilder()
2315
            ->buildBreadcrumbs($this, $action, $menu);
2316
    }
2317
2318
    /**
2319
     * NEXT_MAJOR : remove this method.
2320
     *
2321
     * @return BreadcrumbsBuilderInterface
2322
     */
2323
    final public function getBreadcrumbsBuilder()
2324
    {
2325
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2326
            'The %s method is deprecated since version 3.2 and will be removed in 4.0.'
2327
            .' Use the sonata.admin.breadcrumbs_builder service instead.',
2328
            __METHOD__
2329
        ), E_USER_DEPRECATED);
2330
        if (null === $this->breadcrumbsBuilder) {
2331
            $this->breadcrumbsBuilder = new BreadcrumbsBuilder(
2332
                $this->getConfigurationPool()->getContainer()->getParameter('sonata.admin.configuration.breadcrumbs')
2333
            );
2334
        }
2335
2336
        return $this->breadcrumbsBuilder;
2337
    }
2338
2339
    /**
2340
     * NEXT_MAJOR : remove this method.
2341
     *
2342
     * @return AbstractAdmin
2343
     */
2344
    final public function setBreadcrumbsBuilder(BreadcrumbsBuilderInterface $value)
2345
    {
2346
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2347
            'The %s method is deprecated since version 3.2 and will be removed in 4.0.'
2348
            .' Use the sonata.admin.breadcrumbs_builder service instead.',
2349
            __METHOD__
2350
        ), E_USER_DEPRECATED);
2351
        $this->breadcrumbsBuilder = $value;
2352
2353
        return $this;
2354
    }
2355
2356
    public function setCurrentChild($currentChild)
2357
    {
2358
        $this->currentChild = $currentChild;
2359
    }
2360
2361
    /**
2362
     * NEXT_MAJOR: Remove this method.
2363
     *
2364
     * @deprecated since sonata-project/admin-bundle 3.65, to be removed in 4.0
2365
     */
2366
    public function getCurrentChild()
2367
    {
2368
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2369
            'The %s() method is deprecated since version 3.65 and will be removed in 4.0.'
2370
            .' Use %s::isCurrentChild() instead.',
2371
            __METHOD__,
2372
            __CLASS__
2373
        ), E_USER_DEPRECATED);
2374
2375
        return $this->currentChild;
2376
    }
2377
2378
    public function isCurrentChild(): bool
2379
    {
2380
        return $this->currentChild;
2381
    }
2382
2383
    /**
2384
     * Returns the current child admin instance.
2385
     *
2386
     * @return AdminInterface|null the current child admin instance
2387
     */
2388
    public function getCurrentChildAdmin()
2389
    {
2390
        foreach ($this->children as $children) {
2391
            if ($children->isCurrentChild()) {
2392
                return $children;
2393
            }
2394
        }
2395
2396
        return null;
2397
    }
2398
2399
    public function trans($id, array $parameters = [], $domain = null, $locale = null)
2400
    {
2401
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2402
            'The %s method is deprecated since version 3.9 and will be removed in 4.0.',
2403
            __METHOD__
2404
        ), E_USER_DEPRECATED);
2405
2406
        $domain = $domain ?: $this->getTranslationDomain();
2407
2408
        return $this->translator->trans($id, $parameters, $domain, $locale);
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$translator has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2409
    }
2410
2411
    /**
2412
     * Translate a message id.
2413
     *
2414
     * NEXT_MAJOR: remove this method
2415
     *
2416
     * @param string      $id
2417
     * @param int         $count
2418
     * @param string|null $domain
2419
     * @param string|null $locale
2420
     *
2421
     * @return string the translated string
2422
     *
2423
     * @deprecated since sonata-project/admin-bundle 3.9, to be removed with 4.0
2424
     */
2425
    public function transChoice($id, $count, array $parameters = [], $domain = null, $locale = null)
2426
    {
2427
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2428
            'The %s method is deprecated since version 3.9 and will be removed in 4.0.',
2429
            __METHOD__
2430
        ), E_USER_DEPRECATED);
2431
2432
        $domain = $domain ?: $this->getTranslationDomain();
2433
2434
        return $this->translator->transChoice($id, $count, $parameters, $domain, $locale);
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$translator has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2435
    }
2436
2437
    public function setTranslationDomain($translationDomain)
2438
    {
2439
        $this->translationDomain = $translationDomain;
2440
    }
2441
2442
    public function getTranslationDomain()
2443
    {
2444
        return $this->translationDomain;
2445
    }
2446
2447
    /**
2448
     * {@inheritdoc}
2449
     *
2450
     * NEXT_MAJOR: remove this method
2451
     *
2452
     * @deprecated since sonata-project/admin-bundle 3.9, to be removed with 4.0
2453
     */
2454
    public function setTranslator(TranslatorInterface $translator)
2455
    {
2456
        $args = \func_get_args();
2457
        if (isset($args[1]) && $args[1]) {
2458
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2459
                'The %s method is deprecated since version 3.9 and will be removed in 4.0.',
2460
                __METHOD__
2461
            ), E_USER_DEPRECATED);
2462
        }
2463
2464
        $this->translator = $translator;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$translator has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2465
    }
2466
2467
    /**
2468
     * {@inheritdoc}
2469
     *
2470
     * NEXT_MAJOR: remove this method
2471
     *
2472
     * @deprecated since sonata-project/admin-bundle 3.9, to be removed with 4.0
2473
     */
2474
    public function getTranslator()
2475
    {
2476
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2477
            'The %s method is deprecated since version 3.9 and will be removed in 4.0.',
2478
            __METHOD__
2479
        ), E_USER_DEPRECATED);
2480
2481
        return $this->translator;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$translator has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2482
    }
2483
2484
    public function getTranslationLabel($label, $context = '', $type = '')
2485
    {
2486
        return $this->getLabelTranslatorStrategy()->getLabel($label, $context, $type);
2487
    }
2488
2489
    public function setRequest(Request $request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
2490
    {
2491
        $this->request = $request;
2492
2493
        foreach ($this->getChildren() as $children) {
2494
            $children->setRequest($request);
2495
        }
2496
    }
2497
2498
    public function getRequest()
2499
    {
2500
        if (!$this->request) {
2501
            // NEXT_MAJOR: Throw \LogicException instead.
2502
            throw new \RuntimeException('The Request object has not been set');
2503
        }
2504
2505
        return $this->request;
2506
    }
2507
2508
    public function hasRequest()
2509
    {
2510
        return null !== $this->request;
2511
    }
2512
2513
    public function setFormContractor(FormContractorInterface $formBuilder)
2514
    {
2515
        $this->formContractor = $formBuilder;
2516
    }
2517
2518
    /**
2519
     * @return FormContractorInterface
2520
     */
2521
    public function getFormContractor()
2522
    {
2523
        return $this->formContractor;
2524
    }
2525
2526
    public function setDatagridBuilder(DatagridBuilderInterface $datagridBuilder)
2527
    {
2528
        $this->datagridBuilder = $datagridBuilder;
2529
    }
2530
2531
    public function getDatagridBuilder()
2532
    {
2533
        return $this->datagridBuilder;
2534
    }
2535
2536
    public function setListBuilder(ListBuilderInterface $listBuilder)
2537
    {
2538
        $this->listBuilder = $listBuilder;
2539
    }
2540
2541
    public function getListBuilder()
2542
    {
2543
        return $this->listBuilder;
2544
    }
2545
2546
    public function setShowBuilder(ShowBuilderInterface $showBuilder)
2547
    {
2548
        $this->showBuilder = $showBuilder;
2549
    }
2550
2551
    /**
2552
     * @return ShowBuilderInterface
2553
     */
2554
    public function getShowBuilder()
2555
    {
2556
        return $this->showBuilder;
2557
    }
2558
2559
    public function setConfigurationPool(Pool $configurationPool)
2560
    {
2561
        $this->configurationPool = $configurationPool;
2562
    }
2563
2564
    /**
2565
     * @return Pool
2566
     */
2567
    public function getConfigurationPool()
2568
    {
2569
        return $this->configurationPool;
2570
    }
2571
2572
    public function setRouteGenerator(RouteGeneratorInterface $routeGenerator)
2573
    {
2574
        $this->routeGenerator = $routeGenerator;
2575
    }
2576
2577
    /**
2578
     * @return RouteGeneratorInterface
2579
     */
2580
    public function getRouteGenerator()
2581
    {
2582
        return $this->routeGenerator;
2583
    }
2584
2585
    public function getCode()
2586
    {
2587
        return $this->code;
2588
    }
2589
2590
    /**
2591
     * NEXT_MAJOR: Remove this function.
2592
     *
2593
     * @deprecated This method is deprecated since sonata-project/admin-bundle 3.24 and will be removed in 4.0
2594
     *
2595
     * @param string $baseCodeRoute
2596
     */
2597
    public function setBaseCodeRoute($baseCodeRoute)
2598
    {
2599
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2600
            'The %s is deprecated since 3.24 and will be removed in 4.0.',
2601
            __METHOD__
2602
        ), E_USER_DEPRECATED);
2603
2604
        $this->baseCodeRoute = $baseCodeRoute;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...ctAdmin::$baseCodeRoute has been deprecated with message: This attribute is deprecated since sonata-project/admin-bundle 3.24 and will be removed in 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2605
    }
2606
2607
    public function getBaseCodeRoute()
2608
    {
2609
        // NEXT_MAJOR: Uncomment the following lines.
2610
        // if ($this->isChild()) {
2611
        //     return sprintf('%s|%s', $this->getParent()->getBaseCodeRoute(), $this->getCode());
2612
        // }
2613
        //
2614
        // return $this->getCode();
2615
2616
        // NEXT_MAJOR: Remove all the code below.
2617
        if ($this->isChild()) {
2618
            $parentCode = $this->getParent()->getCode();
2619
2620
            if ($this->getParent()->isChild()) {
2621
                $parentCode = $this->getParent()->getBaseCodeRoute();
2622
            }
2623
2624
            return sprintf('%s|%s', $parentCode, $this->getCode());
2625
        }
2626
2627
        return $this->baseCodeRoute;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...ctAdmin::$baseCodeRoute has been deprecated with message: This attribute is deprecated since sonata-project/admin-bundle 3.24 and will be removed in 4.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2628
    }
2629
2630
    public function getModelManager()
2631
    {
2632
        return $this->modelManager;
2633
    }
2634
2635
    public function setModelManager(ModelManagerInterface $modelManager)
2636
    {
2637
        $this->modelManager = $modelManager;
2638
    }
2639
2640
    public function getManagerType()
2641
    {
2642
        return $this->managerType;
2643
    }
2644
2645
    /**
2646
     * @param string $type
2647
     */
2648
    public function setManagerType($type)
2649
    {
2650
        $this->managerType = $type;
2651
    }
2652
2653
    public function getObjectIdentifier()
2654
    {
2655
        return $this->getCode();
2656
    }
2657
2658
    /**
2659
     * Set the roles and permissions per role.
2660
     */
2661
    public function setSecurityInformation(array $information)
2662
    {
2663
        $this->securityInformation = $information;
2664
    }
2665
2666
    public function getSecurityInformation()
2667
    {
2668
        return $this->securityInformation;
2669
    }
2670
2671
    /**
2672
     * Return the list of permissions the user should have in order to display the admin.
2673
     *
2674
     * @param string $context
2675
     *
2676
     * @return array
2677
     */
2678
    public function getPermissionsShow($context)
2679
    {
2680
        switch ($context) {
2681
            case self::CONTEXT_DASHBOARD:
2682
            case self::CONTEXT_MENU:
2683
            default:
2684
                return ['LIST'];
2685
        }
2686
    }
2687
2688
    public function showIn($context)
2689
    {
2690
        switch ($context) {
2691
            case self::CONTEXT_DASHBOARD:
2692
            case self::CONTEXT_MENU:
2693
            default:
2694
                return $this->isGranted($this->getPermissionsShow($context));
0 ignored issues
show
Documentation introduced by
$this->getPermissionsShow($context) is of type array<integer,string,{"0":"string"}>, but the function expects a string.

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...
2695
        }
2696
    }
2697
2698
    public function createObjectSecurity($object)
2699
    {
2700
        $this->getSecurityHandler()->createObjectSecurity($this, $object);
2701
    }
2702
2703
    public function setSecurityHandler(SecurityHandlerInterface $securityHandler)
2704
    {
2705
        $this->securityHandler = $securityHandler;
2706
    }
2707
2708
    public function getSecurityHandler()
2709
    {
2710
        return $this->securityHandler;
2711
    }
2712
2713
    public function isGranted($name, $object = null)
2714
    {
2715
        $objectRef = $object ? sprintf('/%s#%s', spl_object_hash($object), $this->id($object)) : '';
2716
        $key = md5(json_encode($name).$objectRef);
2717
2718
        if (!\array_key_exists($key, $this->cacheIsGranted)) {
2719
            $this->cacheIsGranted[$key] = $this->securityHandler->isGranted($this, $name, $object ?: $this);
2720
        }
2721
2722
        return $this->cacheIsGranted[$key];
2723
    }
2724
2725
    public function getUrlSafeIdentifier($model)
2726
    {
2727
        return $this->getModelManager()->getUrlSafeIdentifier($model);
2728
    }
2729
2730
    public function getNormalizedIdentifier($model)
2731
    {
2732
        return $this->getModelManager()->getNormalizedIdentifier($model);
2733
    }
2734
2735
    public function id($model)
2736
    {
2737
        return $this->getNormalizedIdentifier($model);
2738
    }
2739
2740
    public function setValidator($validator)
2741
    {
2742
        // NEXT_MAJOR: Move ValidatorInterface check to method signature
2743
        if (!$validator instanceof ValidatorInterface) {
2744
            throw new \InvalidArgumentException(sprintf(
2745
                'Argument 1 must be an instance of %s',
2746
                ValidatorInterface::class
2747
            ));
2748
        }
2749
2750
        $this->validator = $validator;
2751
    }
2752
2753
    public function getValidator()
2754
    {
2755
        return $this->validator;
2756
    }
2757
2758
    public function getShow()
2759
    {
2760
        $this->buildShow();
2761
2762
        return $this->show;
2763
    }
2764
2765
    public function setFormTheme(array $formTheme)
2766
    {
2767
        $this->formTheme = $formTheme;
2768
    }
2769
2770
    public function getFormTheme()
2771
    {
2772
        return $this->formTheme;
2773
    }
2774
2775
    public function setFilterTheme(array $filterTheme)
2776
    {
2777
        $this->filterTheme = $filterTheme;
2778
    }
2779
2780
    public function getFilterTheme()
2781
    {
2782
        return $this->filterTheme;
2783
    }
2784
2785
    public function addExtension(AdminExtensionInterface $extension)
2786
    {
2787
        $this->extensions[] = $extension;
2788
    }
2789
2790
    public function getExtensions()
2791
    {
2792
        return $this->extensions;
2793
    }
2794
2795
    public function setMenuFactory(FactoryInterface $menuFactory)
2796
    {
2797
        $this->menuFactory = $menuFactory;
2798
    }
2799
2800
    public function getMenuFactory()
2801
    {
2802
        return $this->menuFactory;
2803
    }
2804
2805
    public function setRouteBuilder(RouteBuilderInterface $routeBuilder)
2806
    {
2807
        $this->routeBuilder = $routeBuilder;
2808
    }
2809
2810
    public function getRouteBuilder()
2811
    {
2812
        return $this->routeBuilder;
2813
    }
2814
2815
    public function toString($object)
2816
    {
2817
        if (!\is_object($object)) {
2818
            return '';
2819
        }
2820
2821
        if (method_exists($object, '__toString') && null !== $object->__toString()) {
2822
            return (string) $object;
2823
        }
2824
2825
        return sprintf('%s:%s', ClassUtils::getClass($object), spl_object_hash($object));
2826
    }
2827
2828
    public function setLabelTranslatorStrategy(LabelTranslatorStrategyInterface $labelTranslatorStrategy)
2829
    {
2830
        $this->labelTranslatorStrategy = $labelTranslatorStrategy;
2831
    }
2832
2833
    public function getLabelTranslatorStrategy()
2834
    {
2835
        return $this->labelTranslatorStrategy;
2836
    }
2837
2838
    public function supportsPreviewMode()
2839
    {
2840
        return $this->supportsPreviewMode;
2841
    }
2842
2843
    /**
2844
     * NEXT_MAJOR: Remove this.
2845
     *
2846
     * @deprecated since sonata-project/admin-bundle 3.67, to be removed in 4.0.
2847
     *
2848
     * Set custom per page options.
2849
     */
2850
    public function setPerPageOptions(array $options)
2851
    {
2852
        @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2853
            'The method %s is deprecated since sonata-project/admin-bundle 3.67 and will be removed in 4.0.',
2854
            __METHOD__
2855
        ), E_USER_DEPRECATED);
2856
2857
        $this->perPageOptions = $options;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$perPageOptions has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2858
    }
2859
2860
    /**
2861
     * Returns predefined per page options.
2862
     *
2863
     * @return array
2864
     */
2865
    public function getPerPageOptions()
2866
    {
2867
        // NEXT_MAJOR: Remove this line and uncomment the following
2868
        return $this->perPageOptions;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$perPageOptions has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2869
//        $perPageOptions = $this->getModelManager()->getDefaultPerPageOptions($this->class);
2870
//        $perPageOptions[] = $this->getMaxPerPage();
2871
//
2872
//        $perPageOptions = array_unique($perPageOptions);
2873
//        sort($perPageOptions);
2874
//
2875
//        return $perPageOptions;
2876
    }
2877
2878
    /**
2879
     * Set pager type.
2880
     *
2881
     * @param string $pagerType
2882
     */
2883
    public function setPagerType($pagerType)
2884
    {
2885
        $this->pagerType = $pagerType;
2886
    }
2887
2888
    /**
2889
     * Get pager type.
2890
     *
2891
     * @return string
2892
     */
2893
    public function getPagerType()
2894
    {
2895
        return $this->pagerType;
2896
    }
2897
2898
    /**
2899
     * Returns true if the per page value is allowed, false otherwise.
2900
     *
2901
     * @param int $perPage
2902
     *
2903
     * @return bool
2904
     */
2905
    public function determinedPerPageValue($perPage)
2906
    {
2907
        return \in_array($perPage, $this->getPerPageOptions(), true);
2908
    }
2909
2910
    public function isAclEnabled()
2911
    {
2912
        return $this->getSecurityHandler() instanceof AclSecurityHandlerInterface;
2913
    }
2914
2915
    public function getObjectMetadata($object)
2916
    {
2917
        return new Metadata($this->toString($object));
2918
    }
2919
2920
    public function getListModes()
2921
    {
2922
        return $this->listModes;
2923
    }
2924
2925
    public function setListMode($mode)
2926
    {
2927
        if (!$this->hasRequest()) {
2928
            throw new \RuntimeException(sprintf('No request attached to the current admin: %s', $this->getCode()));
2929
        }
2930
2931
        $this->getRequest()->getSession()->set(sprintf('%s.list_mode', $this->getCode()), $mode);
2932
    }
2933
2934
    public function getListMode()
2935
    {
2936
        if (!$this->hasRequest()) {
2937
            return 'list';
2938
        }
2939
2940
        return $this->getRequest()->getSession()->get(sprintf('%s.list_mode', $this->getCode()), 'list');
2941
    }
2942
2943
    public function getAccessMapping()
2944
    {
2945
        return $this->accessMapping;
2946
    }
2947
2948
    public function checkAccess($action, $object = null)
2949
    {
2950
        $access = $this->getAccess();
2951
2952
        if (!\array_key_exists($action, $access)) {
2953
            throw new \InvalidArgumentException(sprintf(
2954
                'Action "%s" could not be found in access mapping.'
2955
                .' Please make sure your action is defined into your admin class accessMapping property.',
2956
                $action
2957
            ));
2958
        }
2959
2960
        if (!\is_array($access[$action])) {
2961
            $access[$action] = [$access[$action]];
2962
        }
2963
2964
        foreach ($access[$action] as $role) {
2965
            if (false === $this->isGranted($role, $object)) {
2966
                throw new AccessDeniedException(sprintf('Access Denied to the action %s and role %s', $action, $role));
2967
            }
2968
        }
2969
    }
2970
2971
    /**
2972
     * Hook to handle access authorization, without throw Exception.
2973
     *
2974
     * @param string $action
2975
     * @param object $object
2976
     *
2977
     * @return bool
2978
     */
2979
    public function hasAccess($action, $object = null)
2980
    {
2981
        $access = $this->getAccess();
2982
2983
        if (!\array_key_exists($action, $access)) {
2984
            return false;
2985
        }
2986
2987
        if (!\is_array($access[$action])) {
2988
            $access[$action] = [$access[$action]];
2989
        }
2990
2991
        foreach ($access[$action] as $role) {
2992
            if (false === $this->isGranted($role, $object)) {
2993
                return false;
2994
            }
2995
        }
2996
2997
        return true;
2998
    }
2999
3000
    /**
3001
     * @param string      $action
3002
     * @param object|null $object
3003
     *
3004
     * @return array
3005
     */
3006
    public function configureActionButtons($action, $object = null)
3007
    {
3008
        $list = [];
3009
3010
        if (\in_array($action, ['tree', 'show', 'edit', 'delete', 'list', 'batch'], true)
3011
            && $this->hasAccess('create')
3012
            && $this->hasRoute('create')
3013
        ) {
3014
            $list['create'] = [
3015
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3016
                'template' => $this->getTemplate('button_create'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3017
//                'template' => $this->getTemplateRegistry()->getTemplate('button_create'),
3018
            ];
3019
        }
3020
3021
        if (\in_array($action, ['show', 'delete', 'acl', 'history'], true)
3022
            && $this->canAccessObject('edit', $object)
0 ignored issues
show
Bug introduced by
It seems like $object defined by parameter $object on line 3006 can also be of type null; however, Sonata\AdminBundle\Admin...dmin::canAccessObject() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
3023
            && $this->hasRoute('edit')
3024
        ) {
3025
            $list['edit'] = [
3026
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3027
                'template' => $this->getTemplate('button_edit'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3028
                //'template' => $this->getTemplateRegistry()->getTemplate('button_edit'),
3029
            ];
3030
        }
3031
3032
        if (\in_array($action, ['show', 'edit', 'acl'], true)
3033
            && $this->canAccessObject('history', $object)
0 ignored issues
show
Bug introduced by
It seems like $object defined by parameter $object on line 3006 can also be of type null; however, Sonata\AdminBundle\Admin...dmin::canAccessObject() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
3034
            && $this->hasRoute('history')
3035
        ) {
3036
            $list['history'] = [
3037
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3038
                'template' => $this->getTemplate('button_history'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3039
                // 'template' => $this->getTemplateRegistry()->getTemplate('button_history'),
3040
            ];
3041
        }
3042
3043
        if (\in_array($action, ['edit', 'history'], true)
3044
            && $this->isAclEnabled()
3045
            && $this->canAccessObject('acl', $object)
0 ignored issues
show
Bug introduced by
It seems like $object defined by parameter $object on line 3006 can also be of type null; however, Sonata\AdminBundle\Admin...dmin::canAccessObject() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
3046
            && $this->hasRoute('acl')
3047
        ) {
3048
            $list['acl'] = [
3049
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3050
                'template' => $this->getTemplate('button_acl'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3051
                // 'template' => $this->getTemplateRegistry()->getTemplate('button_acl'),
3052
            ];
3053
        }
3054
3055
        if (\in_array($action, ['edit', 'history', 'acl'], true)
3056
            && $this->canAccessObject('show', $object)
0 ignored issues
show
Bug introduced by
It seems like $object defined by parameter $object on line 3006 can also be of type null; however, Sonata\AdminBundle\Admin...dmin::canAccessObject() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
3057
            && \count($this->getShow()) > 0
3058
            && $this->hasRoute('show')
3059
        ) {
3060
            $list['show'] = [
3061
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3062
                'template' => $this->getTemplate('button_show'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3063
                // 'template' => $this->getTemplateRegistry()->getTemplate('button_show'),
3064
            ];
3065
        }
3066
3067
        if (\in_array($action, ['show', 'edit', 'delete', 'acl', 'batch'], true)
3068
            && $this->hasAccess('list')
3069
            && $this->hasRoute('list')
3070
        ) {
3071
            $list['list'] = [
3072
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3073
                'template' => $this->getTemplate('button_list'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3074
                // 'template' => $this->getTemplateRegistry()->getTemplate('button_list'),
3075
            ];
3076
        }
3077
3078
        return $list;
3079
    }
3080
3081
    /**
3082
     * @param string $action
3083
     * @param object $object
3084
     *
3085
     * @return array
3086
     */
3087
    public function getActionButtons($action, $object = null)
3088
    {
3089
        $list = $this->configureActionButtons($action, $object);
3090
3091
        foreach ($this->getExtensions() as $extension) {
3092
            // NEXT_MAJOR: remove method check
3093
            if (method_exists($extension, 'configureActionButtons')) {
3094
                $list = $extension->configureActionButtons($this, $list, $action, $object);
3095
            }
3096
        }
3097
3098
        return $list;
3099
    }
3100
3101
    /**
3102
     * Get the list of actions that can be accessed directly from the dashboard.
3103
     *
3104
     * @return array
3105
     */
3106
    public function getDashboardActions()
3107
    {
3108
        $actions = [];
3109
3110
        if ($this->hasRoute('create') && $this->hasAccess('create')) {
3111
            $actions['create'] = [
3112
                'label' => 'link_add',
3113
                'translation_domain' => 'SonataAdminBundle',
3114
                // NEXT_MAJOR: Remove this line and use commented line below it instead
3115
                'template' => $this->getTemplate('action_create'),
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3116
                // 'template' => $this->getTemplateRegistry()->getTemplate('action_create'),
3117
                'url' => $this->generateUrl('create'),
3118
                'icon' => 'plus-circle',
3119
            ];
3120
        }
3121
3122
        if ($this->hasRoute('list') && $this->hasAccess('list')) {
3123
            $actions['list'] = [
3124
                'label' => 'link_list',
3125
                'translation_domain' => 'SonataAdminBundle',
3126
                'url' => $this->generateUrl('list'),
3127
                'icon' => 'list',
3128
            ];
3129
        }
3130
3131
        return $actions;
3132
    }
3133
3134
    /**
3135
     * Setting to true will enable mosaic button for the admin screen.
3136
     * Setting to false will hide mosaic button for the admin screen.
3137
     *
3138
     * @param bool $isShown
3139
     */
3140
    final public function showMosaicButton($isShown)
3141
    {
3142
        if ($isShown) {
3143
            $this->listModes['mosaic'] = ['class' => static::MOSAIC_ICON_CLASS];
3144
        } else {
3145
            unset($this->listModes['mosaic']);
3146
        }
3147
    }
3148
3149
    /**
3150
     * @param object $object
3151
     */
3152
    final public function getSearchResultLink($object)
3153
    {
3154
        foreach ($this->searchResultActions as $action) {
3155
            if ($this->hasRoute($action) && $this->hasAccess($action, $object)) {
3156
                return $this->generateObjectUrl($action, $object);
3157
            }
3158
        }
3159
3160
        return null;
3161
    }
3162
3163
    /**
3164
     * Checks if a filter type is set to a default value.
3165
     *
3166
     * @param string $name
3167
     *
3168
     * @return bool
3169
     */
3170
    final public function isDefaultFilter($name)
3171
    {
3172
        $filter = $this->getFilterParameters();
3173
        $default = $this->getDefaultFilterValues();
3174
3175
        if (!\array_key_exists($name, $filter) || !\array_key_exists($name, $default)) {
3176
            return false;
3177
        }
3178
3179
        return $filter[$name] === $default[$name];
3180
    }
3181
3182
    /**
3183
     * Check object existence and access, without throw Exception.
3184
     *
3185
     * @param string $action
3186
     * @param object $object
3187
     *
3188
     * @return bool
3189
     */
3190
    public function canAccessObject($action, $object)
3191
    {
3192
        return $object && $this->id($object) && $this->hasAccess($action, $object);
3193
    }
3194
3195
    protected function configureQuery(ProxyQueryInterface $query): ProxyQueryInterface
3196
    {
3197
        return $query;
3198
    }
3199
3200
    /**
3201
     * @return MutableTemplateRegistryInterface
3202
     */
3203
    final protected function getTemplateRegistry()
3204
    {
3205
        return $this->templateRegistry;
3206
    }
3207
3208
    /**
3209
     * Returns a list of default sort values.
3210
     *
3211
     * @return array{_page?: int, _per_page?: int, _sort_by?: string, _sort_order?: string}
0 ignored issues
show
Documentation introduced by
The doc-type array{_page?: could not be parsed: Unknown type name "array{_page?:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
3212
     */
3213
    final protected function getDefaultSortValues(): array
3214
    {
3215
        $defaultSortValues = [];
3216
3217
        $this->configureDefaultSortValues($defaultSortValues);
3218
3219
        foreach ($this->getExtensions() as $extension) {
3220
            // NEXT_MAJOR: remove method check
3221
            if (method_exists($extension, 'configureDefaultSortValues')) {
3222
                $extension->configureDefaultSortValues($this, $defaultSortValues);
3223
            }
3224
        }
3225
3226
        return $defaultSortValues;
3227
    }
3228
3229
    /**
3230
     * Returns a list of default filters.
3231
     *
3232
     * @return array
3233
     */
3234
    final protected function getDefaultFilterValues()
3235
    {
3236
        $defaultFilterValues = [];
3237
3238
        $this->configureDefaultFilterValues($defaultFilterValues);
3239
3240
        foreach ($this->getExtensions() as $extension) {
3241
            // NEXT_MAJOR: remove method check
3242
            if (method_exists($extension, 'configureDefaultFilterValues')) {
3243
                $extension->configureDefaultFilterValues($this, $defaultFilterValues);
3244
            }
3245
        }
3246
3247
        return $defaultFilterValues;
3248
    }
3249
3250
    protected function configureFormFields(FormMapper $form)
3251
    {
3252
    }
3253
3254
    protected function configureListFields(ListMapper $list)
3255
    {
3256
    }
3257
3258
    protected function configureDatagridFilters(DatagridMapper $filter)
3259
    {
3260
    }
3261
3262
    protected function configureShowFields(ShowMapper $show)
3263
    {
3264
    }
3265
3266
    protected function configureRoutes(RouteCollection $collection)
3267
    {
3268
    }
3269
3270
    /**
3271
     * Allows you to customize batch actions.
3272
     *
3273
     * @param array $actions List of actions
3274
     *
3275
     * @return array
3276
     */
3277
    protected function configureBatchActions($actions)
3278
    {
3279
        return $actions;
3280
    }
3281
3282
    /**
3283
     * NEXT_MAJOR: remove this method.
3284
     *
3285
     * @deprecated Use configureTabMenu instead
3286
     */
3287
    protected function configureSideMenu(ItemInterface $menu, $action, ?AdminInterface $childAdmin = null)
0 ignored issues
show
Unused Code introduced by
The parameter $menu is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $action is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $childAdmin is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
3288
    {
3289
    }
3290
3291
    /**
3292
     * Configures the tab menu in your admin.
3293
     *
3294
     * @param string $action
3295
     */
3296
    protected function configureTabMenu(ItemInterface $menu, $action, ?AdminInterface $childAdmin = null)
3297
    {
3298
        // Use configureSideMenu not to mess with previous overrides
3299
        // NEXT_MAJOR: remove this line
3300
        $this->configureSideMenu($menu, $action, $childAdmin);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...in::configureSideMenu() has been deprecated with message: Use configureTabMenu instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3301
    }
3302
3303
    /**
3304
     * build the view FieldDescription array.
3305
     */
3306
    protected function buildShow()
3307
    {
3308
        if ($this->loaded['show']) {
3309
            return;
3310
        }
3311
3312
        $this->loaded['show'] = true;
3313
3314
        $this->show = $this->getShowBuilder()->getBaseList();
3315
        $mapper = new ShowMapper($this->getShowBuilder(), $this->show, $this);
3316
3317
        $this->configureShowFields($mapper);
3318
3319
        foreach ($this->getExtensions() as $extension) {
3320
            $extension->configureShowFields($mapper);
3321
        }
3322
    }
3323
3324
    /**
3325
     * build the list FieldDescription array.
3326
     */
3327
    protected function buildList()
3328
    {
3329
        if ($this->loaded['list']) {
3330
            return;
3331
        }
3332
3333
        $this->loaded['list'] = true;
3334
3335
        $this->list = $this->getListBuilder()->getBaseList();
3336
        $mapper = new ListMapper($this->getListBuilder(), $this->list, $this);
3337
3338
        if (\count($this->getBatchActions()) > 0 && $this->hasRequest() && !$this->getRequest()->isXmlHttpRequest()) {
3339
            $fieldDescription = $this->getModelManager()->getNewFieldDescriptionInstance(
3340
                $this->getClass(),
3341
                'batch',
3342
                [
3343
                    'label' => 'batch',
3344
                    'code' => '_batch',
3345
                    'sortable' => false,
3346
                    'virtual_field' => true,
3347
                ]
3348
            );
3349
3350
            $fieldDescription->setAdmin($this);
3351
            // NEXT_MAJOR: Remove this line and use commented line below it instead
3352
            $fieldDescription->setTemplate($this->getTemplate('batch'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3353
            // $fieldDescription->setTemplate($this->getTemplateRegistry()->getTemplate('batch'));
3354
3355
            $mapper->add($fieldDescription, ListMapper::TYPE_BATCH);
3356
        }
3357
3358
        $this->configureListFields($mapper);
3359
3360
        foreach ($this->getExtensions() as $extension) {
3361
            $extension->configureListFields($mapper);
3362
        }
3363
3364
        if ($this->hasRequest() && $this->getRequest()->isXmlHttpRequest()) {
3365
            $fieldDescription = $this->getModelManager()->getNewFieldDescriptionInstance(
3366
                $this->getClass(),
3367
                'select',
3368
                [
3369
                    'label' => false,
3370
                    'code' => '_select',
3371
                    'sortable' => false,
3372
                    'virtual_field' => false,
3373
                ]
3374
            );
3375
3376
            $fieldDescription->setAdmin($this);
3377
            // NEXT_MAJOR: Remove this line and use commented line below it instead
3378
            $fieldDescription->setTemplate($this->getTemplate('select'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3379
            // $fieldDescription->setTemplate($this->getTemplateRegistry()->getTemplate('select'));
3380
3381
            $mapper->add($fieldDescription, ListMapper::TYPE_SELECT);
3382
        }
3383
    }
3384
3385
    /**
3386
     * Build the form FieldDescription collection.
3387
     */
3388
    protected function buildForm()
3389
    {
3390
        if ($this->loaded['form']) {
3391
            return;
3392
        }
3393
3394
        $this->loaded['form'] = true;
3395
3396
        $formBuilder = $this->getFormBuilder();
3397
        $formBuilder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
3398
            $this->preValidate($event->getData());
3399
        }, 100);
3400
3401
        $this->form = $formBuilder->getForm();
0 ignored issues
show
Documentation Bug introduced by
It seems like $formBuilder->getForm() of type object<Symfony\Component\Form\FormInterface> is incompatible with the declared type object<Symfony\Component\Form\Form>|null of property $form.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
3402
    }
3403
3404
    /**
3405
     * Gets the subclass corresponding to the given name.
3406
     *
3407
     * @param string $name The name of the sub class
3408
     *
3409
     * @return string the subclass
3410
     */
3411
    protected function getSubClass($name)
3412
    {
3413
        if ($this->hasSubClass($name)) {
3414
            return $this->subClasses[$name];
3415
        }
3416
3417
        // NEXT_MAJOR: Throw \LogicException instead.
3418
        throw new \RuntimeException(sprintf('Unable to find the subclass `%s` for admin `%s`', $name, static::class));
3419
    }
3420
3421
    /**
3422
     * Attach the inline validator to the model metadata, this must be done once per admin.
3423
     */
3424
    protected function attachInlineValidator()
3425
    {
3426
        $admin = $this;
3427
3428
        // add the custom inline validation option
3429
        $metadata = $this->validator->getMetadataFor($this->getClass());
3430
        if (!$metadata instanceof GenericMetadata) {
3431
            throw new \UnexpectedValueException(
3432
                sprintf(
3433
                    'Cannot add inline validator for %s because its metadata is an instance of %s instead of %s',
3434
                    $this->getClass(),
3435
                    \get_class($metadata),
3436
                    GenericMetadata::class
3437
                )
3438
            );
3439
        }
3440
3441
        $metadata->addConstraint(new InlineConstraint([
3442
            'service' => $this,
3443
            'method' => static function (ErrorElement $errorElement, $object) use ($admin) {
3444
                /* @var \Sonata\AdminBundle\Admin\AdminInterface $admin */
3445
3446
                // This avoid the main validation to be cascaded to children
3447
                // The problem occurs when a model Page has a collection of Page as property
3448
                if ($admin->hasSubject() && spl_object_hash($object) !== spl_object_hash($admin->getSubject())) {
3449
                    return;
3450
                }
3451
3452
                $admin->validate($errorElement, $object);
3453
3454
                foreach ($admin->getExtensions() as $extension) {
3455
                    $extension->validate($admin, $errorElement, $object);
3456
                }
3457
            },
3458
            'serializingWarning' => true,
3459
        ]));
3460
    }
3461
3462
    /**
3463
     * NEXT_MAJOR: Remove this function.
3464
     *
3465
     * @deprecated since sonata-project/admin-bundle 3.67, to be removed in 4.0.
3466
     *
3467
     * Predefine per page options.
3468
     */
3469
    protected function predefinePerPageOptions()
3470
    {
3471
        array_unshift($this->perPageOptions, $this->maxPerPage);
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$perPageOptions has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tractAdmin::$maxPerPage has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3472
        $this->perPageOptions = array_unique($this->perPageOptions);
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$perPageOptions has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3473
        sort($this->perPageOptions);
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$perPageOptions has been deprecated with message: since sonata-project/admin-bundle 3.67.

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3474
    }
3475
3476
    /**
3477
     * Return list routes with permissions name.
3478
     *
3479
     * @return array<string, string>
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
3480
     */
3481
    protected function getAccess()
3482
    {
3483
        $access = array_merge([
3484
            'acl' => 'MASTER',
3485
            'export' => 'EXPORT',
3486
            'historyCompareRevisions' => 'EDIT',
3487
            'historyViewRevision' => 'EDIT',
3488
            'history' => 'EDIT',
3489
            'edit' => 'EDIT',
3490
            'show' => 'VIEW',
3491
            'create' => 'CREATE',
3492
            'delete' => 'DELETE',
3493
            'batchDelete' => 'DELETE',
3494
            'list' => 'LIST',
3495
        ], $this->getAccessMapping());
3496
3497
        foreach ($this->extensions as $extension) {
3498
            // NEXT_MAJOR: remove method check
3499
            if (method_exists($extension, 'getAccessMapping')) {
3500
                $access = array_merge($access, $extension->getAccessMapping($this));
3501
            }
3502
        }
3503
3504
        return $access;
3505
    }
3506
3507
    /**
3508
     * Configures a list of default filters.
3509
     */
3510
    protected function configureDefaultFilterValues(array &$filterValues)
3511
    {
3512
    }
3513
3514
    /**
3515
     * Configures a list of default sort values.
3516
     *
3517
     * Example:
3518
     *   $sortValues['_sort_by'] = 'foo'
3519
     *   $sortValues['_sort_order'] = 'DESC'
3520
     */
3521
    protected function configureDefaultSortValues(array &$sortValues)
0 ignored issues
show
Unused Code introduced by
The parameter $sortValues is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
3522
    {
3523
    }
3524
3525
    /**
3526
     * Set the parent object, if any, to the provided object.
3527
     */
3528
    final protected function appendParentObject(object $object): void
3529
    {
3530
        if ($this->isChild() && $this->getParentAssociationMapping()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getParentAssociationMapping() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
3531
            $parentAdmin = $this->getParent();
3532
            $parentObject = $parentAdmin->getObject($this->request->get($parentAdmin->getIdParameter()));
3533
3534
            if (null !== $parentObject) {
3535
                $propertyAccessor = $this->getConfigurationPool()->getPropertyAccessor();
3536
                $propertyPath = new PropertyPath($this->getParentAssociationMapping());
3537
3538
                $value = $propertyAccessor->getValue($object, $propertyPath);
3539
3540
                if (\is_array($value) || $value instanceof \ArrayAccess) {
3541
                    $value[] = $parentObject;
3542
                    $propertyAccessor->setValue($object, $propertyPath, $value);
3543
                } else {
3544
                    $propertyAccessor->setValue($object, $propertyPath, $parentObject);
3545
                }
3546
            }
3547
        } elseif ($this->hasParentFieldDescription()) {
3548
            $parentAdmin = $this->getParentFieldDescription()->getAdmin();
3549
            $parentObject = $parentAdmin->getObject($this->request->get($parentAdmin->getIdParameter()));
3550
3551
            if (null !== $parentObject) {
3552
                ObjectManipulator::setObject($object, $parentObject, $this->getParentFieldDescription());
0 ignored issues
show
Bug introduced by
It seems like $this->getParentFieldDescription() can be null; however, setObject() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
3553
            }
3554
        }
3555
    }
3556
3557
    /**
3558
     * Build all the related urls to the current admin.
3559
     */
3560
    private function buildRoutes(): void
3561
    {
3562
        if ($this->loaded['routes']) {
3563
            return;
3564
        }
3565
3566
        $this->loaded['routes'] = true;
3567
3568
        $this->routes = new RouteCollection(
3569
            $this->getBaseCodeRoute(),
3570
            $this->getBaseRouteName(),
3571
            $this->getBaseRoutePattern(),
3572
            $this->getBaseControllerName()
3573
        );
3574
3575
        $this->routeBuilder->build($this, $this->routes);
3576
3577
        $this->configureRoutes($this->routes);
3578
3579
        foreach ($this->getExtensions() as $extension) {
3580
            $extension->configureRoutes($this, $this->routes);
3581
        }
3582
    }
3583
}
3584
3585
class_exists(\Sonata\Form\Validator\ErrorElement::class);
3586