-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEntityFormMapper.php
More file actions
95 lines (78 loc) · 2.03 KB
/
Copy pathEntityFormMapper.php
File metadata and controls
95 lines (78 loc) · 2.03 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
<?php
namespace ADT\DoctrineForms;
use ADT\DoctrineComponents\Entities\Entity;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Iterator;
use Nette\Forms\Container;
use Nette\Forms\Control;
use Symfony\Component\PropertyAccess\PropertyAccessor;
class EntityFormMapper
{
private EntityManagerInterface $em;
/**
* @var IComponentMapper[]
*/
private array $componentMappers;
private ?PropertyAccessor $accessor = null;
private Form $entityForm;
public function __construct(EntityManagerInterface $entityManager, Form $entityForm)
{
$this->em = $entityManager;
$this->entityForm = $entityForm;
$this->componentMappers = array(
new Controls\TextControl($this),
new Controls\ToOne($this),
new Controls\ToMany($this),
);
}
public function getAccessor(): ?PropertyAccessor
{
if ($this->accessor === NULL) {
$this->accessor = new PropertyAccessor(TRUE);
}
return $this->accessor;
}
public function getEntityManager(): EntityManagerInterface
{
return $this->em;
}
public function load(Entity $entity, Container|Control $formElement): void
{
$meta = $this->getMetadata($entity);
foreach (self::iterate($formElement) as $component) {
foreach ($this->componentMappers as $mapper) {
if ($mapper->load($meta, $component, $entity)) {
break;
}
}
}
}
public function save(Entity $entity, Container|Control $formElement): void
{
$meta = $this->getMetadata($entity);
foreach (self::iterate($formElement) as $component) {
foreach ($this->componentMappers as $mapper) {
if ($mapper->save($meta, $component, $entity)) {
break;
}
}
}
}
private static function iterate(Container|Control $formElement): Iterator|array
{
if ($formElement instanceof Container) {
return $formElement->getComponents();
} else {
return array($formElement);
}
}
public function getMetadata(object $entity): ClassMetadata
{
return $this->em->getClassMetadata(get_class($entity));
}
public function getForm(): Form
{
return $this->entityForm;
}
}