Passed
Push — master ( cc4e78...1262d4 )
by Damian
04:08
created

SearchFacetsType::buildForm()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 18
rs 9.7998
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusElasticsearchPlugin\Form\Type;
6
7
use BitBag\SyliusElasticsearchPlugin\Facet\RegistryInterface;
8
use BitBag\SyliusElasticsearchPlugin\Model\SearchFacets;
9
use Symfony\Component\Form\AbstractType;
10
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
11
use Symfony\Component\Form\FormBuilderInterface;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
14
final class SearchFacetsType extends AbstractType
15
{
16
    /** @var RegistryInterface */
17
    private $facetRegistry;
18
19
    public function __construct(RegistryInterface $facetRegistry)
20
    {
21
        $this->facetRegistry = $facetRegistry;
22
    }
23
24
    public function buildForm(FormBuilderInterface $builder, array $options): void
25
    {
26
        foreach ($options['facets'] as $facetId => $facetData) {
27
            $facet = $this->facetRegistry->getFacetById($facetId);
28
            $choices = [];
29
            foreach ($facetData['buckets'] as $bucket) {
30
                $choices[$facet->getBucketLabel($bucket)] = $bucket['key'];
31
            }
32
            if (!empty($choices)) {
33
                $builder
34
                    ->add(
35
                        $facetId,
36
                        ChoiceType::class,
37
                        [
38
                            'label' => $facet->getLabel(),
39
                            'choices' => $choices,
40
                            'expanded' => true,
41
                            'multiple' => true,
42
                        ]
43
                    )
44
                ;
45
            }
46
        }
47
    }
48
49
    public function configureOptions(OptionsResolver $resolver): void
50
    {
51
        $resolver->setRequired('facets');
52
        $resolver->setDefault('data_class', SearchFacets::class);
53
    }
54
}
55