-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPublicPropertyDataMapper.php
More file actions
108 lines (90 loc) · 2.91 KB
/
Copy pathPublicPropertyDataMapper.php
File metadata and controls
108 lines (90 loc) · 2.91 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
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace Quatrevieux\Form\DataMapper;
use Nette\PhpGenerator\Literal;
use Quatrevieux\Form\DataMapper\Generator\DataMapperTypeGeneratorInterface;
use Quatrevieux\Form\Util\Code;
use ReflectionClass;
use ReflectionProperty;
use TypeError;
use function get_object_vars;
use function sprintf;
/**
* Simple data mapper implementation using default constructor and fill directly public properties
*
* @template T as object
* @implements DataMapperInterface<T>
* @implements DataMapperTypeGeneratorInterface<PublicPropertyDataMapper<T>>
*/
final class PublicPropertyDataMapper implements DataMapperInterface, DataMapperTypeGeneratorInterface
{
public function __construct(
/**
* Data transfer object class name
*
* @var class-string<T> $className
*/
private readonly string $className,
) {}
/**
* {@inheritdoc}
*/
public function className(): string
{
return $this->className;
}
/**
* {@inheritdoc}
*/
public function toDataObject(array $fields): DataMapperResult
{
$className = $this->className;
$object = new $className();
foreach ($fields as $name => $value) {
try {
$object->$name = $value;
} catch (TypeError $e) {
// Ignore type error : can occur when trying to set null on a non-nullable property
}
}
return new DataMapperResult($object);
}
/**
* {@inheritdoc}
*/
public function toArray(object $data): array
{
return get_object_vars($data);
}
/**
* {@inheritdoc}
*/
public function generateToDataObject(DataMapperInterface $dataMapper): string
{
$code = '$object = ' . Code::new($dataMapper->className()) . ';' . PHP_EOL;
$classReflection = new ReflectionClass($dataMapper->className());
foreach ($classReflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
$propertyName = $property->name;
$propertyNameString = Code::value($propertyName);
if (!$property->getType() || $property->getType()->allowsNull()) {
$code .= sprintf('$object->%s = $fields[%s] ?? null;', $propertyName, $propertyNameString) . PHP_EOL;
} else {
$tmpVarname = new Literal(Code::varName($property->name));
$code .= <<<PHP
if (({$tmpVarname} = \$fields[{$propertyNameString}] ?? null) !== null) {
\$object->{$propertyName} = {$tmpVarname};
}
PHP
;
}
}
$code .= sprintf('return new \%s($object);', DataMapperResult::class);
return $code;
}
/**
* {@inheritdoc}
*/
public function generateToArray(DataMapperInterface $dataMapper): string
{
return 'return get_object_vars($data);';
}
}