-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathObjectBeanPropertyDescriptor.php
More file actions
353 lines (312 loc) · 11.9 KB
/
ObjectBeanPropertyDescriptor.php
File metadata and controls
353 lines (312 loc) · 11.9 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
<?php
declare(strict_types=1);
namespace TheCodingMachine\TDBM\Utils;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use TheCodingMachine\TDBM\Schema\ForeignKey;
use TheCodingMachine\TDBM\TDBMException;
use TheCodingMachine\TDBM\Utils\Annotation\AnnotationParser;
use TheCodingMachine\TDBM\Utils\Annotation;
use Zend\Code\Generator\AbstractMemberGenerator;
use Zend\Code\Generator\DocBlockGenerator;
use Zend\Code\Generator\MethodGenerator;
use Zend\Code\Generator\ParameterGenerator;
/**
* This class represent a property in a bean that points to another table.
*/
class ObjectBeanPropertyDescriptor extends AbstractBeanPropertyDescriptor
{
use ForeignKeyAnalyzerTrait;
/**
* @var ForeignKeyConstraint
*/
private $foreignKey;
/**
* @var string
*/
private $beanNamespace;
/**
* @var BeanDescriptor
*/
private $foreignBeanDescriptor;
/**
* ObjectBeanPropertyDescriptor constructor.
* @param Table $table
* @param ForeignKeyConstraint $foreignKey
* @param NamingStrategyInterface $namingStrategy
* @param string $beanNamespace
* @param AnnotationParser $annotationParser
* @param BeanDescriptor $foreignBeanDescriptor The BeanDescriptor of FK foreign table
*/
public function __construct(
Table $table,
ForeignKeyConstraint $foreignKey,
NamingStrategyInterface $namingStrategy,
string $beanNamespace,
AnnotationParser $annotationParser,
BeanDescriptor $foreignBeanDescriptor
) {
parent::__construct($table, $namingStrategy);
$this->foreignKey = $foreignKey;
$this->beanNamespace = $beanNamespace;
$this->annotationParser = $annotationParser;
$this->table = $table;
$this->namingStrategy = $namingStrategy;
$this->foreignBeanDescriptor = $foreignBeanDescriptor;
}
/**
* Returns the foreignkey the column is part of, if any. null otherwise.
*
* @return ForeignKeyConstraint
*/
public function getForeignKey(): ForeignKeyConstraint
{
return $this->foreignKey;
}
/**
* Returns the name of the class linked to this property or null if this is not a foreign key.
*
* @return string
*/
public function getClassName(): string
{
return $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
}
/**
* Returns the PHP type for the property (it can be a scalar like int, bool, or class names, like \DateTimeInterface, App\Bean\User....)
*
* @return string
*/
public function getPhpType(): string
{
return '\\' . $this->beanNamespace . '\\' . $this->getClassName();
}
/**
* Returns true if the property is compulsory (and therefore should be fetched in the constructor).
*
* @return bool
*/
public function isCompulsory(): bool
{
// Are all columns nullable?
foreach ($this->getLocalColumns() as $column) {
if ($column->getNotnull()) {
return true;
}
}
return false;
}
/**
* Returns true if the property has a default value.
*
* @return bool
*/
public function hasDefault(): bool
{
return false;
}
/**
* Returns the code that assigns a value to its default value.
*
* @return string
*
* @throws TDBMException
*/
public function assignToDefaultCode(): string
{
throw new TDBMException('Foreign key based properties cannot be assigned a default value.');
}
/**
* Returns true if the property is the primary key.
*
* @return bool
*/
public function isPrimaryKey(): bool
{
$fkColumns = $this->foreignKey->getUnquotedLocalColumns();
sort($fkColumns);
$pkColumns = TDBMDaoGenerator::getPrimaryKeyColumnsOrFail($this->table);
sort($pkColumns);
return $fkColumns == $pkColumns;
}
/**
* Returns the PHP code for getters and setters.
*
* @return (MethodGenerator|null)[]
*/
public function getGetterSetterCode(): array
{
$tableName = $this->table->getName();
$getterName = $this->getGetterName();
$setterName = $this->getSetterName();
$isNullable = !$this->isCompulsory();
$referencedBeanName = $this->namingStrategy->getBeanClassName($this->foreignKey->getForeignTableName());
$getter = new MethodGenerator($getterName);
$getter->setDocBlock(new DocBlockGenerator('Returns the ' . $referencedBeanName . ' object bound to this object via the ' . implode(' and ', $this->foreignKey->getUnquotedLocalColumns()) . ' column.'));
/*$types = [ $referencedBeanName ];
if ($isNullable) {
$types[] = 'null';
}
$getter->getDocBlock()->setTag(new ReturnTag($types));*/
$getter->setReturnType(($isNullable ? '?' : '') . $this->beanNamespace . '\\' . $referencedBeanName);
$tdbmFk = ForeignKey::createFromFk($this->foreignKey);
$getter->setBody('return $this->getRef(' . var_export($tdbmFk->getCacheKey(), true) . ', ' . var_export($tableName, true) . ');');
if ($this->isGetterProtected()) {
$getter->setVisibility(AbstractMemberGenerator::VISIBILITY_PROTECTED);
}
if (!$this->isReadOnly()) {
$setter = new MethodGenerator($setterName);
$setter->setDocBlock(new DocBlockGenerator('The setter for the ' . $referencedBeanName . ' object bound to this object via the ' . implode(' and ', $this->foreignKey->getUnquotedLocalColumns()) . ' column.'));
$setter->setParameter(new ParameterGenerator('object', ($isNullable ? '?' : '') . $this->beanNamespace . '\\' . $referencedBeanName));
$setter->setReturnType('void');
$setter->setBody('$this->setRef(' . var_export($tdbmFk->getCacheKey(), true) . ', $object, ' . var_export($tableName, true) . ');');
if ($this->isSetterProtected()) {
$setter->setVisibility(AbstractMemberGenerator::VISIBILITY_PROTECTED);
}
} else {
$setter = null;
}
return [$getter, $setter];
}
/**
* Returns the part of code useful when doing json serialization.
*
* @return string
*/
public function getJsonSerializeCode(): string
{
if ($this->findAnnotation(Annotation\JsonIgnore::class)) {
return '';
}
if ($this->isGetterProtected()) {
return '';
}
if ($this->findAnnotation(Annotation\JsonCollection::class)) {
if ($this->findAnnotation(Annotation\JsonInclude::class) ||
$this->findAnnotation(Annotation\JsonRecursive::class)) {
return '';
}
$isIncluded = false;
$format = 'jsonSerialize(true)';
} else {
$isIncluded = $this->findAnnotation(Annotation\JsonInclude::class) !== null;
/** @var Annotation\JsonFormat|null $jsonFormat */
$jsonFormat = $this->findAnnotation(Annotation\JsonFormat::class);
if ($jsonFormat !== null) {
$method = $jsonFormat->method ?? 'get' . ucfirst($jsonFormat->property);
$format = "$method()";
} else {
$stopRecursion = $this->findAnnotation(Annotation\JsonRecursive::class) ? '' : 'true';
$format = "jsonSerialize($stopRecursion)";
}
}
/** @var Annotation\JsonKey|null $jsonKey */
$jsonKey = $this->findAnnotation(Annotation\JsonKey::class);
$index = $jsonKey ? $jsonKey->key : $this->namingStrategy->getJsonProperty($this);
$getter = $this->getGetterName();
if (!$this->isCompulsory()) {
$recursiveCode = "\$array['$index'] = (\$object = \$this->$getter()) ? \$object->$format : null;";
$lazyCode = "\$array['$index'] = (\$object = \$this->$getter()) ? {$this->getLazySerializeCode('$object')} : null;";
} else {
$recursiveCode = "\$array['$index'] = \$this->$getter()->$format;";
$lazyCode = "\$array['$index'] = {$this->getLazySerializeCode("\$this->$getter()")};";
}
if ($isIncluded) {
$code = $recursiveCode;
} else {
$code = <<<PHP
if (\$stopRecursion) {
$lazyCode
} else {
$recursiveCode
}
PHP;
}
return $code;
}
private function getLazySerializeCode(string $propertyAccess): string
{
$rows = [];
foreach ($this->getForeignKey()->getUnquotedForeignColumns() as $column) {
$descriptor = $this->getBeanPropertyDescriptor($column);
$shouldFlatten = false;
if ($descriptor instanceof InheritanceReferencePropertyDescriptor) {
$descriptor = $descriptor->getNonScalarReferencedPropertyDescriptor();
$shouldFlatten = true;
}
$indexName = ltrim($descriptor->getVariableName(), '$');
$columnGetterName = $descriptor->getGetterName();
if ($descriptor instanceof ObjectBeanPropertyDescriptor) {
if ($shouldFlatten) {
$rows[] = trim($descriptor->getLazySerializeCode($propertyAccess), '[]');
} else {
$lazySerializeCode = $descriptor->getLazySerializeCode("$propertyAccess->$columnGetterName()");
$rows[] = "'$indexName' => $lazySerializeCode";
}
} elseif ($descriptor instanceof ScalarBeanPropertyDescriptor) {
$rows[] = "'$indexName' => $propertyAccess->$columnGetterName()";
} else {
throw new TDBMException('PropertyDescriptor of class `' . get_class($descriptor) . '` cannot be serialized.');
}
}
return '[' . implode(', ', $rows) . ']';
}
private function getBeanPropertyDescriptor(string $column): AbstractBeanPropertyDescriptor
{
foreach ($this->foreignBeanDescriptor->getBeanPropertyDescriptors() as $descriptor) {
if ($descriptor instanceof ScalarBeanPropertyDescriptor && $descriptor->getColumnName() === $column) {
return $descriptor;
}
if ($descriptor instanceof ObjectBeanPropertyDescriptor && in_array($column, $descriptor->getForeignKey()->getLocalColumns(), true)) {
return $descriptor;
}
if ($descriptor instanceof ObjectBeanPropertyDescriptor && in_array($column, $descriptor->getForeignKey()->getUnquotedLocalColumns(), true)) {
return $descriptor;
}
}
throw new TDBMException('PropertyDescriptor for `'.$this->table->getName().'`.`' . $column . '` not found in `' . $this->foreignBeanDescriptor->getTable()->getName() . '`');
}
/**
* The code to past in the __clone method.
* @return null|string
*/
public function getCloneRule(): ?string
{
return null;
}
/**
* Tells if this property is a type-hintable in PHP (resource isn't for example)
*
* @return bool
*/
public function isTypeHintable(): bool
{
return true;
}
private function isGetterProtected(): bool
{
return $this->findAnnotation(Annotation\ProtectedGetter::class) !== null;
}
private function isSetterProtected(): bool
{
return $this->findAnnotation(Annotation\ProtectedSetter::class) !== null;
}
public function isReadOnly(): bool
{
return $this->findAnnotation(Annotation\ReadOnly::class) !== null;
}
/**
* @param string $type
* @return null|object
*/
private function findAnnotation(string $type)
{
foreach ($this->getAnnotations() as $annotations) {
$annotation = $annotations->findAnnotation($type);
if ($annotation !== null) {
return $annotation;
}
}
return null;
}
}