-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
AbstractAdmin.php
4016 lines (3452 loc) · 121 KB
/
AbstractAdmin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Admin;
use Doctrine\Common\Util\ClassUtils;
use Knp\Menu\ItemInterface;
use Sonata\AdminBundle\Datagrid\DatagridInterface;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\DependencyInjection\Admin\AbstractTaggedAdmin;
use Sonata\AdminBundle\Exception\AdminClassNotFoundException;
use Sonata\AdminBundle\Exporter\DataSourceInterface;
use Sonata\AdminBundle\FieldDescription\FieldDescriptionCollection;
use Sonata\AdminBundle\FieldDescription\FieldDescriptionInterface;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Form\Type\ModelHiddenType;
use Sonata\AdminBundle\Manipulator\ObjectManipulator;
use Sonata\AdminBundle\Object\Metadata;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface;
// NEXT_MAJOR: Uncomment next line.
// use Sonata\AdminBundle\Util\Instantiator;
use Sonata\AdminBundle\Util\ParametersManipulator;
use Sonata\Form\Validator\Constraints\InlineConstraint;
use Sonata\Form\Validator\ErrorElement;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PropertyAccess\Exception\AccessException;
use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface as RoutingUrlGeneratorInterface;
use Symfony\Component\Security\Acl\Model\DomainObjectInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Validator\Mapping\GenericMetadata;
/**
* @author Thomas Rabaix <[email protected]>
*
* @phpstan-import-type FieldDescriptionOptions from FieldDescriptionInterface
*
* @phpstan-template T of object
* @phpstan-extends AbstractTaggedAdmin<T>
* @phpstan-implements AdminInterface<T>
*/
abstract class AbstractAdmin extends AbstractTaggedAdmin implements AdminInterface, DomainObjectInterface, AdminTreeInterface
{
public const CONTEXT_MENU = 'menu';
public const CONTEXT_DASHBOARD = 'dashboard';
public const CLASS_REGEX =
'@
(?:([A-Za-z0-9]*)\\\)? # vendor name / app name
(Bundle\\\)? # optional bundle directory
([A-Za-z0-9]+?)(?:Bundle)?\\\ # bundle name, with optional suffix
(
Entity|Document|Model|PHPCR|CouchDocument|Phpcr|
Doctrine\\\Orm|Doctrine\\\Phpcr|Doctrine\\\MongoDB|Doctrine\\\CouchDB
)\\\(.*)@x';
private const ACTION_TREE = 1;
private const ACTION_SHOW = 2;
private const ACTION_EDIT = 4;
private const ACTION_DELETE = 8;
private const ACTION_ACL = 16;
private const ACTION_HISTORY = 32;
private const ACTION_LIST = 64;
private const ACTION_BATCH = 128;
private const INTERNAL_ACTIONS = [
'tree' => self::ACTION_TREE,
'show' => self::ACTION_SHOW,
'edit' => self::ACTION_EDIT,
'delete' => self::ACTION_DELETE,
'acl' => self::ACTION_ACL,
'history' => self::ACTION_HISTORY,
'list' => self::ACTION_LIST,
'batch' => self::ACTION_BATCH,
];
private const MASK_OF_ACTION_CREATE = self::ACTION_TREE | self::ACTION_SHOW | self::ACTION_EDIT | self::ACTION_DELETE | self::ACTION_LIST | self::ACTION_BATCH;
private const MASK_OF_ACTION_SHOW = self::ACTION_EDIT | self::ACTION_HISTORY | self::ACTION_ACL;
private const MASK_OF_ACTION_EDIT = self::ACTION_SHOW | self::ACTION_DELETE | self::ACTION_ACL | self::ACTION_HISTORY;
private const MASK_OF_ACTION_HISTORY = self::ACTION_SHOW | self::ACTION_EDIT | self::ACTION_ACL;
private const MASK_OF_ACTION_ACL = self::ACTION_EDIT | self::ACTION_HISTORY;
private const MASK_OF_ACTION_LIST = self::ACTION_SHOW | self::ACTION_EDIT | self::ACTION_DELETE | self::ACTION_ACL | self::ACTION_BATCH;
private const MASK_OF_ACTIONS_USING_OBJECT = self::MASK_OF_ACTION_SHOW | self::MASK_OF_ACTION_EDIT | self::MASK_OF_ACTION_HISTORY | self::MASK_OF_ACTION_ACL;
private const DEFAULT_LIST_PER_PAGE_RESULTS = 32;
private const DEFAULT_LIST_PER_PAGE_OPTIONS = [16, 32, 64, 128, 256];
/**
* The list FieldDescription constructed from the configureListField method.
*
* @var array<string, FieldDescriptionInterface>
*/
protected $listFieldDescriptions = [];
/**
* The show FieldDescription constructed from the configureShowFields method.
*
* @var FieldDescriptionInterface[]
*/
protected $showFieldDescriptions = [];
/**
* The list FieldDescription constructed from the configureFormField method.
*
* @var FieldDescriptionInterface[]
*/
protected $formFieldDescriptions = [];
/**
* The filter FieldDescription constructed from the configureFilterField method.
*
* @var FieldDescriptionInterface[]
*/
protected $filterFieldDescriptions = [];
/**
* NEXT_MAJOR: Remove this property.
*
* The number of result to display in the list.
*
* @deprecated since sonata-project/admin-bundle 3.67.
*
* @var int
*/
protected $maxPerPage = self::DEFAULT_LIST_PER_PAGE_RESULTS;
/**
* The maximum number of page numbers to display in the list.
*
* @var int
*/
protected $maxPageLinks = 25;
/**
* The base route name used to generate the routing information.
*
* @var string|null
*/
protected $baseRouteName;
/**
* The base route pattern used to generate the routing information.
*
* @var string|null
*/
protected $baseRoutePattern;
/**
* The label class name (used in the title/breadcrumb ...).
*
* @var string|null
*/
protected $classnameLabel;
/**
* The translation domain to be used to translate messages.
*
* @var string
*/
protected $translationDomain = 'messages';
/**
* Options to set to the form (ie, validation_groups).
*
* @deprecated since sonata-project/admin-bundle 3.89, use configureFormOptions() instead.
*
* @var array<string, mixed>
*/
protected $formOptions = [];
/**
* NEXT_MAJOR: Remove this property.
*
* Default values to the datagrid.
*
* @deprecated since sonata-project/admin-bundle 3.67, use configureDefaultSortValues() instead.
*
* @var array
*/
protected $datagridValues = [
DatagridInterface::PAGE => 1,
DatagridInterface::PER_PAGE => self::DEFAULT_LIST_PER_PAGE_RESULTS,
];
/**
* NEXT_MAJOR: Remove this property.
*
* Predefined per page options.
*
* @deprecated since sonata-project/admin-bundle 3.67.
*
* @var array
*/
protected $perPageOptions = self::DEFAULT_LIST_PER_PAGE_OPTIONS;
/**
* Array of routes related to this admin.
*
* @var RouteCollection|null
*/
protected $routes;
/**
* The subject only set in edit/update/create mode.
*
* @var object|null
*
* @phpstan-var T|null
*/
protected $subject;
/**
* Define a Collection of child admin, ie /admin/order/{id}/order-element/{childId}.
*
* @var array<string, AdminInterface>
*/
protected $children = [];
/**
* Reference the parent admin.
*
* @var AdminInterface|null
*/
protected $parent;
/**
* The base code route refer to the prefix used to generate the route name.
*
* NEXT_MAJOR: remove this attribute.
*
* @deprecated This attribute is deprecated since sonata-project/admin-bundle 3.24 and will be removed in 4.0
*
* @var string
*/
protected $baseCodeRoute = '';
/**
* NEXT_MAJOR: should be default array and private.
*
* @var array<string, mixed>|string|null
*/
protected $parentAssociationMapping;
/**
* Reference the parent FieldDescription related to this admin
* only set for FieldDescription which is associated to an Sub Admin instance.
*
* @var FieldDescriptionInterface|null
*/
protected $parentFieldDescription;
/**
* If true then the current admin is part of the nested admin set (from the url).
*
* @var bool
*/
protected $currentChild = false;
/**
* NEXT_MAJOR: Rename $uniqId.
*
* The uniqId is used to avoid clashing with 2 admin related to the code
* ie: a Block linked to a Block.
*
* @var string|null
*/
protected $uniqid;
/**
* The current request object.
*
* @var Request|null
*/
protected $request;
/**
* The datagrid instance.
*
* @var DatagridInterface|null
*/
protected $datagrid;
/**
* The generated breadcrumbs.
*
* NEXT_MAJOR : remove this property
*
* @var array<string, ItemInterface|null>
*/
protected $breadcrumbs = [];
/**
* @var ItemInterface|null
*/
protected $menu;
/**
* @var array<string, bool>
*/
protected $loaded = [
'view_fields' => false, // NEXT_MAJOR: Remove this unused value.
'view_groups' => false, // NEXT_MAJOR: Remove this unused value.
'routes' => false,
'tab_menu' => false,
'show' => false,
'list' => false,
'form' => false,
'datagrid' => false,
];
/**
* @var string[]
*/
protected $formTheme = [];
/**
* @var string[]
*/
protected $filterTheme = [];
/**
* @var array<string, string>
*
* @deprecated since sonata-project/admin-bundle 3.34, will be dropped in 4.0. Use TemplateRegistry services instead
*/
protected $templates = [];
/**
* @var AdminExtensionInterface[]
*/
protected $extensions = [];
/**
* Setting to true will enable preview mode for
* the entity and show a preview button in the
* edit/create forms.
*
* @var bool
*/
protected $supportsPreviewMode = false;
/**
* @var array<string, bool>
*/
protected $cacheIsGranted = [];
/**
* Action list for the search result.
*
* @var string[]
*/
protected $searchResultActions = ['edit', 'show'];
/**
* The Access mapping.
*
* @var array<string, string|string[]> [action1 => requiredRole1, action2 => [requiredRole2, requiredRole3]]
*/
protected $accessMapping = [];
/**
* @var MutableTemplateRegistryInterface|null
*/
private $templateRegistry;
/**
* The subclasses supported by the admin class.
*
* @var array<string, string>
*/
private $subClasses = [];
/**
* The list collection.
*
* @var FieldDescriptionCollection|null
*/
private $list;
/**
* @var FieldDescriptionCollection|null
*/
private $show;
/**
* @var FormInterface|null
*/
private $form;
/**
* The cached base route name.
*
* @var string|null
*/
private $cachedBaseRouteName;
/**
* The cached base route pattern.
*
* @var string|null
*/
private $cachedBaseRoutePattern;
/**
* The form group disposition.
*
* NEXT_MAJOR: must have `[]` as default value and remove the possibility to
* hold boolean values.
*
* @var array|bool
*/
private $formGroups = false;
/**
* The form tabs disposition.
*
* NEXT_MAJOR: must have `[]` as default value and remove the possibility to
* hold boolean values.
*
* @var array|bool
*/
private $formTabs = false;
/**
* The view group disposition.
*
* NEXT_MAJOR: must have `[]` as default value and remove the possibility to
* hold boolean values.
*
* @var array|bool
*/
private $showGroups = false;
/**
* The view tab disposition.
*
* NEXT_MAJOR: must have `[]` as default value and remove the possibility to
* hold boolean values.
*
* @var array|bool
*/
private $showTabs = false;
/**
* The breadcrumbsBuilder component.
*
* @var BreadcrumbsBuilderInterface|null
*/
private $breadcrumbsBuilder;
/**
* NEXT_MAJOR: Remove the construct override.
*
* @phpstan-param class-string<T> $class
*/
public function __construct($code, $class, $baseControllerName = null)
{
parent::__construct($code, $class, $baseControllerName);
// NEXT_MAJOR: Remove this line.
$this->predefinePerPageOptions();
// NEXT_MAJOR: Remove this line.
$this->datagridValues[DatagridInterface::PER_PAGE] = $this->maxPerPage;
}
/**
* {@inheritdoc}
*/
public function getExportFormats()
{
return [
'json', 'xml', 'csv', 'xls',
];
}
/**
* @final since sonata-project/admin-bundle 3.76
*
* @return string[]
*/
public function getExportFields()
{
$fields = $this->configureExportFields();
foreach ($this->getExtensions() as $extension) {
if (method_exists($extension, 'configureExportFields')) {
$fields = $extension->configureExportFields($this, $fields);
}
}
return $fields;
}
/**
* @final since sonata-project/admin-bundle 3.102.
*/
public function getDataSourceIterator()
{
$datagrid = $this->getDatagrid();
$datagrid->buildPager();
$fields = [];
foreach ($this->getExportFields() as $key => $field) {
// NEXT_MAJOR: Remove the following code in favor of the commented one.
$label = $this->getTranslationLabel($field, 'export', 'label');
$transLabel = $this->getTranslator()->trans($label, [], $this->getTranslationDomain());
if ($transLabel === $label) {
$fields[$key] = $field;
} else {
$fields[$transLabel] = $field;
}
// if (!\is_string($key)) {
// $label = $this->getTranslationLabel($field, 'export', 'label');
// $key = $this->getTranslator()->trans($label, [], $this->getTranslationDomain());
// }
//
// $fields[$key] = $field;
}
if ($this->getDataSource()) {
$query = $datagrid->getQuery();
return $this->getDataSource()->createIterator($query, $fields);
}
@trigger_error(sprintf(
'Using "%s()" without setting a "%s" instance in the admin is deprecated since sonata-project/admin-bundle 3.79'
.' and won\'t be possible in 4.0.',
__METHOD__,
DataSourceInterface::class
), \E_USER_DEPRECATED);
return $this->getModelManager()->getDataSourceIterator($datagrid, $fields);
}
/**
* NEXT_MAJOR: Remove this method.
*
* @deprecated since sonata-project/admin-bundle 3.82, use configureFormOptions() to set $formOptions['constraints'] instead.
*/
public function validate(ErrorElement $errorElement, $object)
{
if ('sonata_deprecation_mute' !== (\func_get_args()[2] ?? null)) {
@trigger_error(sprintf(
'The %s method is deprecated since version 3.82 and will be removed in 4.0.',
__METHOD__
), \E_USER_DEPRECATED);
}
}
/**
* @final since sonata-admin/admin-bundle 3.84
*/
public function initialize()
{
if (!$this->classnameLabel) {
/* NEXT_MAJOR: remove cast to string, null is not supposed to be
supported but was documented as such */
$this->classnameLabel = substr(
(string) $this->getClass(),
strrpos((string) $this->getClass(), '\\') + 1
);
}
// NEXT_MAJOR: Remove this line.
$this->baseCodeRoute = $this->getCode();
$this->configure();
foreach ($this->getExtensions() as $extension) {
// NEXT_MAJOR: remove method_exists check
if (method_exists($extension, 'configure')) {
$extension->configure($this);
}
}
}
/**
* NEXT_MAJOR: Restrict visibility to protected.
*/
public function configure()
{
}
public function update($object)
{
$this->preUpdate($object);
foreach ($this->getExtensions() as $extension) {
$extension->preUpdate($this, $object);
}
$result = $this->getModelManager()->update($object);
// BC compatibility
if (null !== $result) {
$object = $result;
}
$this->postUpdate($object);
foreach ($this->getExtensions() as $extension) {
$extension->postUpdate($this, $object);
}
return $object;
}
/**
* @final since sonata-project/admin-bundle 3.102.
*/
public function create($object)
{
$this->prePersist($object);
foreach ($this->getExtensions() as $extension) {
$extension->prePersist($this, $object);
}
$result = $this->getModelManager()->create($object);
// BC compatibility
if (null !== $result) {
$object = $result;
}
$this->postPersist($object);
foreach ($this->getExtensions() as $extension) {
$extension->postPersist($this, $object);
}
$this->createObjectSecurity($object);
return $object;
}
/**
* @final since sonata-project/admin-bundle 3.102.
*/
public function delete($object)
{
$this->preRemove($object);
foreach ($this->getExtensions() as $extension) {
$extension->preRemove($this, $object);
}
$this->getSecurityHandler()->deleteObjectSecurity($this, $object);
$this->getModelManager()->delete($object);
$this->postRemove($object);
foreach ($this->getExtensions() as $extension) {
$extension->postRemove($this, $object);
}
}
/**
* NEXT_MAJOR: Change visibility to protected.
*
* @param object $object
*
* @phpstan-param T $object
*/
public function preValidate($object)
{
}
public function preUpdate($object)
{
}
public function postUpdate($object)
{
}
public function prePersist($object)
{
}
public function postPersist($object)
{
}
public function preRemove($object)
{
}
public function postRemove($object)
{
}
public function preBatchAction($actionName, ProxyQueryInterface $query, array &$idx, $allElements)
{
}
final public function getDefaultFilterParameters(): array
{
return array_merge(
/* @phpstan-ignore-next-line */
$this->getModelManager()->getDefaultSortValues($this->getClass(), 'sonata_deprecation_mute'), // NEXT_MAJOR: Remove this line.
$this->datagridValues, // NEXT_MAJOR: Remove this line.
$this->getDefaultSortValues(),
$this->getDefaultFilterValues()
);
}
/**
* @final since sonata-project/admin-bundle 3.102.
*
* @return array<string, mixed>
*/
public function getFilterParameters()
{
$parameters = $this->getDefaultFilterParameters();
// build the values array
if ($this->hasRequest()) {
/** @var InputBag|ParameterBag $bag */
$bag = $this->getRequest()->query;
if ($bag instanceof InputBag) {
// symfony 5.1+
$filters = $bag->all('filter');
} else {
$filters = $bag->get('filter', []);
}
if (isset($filters[DatagridInterface::PAGE])) {
$filters[DatagridInterface::PAGE] = (int) $filters[DatagridInterface::PAGE];
}
if (isset($filters[DatagridInterface::PER_PAGE])) {
$filters[DatagridInterface::PER_PAGE] = (int) $filters[DatagridInterface::PER_PAGE];
}
// if filter persistence is configured
// NEXT_MAJOR: remove `$this->persistFilters !== false` from the condition
if (false !== $this->persistFilters && $this->hasFilterPersister()) {
// if reset filters is asked, remove from storage
if ('reset' === $this->getRequest()->query->get('filters')) {
$this->getFilterPersister()->reset($this->getCode());
}
// if no filters, fetch from storage
// otherwise save to storage
if (empty($filters)) {
$filters = $this->getFilterPersister()->get($this->getCode());
} else {
$this->getFilterPersister()->set($this->getCode(), $filters);
}
}
$parameters = ParametersManipulator::merge($parameters, $filters);
// always force the parent value
if ($this->isChild() && $this->getParentAssociationMapping()) {
$name = str_replace('.', '__', $this->getParentAssociationMapping());
$parameters[$name] = ['value' => $this->getRequest()->get($this->getParent()->getIdParameter())];
}
}
if (!isset($parameters[DatagridInterface::PER_PAGE]) || !$this->determinedPerPageValue($parameters[DatagridInterface::PER_PAGE])) {
$parameters[DatagridInterface::PER_PAGE] = $this->getMaxPerPage();
}
$parameters = $this->configureFilterParameters($parameters);
foreach ($this->getExtensions() as $extension) {
// NEXT_MAJOR: remove method_exists check
if (method_exists($extension, 'configureFilterParameters')) {
$parameters = $extension->configureFilterParameters($this, $parameters);
}
}
return $parameters;
}
/**
* NEXT_MAJOR: Change the visibility to private.
*/
public function buildDatagrid()
{
if ('sonata_deprecation_mute' !== (\func_get_args()[0] ?? null)) {
@trigger_error(sprintf(
'The %s() method is deprecated since sonata-project/admin-bundle 3.92'
.' and will become private in version 4.0.',
__METHOD__
), \E_USER_DEPRECATED);
}
if ($this->loaded['datagrid']) {
return;
}
$this->loaded['datagrid'] = true;
$filterParameters = $this->getFilterParameters();
// transform DatagridInterface::SORT_BY from a string to a FieldDescriptionInterface for the datagrid.
if (isset($filterParameters[DatagridInterface::SORT_BY]) && \is_string($filterParameters[DatagridInterface::SORT_BY])) {
if ($this->hasListFieldDescription($filterParameters[DatagridInterface::SORT_BY])) {
$filterParameters[DatagridInterface::SORT_BY] = $this->getListFieldDescription($filterParameters[DatagridInterface::SORT_BY]);
} else {
$filterParameters[DatagridInterface::SORT_BY] = $this->createFieldDescription(
$filterParameters[DatagridInterface::SORT_BY]
);
$this->getListBuilder()->buildField(null, $filterParameters[DatagridInterface::SORT_BY], $this);
}
}
// initialize the datagrid
$this->datagrid = $this->getDatagridBuilder()->getBaseDatagrid($this, $filterParameters);
$this->datagrid->getPager()->setMaxPageLinks($this->getMaxPageLinks());
$mapper = new DatagridMapper($this->getDatagridBuilder(), $this->datagrid, $this);
// build the datagrid filter
$this->configureDatagridFilters($mapper);
// ok, try to limit to add parent filter
if ($this->isChild() && $this->getParentAssociationMapping() && !$mapper->has($this->getParentAssociationMapping())) {
$mapper->add($this->getParentAssociationMapping(), null, [
'show_filter' => false,
'label' => false,
'field_type' => ModelHiddenType::class,
'field_options' => [
'model_manager' => $this->getModelManager(),
],
'operator_type' => HiddenType::class,
], [
'admin_code' => $this->getParent()->getCode(),
]);
}
foreach ($this->getExtensions() as $extension) {
$extension->configureDatagridFilters($mapper);
}
}
/**
* @final since sonata-project/admin-bundle 3.102.
*
* Returns the name of the parent related field, so the field can be use to set the default
* value (ie the parent object) or to filter the object.
*
* @throws \LogicException
*
* @return string|null
*/
public function getParentAssociationMapping()
{
if (!$this->isChild()) {
// NEXT_MAJOR: Uncomment the exception.
@trigger_error(sprintf(
'Calling %s() when the admin is not a child admin is deprecated since sonata-project/admin-bundle 3.103'
.' and will throw a %s exception in 4.0.',
__METHOD__,
\LogicException::class
), \E_USER_DEPRECATED);
// throw new \LogicException(sprintf(
// 'Admin "%s" has no parent.',
// static::class
// ));
return $this->parentAssociationMapping;
}
$parent = $this->getParent()->getCode();
// NEXT_MAJOR: remove this.
if (!\is_array($this->parentAssociationMapping)) {
return $this->parentAssociationMapping;
}
// NEXT_MAJOR: Return $this->parentAssociationMapping[$parent] without checks.
if (\array_key_exists($parent, $this->parentAssociationMapping)) {
return $this->parentAssociationMapping[$parent];
}
// NEXT_MAJOR: Remove this exception
throw new \InvalidArgumentException(sprintf(
'There\'s no association between "%s" and "%s".',
$this->getCode(),
$this->getParent()->getCode()
));
}
/**
* NEXT_MAJOR: Remove this method.
*
* @deprecated since sonata-project/admin-bundle 3.103 and will be removed in 4.0.
*
* @param string $code
* @param string $value
*/
final public function addParentAssociationMapping($code, $value)
{
if (\is_string($this->parentAssociationMapping)) {
@trigger_error(sprintf(
'Calling "%s" when $this->parentAssociationMapping is string is deprecated since sonata-project/admin-bundle 3.75 and will be removed in 4.0.',
__METHOD__
), \E_USER_DEPRECATED);
}
@trigger_error(sprintf(
'Method "%s()" is deprecated since sonata-project/admin-bundle 3.103 and will be removed in 4.0.',
__METHOD__
), \E_USER_DEPRECATED);
$this->parentAssociationMapping[$code] = $value;
}
/**
* @final since sonata-project/admin-bundle 3.102.
*
* Returns the baseRoutePattern used to generate the routing information.
*
* @throws \RuntimeException // NEXT_MAJOR: Remove this tag
*
* @return string the baseRoutePattern used to generate the routing information
*/
public function getBaseRoutePattern()
{
if (null !== $this->cachedBaseRoutePattern) {
return $this->cachedBaseRoutePattern;
}
if ($this->isChild()) { // the admin class is a child, prefix it with the parent route pattern
$baseRoutePattern = $this->baseRoutePattern;
if (!$this->baseRoutePattern) {
preg_match(self::CLASS_REGEX, $this->class, $matches);
if (!$matches) {
// NEXT_MAJOR: Throw \LogicException instead
throw new \RuntimeException(sprintf(
'Please define a default `baseRoutePattern` value for the admin class `%s`',
static::class
));
}
$baseRoutePattern = $this->urlize($matches[5], '-');
}
$this->cachedBaseRoutePattern = sprintf(
'%s/%s/%s',
$this->getParent()->getBaseRoutePattern(),
$this->getParent()->getRouterIdParameter(),
$baseRoutePattern
);
} elseif ($this->baseRoutePattern) {
$this->cachedBaseRoutePattern = $this->baseRoutePattern;
} else {
preg_match(self::CLASS_REGEX, $this->class, $matches);
if (!$matches) {
// NEXT_MAJOR: Throw \LogicException instead
throw new \RuntimeException(sprintf(
'Please define a default `baseRoutePattern` value for the admin class `%s`',
static::class
));
}
$this->cachedBaseRoutePattern = sprintf(
'/%s%s/%s',
empty($matches[1]) ? '' : $this->urlize($matches[1], '-').'/',
$this->urlize($matches[3], '-'),
$this->urlize($matches[5], '-')
);
}
return $this->cachedBaseRoutePattern;
}
/**
* @final since sonata-project/admin-bundle 3.102.
*
* Returns the baseRouteName used to generate the routing information.
*
* @throws \RuntimeException // NEXT_MAJOR: Remove this tag
*
* @return string the baseRouteName used to generate the routing information
*/
public function getBaseRouteName()
{