1 | <?php |
||
14 | class EntityHydrator |
||
15 | { |
||
16 | public function __construct(TextFormater $formater, GuesserManager $guesserManager, EntityResolver $resolver, UniqueCache $cache) |
||
23 | |||
24 | public function hydrate(ObjectManager $em, $entity, $values) |
||
25 | { |
||
26 | foreach ($values as $property => $value) { |
||
27 | if (false !== $mapping = $this->resolver->getMetadataFromProperty($em, $entity, $property)) { |
||
28 | $this->formatFromMapping($mapping, $property, $value); |
||
29 | } |
||
30 | |||
31 | try { |
||
32 | PropertyAccess::createPropertyAccessor() |
||
33 | ->setValue( |
||
34 | $entity, |
||
35 | $this->formater->toCamelCase($property), |
||
36 | $value |
||
37 | ) |
||
38 | ; |
||
39 | } catch (\Exception $e) { |
||
40 | if (!($value instanceof ArrayCollection)) { |
||
41 | throw $e; |
||
42 | } |
||
43 | |||
44 | PropertyAccess::createPropertyAccessor() |
||
45 | ->setValue( |
||
46 | $entity, |
||
47 | $this->formater->toCamelCase($property), |
||
48 | $value->toArray() |
||
49 | ) |
||
50 | ; |
||
51 | } |
||
52 | } |
||
53 | |||
54 | return $this; |
||
55 | } |
||
56 | |||
57 | public function completeRequired(ObjectManager $em, $entity) |
||
61 | |||
62 | public function completeFields(ObjectManager $em, $entity) |
||
63 | { |
||
64 | $accessor = PropertyAccess::createPropertyAccessor(); |
||
65 | |||
66 | $metadata = $this->resolver->getMetadataFromObject($em, $entity); |
||
67 | |||
68 | foreach ($metadata->getColumnNames() as $columnName) { |
||
69 | $property = $metadata->getFieldName($columnName); |
||
70 | if (false === $metadata->isNullable($property)) { |
||
71 | try { |
||
72 | if (null === $accessor->getValue($entity, $property)) { |
||
73 | $accessor->setValue( |
||
74 | $entity, |
||
75 | $property, |
||
76 | $this->complete($metadata->getFieldMapping($property), $metadata->getName()) |
||
77 | ); |
||
78 | } |
||
79 | } catch (\Exception $ex) { |
||
80 | unset($ex); |
||
81 | } |
||
82 | } |
||
83 | } |
||
84 | |||
85 | return $this; |
||
86 | } |
||
87 | |||
88 | protected function complete($mapping, $className) |
||
102 | |||
103 | protected function format($mapping, $value) |
||
112 | |||
113 | protected function formatFromMapping($mapping, &$property, &$value) |
||
132 | } |
||
133 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: