Completed
Push — master ( 627c22...455f51 )
by Craig
07:48 queued 01:20
created

FormAwareEvent::getFormData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula Foundation - https://ziku.la/
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 Zikula\Bundle\FormExtensionBundle\Event;
15
16
use Symfony\Component\Form\FormInterface;
17
18
/**
19
 * This event should not be confused with Symfony's own FormEvents.
20
 * @see https://symfony.com/doc/current/form/events.html
21
 * This event is dispatched outside the flow of Symfony's form handling.
22
 *
23
 * This event is subclassed twice and dispatched twice in the workflow of a form.
24
 *   1) FormPostCreatedEvent: After the form is created and before it is `handled`.
25
 *   2) FormPostValidatedEvent: After the form is submitted and validated.
26
 */
27
class FormAwareEvent
28
{
29
    /**
30
     * @var FormInterface
31
     */
32
    private $form;
33
34
    /**
35
     * @var array
36
     */
37
    private $templates = [];
38
39
    public function __construct(FormInterface $form)
40
    {
41
        $this->form = $form;
42
    }
43
44
    /**
45
     * @param string|null $prefix
46
     * @return mixed
47
     */
48
    public function getFormData(string $prefix = null)
49
    {
50
        if (isset($prefix)) {
51
            return $this->form->get($prefix)->getData();
52
        }
53
54
        return $this->form->getData();
55
    }
56
57
    /**
58
     * @param FormInterface|string|int $child
59
     * @param string|null $type
60
     * @param array $options
61
     *
62
     * @return $this
63
     */
64
    public function formAdd($child, string $type = null, array $options = []): self
65
    {
66
        $this->form->add($child, $type, $options);
67
68
        return $this;
69
    }
70
71
    /**
72
     * @param string $template
73
     * @param array $templateVars
74
     *
75
     * @return $this
76
     */
77
    public function addTemplate(string $template, array $templateVars = []): self
78
    {
79
        if (!in_array($template, $this->templates, true)) {
80
            $this->templates[] = ['view' => $template, 'params' => $templateVars];
81
        }
82
83
        return $this;
84
    }
85
86
    public function getTemplates(): array
87
    {
88
        return $this->templates;
89
    }
90
}
91