forked from sonata-project/SonataClassificationBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionFilter.php
More file actions
105 lines (88 loc) · 2.8 KB
/
CollectionFilter.php
File metadata and controls
105 lines (88 loc) · 2.8 KB
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
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\ClassificationBundle\Admin\Filter;
use Sonata\AdminBundle\Filter\Model\FilterData;
use Sonata\AdminBundle\Form\Type\Filter\DefaultType;
use Sonata\ClassificationBundle\Model\CollectionManagerInterface;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\DoctrineORMAdminBundle\Filter\Filter;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
final class CollectionFilter extends Filter
{
public function __construct(private CollectionManagerInterface $collectionManager)
{
}
public function filter(ProxyQueryInterface $query, string $alias, string $field, FilterData $data): void
{
if (!$data->hasValue() || null === $data->getValue()) {
return;
}
$query
->getQueryBuilder()
->andWhere(\sprintf('%s.%s = :collection', $alias, $field))
->setParameter('collection', $data->getValue());
$this->setActive(true);
}
public function getDefaultOptions(): array
{
return [
'context' => null,
'field_type' => ChoiceType::class,
];
}
/**
* @return array<string, mixed>
*/
public function getFormOptions(): array
{
return [
'field_type' => $this->getFieldType(),
'field_options' => $this->getOption('choices', [
'choices' => $this->getChoices(),
'choice_translation_domain' => false,
]),
'label' => $this->getLabel(),
];
}
/**
* NEXT_MAJOR: Remove this method.
*/
public function getRenderSettings(): array
{
return [DefaultType::class, [
'field_type' => $this->getFieldType(),
'field_options' => $this->getOption('choices', [
'choices' => $this->getChoices(),
'choice_translation_domain' => false,
]),
'label' => $this->getLabel(),
]];
}
/**
* @return array<string, int|string>
*/
private function getChoices(): array
{
$contextId = $this->getOption('context');
if (null === $contextId) {
$collections = $this->collectionManager->findAll();
} else {
$collections = $this->collectionManager->getByContext($contextId);
}
$choices = [];
foreach ($collections as $collection) {
$id = $collection->getId();
\assert(null !== $id);
$choices[(string) $collection] = $id;
}
return $choices;
}
}