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

SearchFormEventListener::onBlockEvent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 16
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitBag\SyliusElasticsearchPlugin\Block;
6
7
use BitBag\SyliusElasticsearchPlugin\Form\Type\SearchType;
8
use BitBag\SyliusElasticsearchPlugin\Model\Search;
9
use Sonata\BlockBundle\Event\BlockEvent;
10
use Sonata\BlockBundle\Model\Block;
11
use Symfony\Component\Form\FormFactoryInterface;
12
use Symfony\Component\Form\FormInterface;
13
use Symfony\Component\Routing\RouterInterface;
14
15
final class SearchFormEventListener
16
{
17
    /** @var string */
18
    private $template;
19
20
    /** @var FormFactoryInterface */
21
    private $formFactory;
22
23
    /** @var RouterInterface */
24
    private $router;
25
26
    /** @var FormInterface */
27
    private $form;
28
29
    public function __construct(string $template, FormFactoryInterface $formFactory, RouterInterface $router)
30
    {
31
        $this->template = $template;
32
        $this->formFactory = $formFactory;
33
        $this->router = $router;
34
    }
35
36
    public function onBlockEvent(BlockEvent $event): void
37
    {
38
        $block = new Block();
39
        $block->setId(uniqid('', true));
40
        $block->setSettings(
41
            array_replace(
42
                $event->getSettings(),
43
                [
44
                    'template' => $this->template,
45
                    'form' => $this->getForm()->createView()
46
                ]
47
            )
48
        );
49
        $block->setType('sonata.block.service.template');
50
51
        $event->addBlock($block);
52
    }
53
54
    public function getForm(Search $search = null): FormInterface
55
    {
56
        if (!$this->form) {
57
            if (!$search) {
58
                $search = new Search();
59
            }
60
            $this->form = $this->formFactory
61
                ->create(SearchType::class, $search, ['action' => $this->router->generate('bitbag_sylius_elasticsearch_plugin_shop_search')]);
62
        }
63
        return $this->form;
64
    }
65
}
66