1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ScayTrase\Api\Cruds\Adaptors\Symfony; |
4
|
|
|
|
5
|
|
|
use ScayTrase\Api\Cruds\EntityProcessorInterface; |
6
|
|
|
use ScayTrase\Api\Cruds\Exception\EntityProcessingException; |
7
|
|
|
use Symfony\Component\Form\FormFactoryInterface; |
8
|
|
|
use Symfony\Component\Form\FormInterface; |
9
|
|
|
use Symfony\Component\Form\FormTypeInterface; |
10
|
|
|
|
11
|
|
|
final class FormProcessor implements EntityProcessorInterface |
12
|
|
|
{ |
13
|
|
|
/** @var FormFactoryInterface */ |
14
|
|
|
private $factory; |
15
|
|
|
/** @var string|FormTypeInterface */ |
16
|
|
|
private $form; |
17
|
|
|
/** @var array */ |
18
|
|
|
private $options = []; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* FormProcessor constructor. |
22
|
|
|
* |
23
|
|
|
* @param string|FormTypeInterface $form Form instance or form class (factory required for class) |
24
|
|
|
* @param array $options Form options |
25
|
|
|
* @param FormFactoryInterface|null $factory Optional if form already provided |
26
|
|
|
* |
27
|
|
|
* @throws \LogicException |
28
|
|
|
*/ |
29
|
5 |
|
public function __construct($form, array $options = [], FormFactoryInterface $factory = null) |
30
|
|
|
{ |
31
|
5 |
|
if (!$form instanceof FormInterface && !$factory) { |
32
|
|
|
throw new \LogicException('You should either provide instantiated form or factory'); |
33
|
|
|
} |
34
|
|
|
|
35
|
5 |
|
$this->factory = $factory; |
36
|
5 |
|
$this->form = $form; |
37
|
5 |
|
$this->options = $options; |
38
|
5 |
|
} |
39
|
|
|
|
40
|
|
|
/** {@inheritdoc} */ |
41
|
5 |
|
public function updateEntity($entity, $data) |
42
|
|
|
{ |
43
|
5 |
|
$form = $this->form; |
44
|
|
|
|
45
|
5 |
|
if (!$form instanceof FormInterface) { |
46
|
3 |
|
$form = $this->factory->create($this->form, $entity, $this->options); |
|
|
|
|
47
|
3 |
|
} else { |
48
|
2 |
|
$form->setData($entity); |
49
|
|
|
} |
50
|
|
|
|
51
|
5 |
|
$form->submit($data, false); |
52
|
|
|
|
53
|
5 |
|
if (!$form->isValid()) { |
54
|
1 |
|
throw EntityProcessingException::invalidDataSubmitted((string)$form->getErrors(true), $data); |
55
|
|
|
} |
56
|
|
|
|
57
|
5 |
|
return $form->getData(); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.