-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathConfigurator.php
More file actions
320 lines (263 loc) · 11.6 KB
/
Copy pathConfigurator.php
File metadata and controls
320 lines (263 loc) · 11.6 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
<?php
declare(strict_types=1);
namespace Cycle\Annotated;
use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Embeddable;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Relation as RelationAnnotation;
use Cycle\Annotated\Exception\AnnotationException;
use Cycle\Annotated\Exception\AnnotationRequiredArgumentsException;
use Cycle\Annotated\Exception\AnnotationWrongTypeArgumentException;
use Cycle\Annotated\Utils\EntityUtils;
use Cycle\Schema\Definition\Entity as EntitySchema;
use Cycle\Schema\Definition\Field;
use Cycle\Schema\Definition\Relation;
use Cycle\Schema\Generator\SyncTables;
use Cycle\Schema\SchemaModifierInterface;
use Doctrine\Common\Annotations\Reader as DoctrineReader;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\Rules\English\InflectorFactory;
use Exception;
use Spiral\Attributes\ReaderInterface;
use function is_subclass_of;
final class Configurator
{
private ReaderInterface $reader;
private Inflector $inflector;
private EntityUtils $utils;
public function __construct(
DoctrineReader|ReaderInterface $reader,
private int $tableNamingStrategy = Entities::TABLE_NAMING_PLURAL,
) {
$this->reader = ReaderFactory::create($reader);
$this->inflector = (new InflectorFactory())->build();
$this->utils = new EntityUtils($this->reader);
}
public function initEntity(Entity $ann, \ReflectionClass $class): EntitySchema
{
$e = new EntitySchema();
$e->setClass($class->getName());
$e->setRole($ann->getRole() ?? $this->inflector->camelize($class->getShortName()));
// representing classes
$e->setMapper($this->resolveName($ann->getMapper(), $class));
$e->setRepository($this->resolveName($ann->getRepository(), $class));
$e->setSource($this->resolveName($ann->getSource(), $class));
$e->setScope($this->resolveName($ann->getScope(), $class));
$e->setDatabase($ann->getDatabase());
$e->setTableName(
$ann->getTable() ?? $this->utils->tableName($e->getRole(), $this->tableNamingStrategy)
);
$typecast = $ann->getTypecast();
if (is_array($typecast)) {
$typecast = array_map(fn (string $value): string => $this->resolveName($value, $class), $typecast);
} else {
$typecast = $this->resolveName($typecast, $class);
}
$e->setTypecast($typecast);
if ($ann->isReadonlySchema()) {
$e->getOptions()->set(SyncTables::READONLY_SCHEMA, true);
}
return $e;
}
public function initEmbedding(Embeddable $emb, \ReflectionClass $class): EntitySchema
{
$e = new EntitySchema();
$e->setClass($class->getName());
$e->setRole($emb->getRole() ?? $this->inflector->camelize($class->getShortName()));
// representing classes
$e->setMapper($this->resolveName($emb->getMapper(), $class));
return $e;
}
public function initFields(EntitySchema $entity, \ReflectionClass $class, string $columnPrefix = ''): void
{
foreach ($class->getProperties() as $property) {
try {
$column = $this->reader->firstPropertyMetadata($property, Column::class);
} catch (Exception $e) {
throw new AnnotationException($e->getMessage(), $e->getCode(), $e);
} catch (\ArgumentCountError $e) {
throw AnnotationRequiredArgumentsException::createFor($property, Column::class, $e);
} catch (\TypeError $e) {
throw AnnotationWrongTypeArgumentException::createFor($property, $e);
}
if ($column === null) {
continue;
}
$field = $this->initField($property, $column, $class, $columnPrefix);
$field->setEntityClass($property->getDeclaringClass()->getName());
$entity->getFields()->set($property->getName(), $field);
}
}
public function initRelations(EntitySchema $entity, \ReflectionClass $class): void
{
foreach ($class->getProperties() as $property) {
try {
$metadata = $this->reader->getPropertyMetadata($property, RelationAnnotation\RelationInterface::class);
} catch (Exception $e) {
throw new AnnotationException($e->getMessage(), $e->getCode(), $e);
}
foreach ($metadata as $meta) {
assert($meta instanceof RelationAnnotation\RelationInterface);
if ($meta->getTarget() === null) {
throw new AnnotationException(
"Relation target definition is required on `{$entity->getClass()}`.`{$property->getName()}`"
);
}
$relation = new Relation();
$relation->setTarget($this->resolveName($meta->getTarget(), $class));
$relation->setType($meta->getType());
$inverse = $meta->getInverse() ?? $this->reader->firstPropertyMetadata(
$property,
RelationAnnotation\Inverse::class
);
if ($inverse !== null) {
$relation->setInverse(
$inverse->getName(),
$inverse->getType(),
$inverse->getLoadMethod()
);
}
if ($meta instanceof RelationAnnotation\Embedded && $meta->getPrefix() === null) {
/** @var Embeddable|null $embeddable */
$embeddable = $this->reader->firstClassMetadata(
new \ReflectionClass($relation->getTarget()),
Embeddable::class
);
$meta->setPrefix($embeddable->getColumnPrefix());
}
foreach ($meta->getOptions() as $option => $value) {
$value = match ($option) {
'collection' => $this->resolveName($value, $class),
'though', 'through' => $this->resolveName($value, $class),
default => $value
};
$relation->getOptions()->set($option, $value);
}
// need relation definition
$entity->getRelations()->set($property->getName(), $relation);
}
}
}
public function initModifiers(EntitySchema $entity, \ReflectionClass $class): void
{
try {
$metadata = $this->reader->getClassMetadata($class, SchemaModifierInterface::class);
} catch (Exception $e) {
throw new AnnotationException($e->getMessage(), $e->getCode(), $e);
}
foreach ($metadata as $meta) {
assert($meta instanceof SchemaModifierInterface);
// need relation definition
$entity->addSchemaModifier($meta);
}
}
/**
* @param Column[] $columns
*/
public function initColumns(EntitySchema $entity, array $columns, \ReflectionClass $class): void
{
foreach ($columns as $key => $column) {
$isNumericKey = is_numeric($key);
$propertyName = $column->getProperty();
if (!$isNumericKey && $propertyName !== null && $key !== $propertyName) {
throw new AnnotationException(
"Can not use name \"{$key}\" for Column of the `{$entity->getRole()}` role, because the "
. "\"property\" field of the metadata class has already been set to \"{$propertyName}\"."
);
}
$propertyName = $propertyName ?? ($isNumericKey ? null : $key);
$columnName = $column->getColumn() ?? $propertyName;
$propertyName = $propertyName ?? $columnName;
if ($columnName === null) {
throw new AnnotationException(
"Column name definition is required on `{$entity->getClass()}`"
);
}
$field = $this->initField($columnName, $column, $class, '');
$field->setEntityClass($entity->getClass());
$entity->getFields()->set($propertyName, $field);
}
}
public function initField(string|\ReflectionProperty $nameOrProperty, Column $column, \ReflectionClass $class, string $columnPrefix): Field
{
$type = $column->getType();
$isNullable = $column->hasNullable() ? $column->isNullable() : null;
$hasDefault = $column->hasDefault();
$default = $column->getDefault();
if ($nameOrProperty instanceof \ReflectionProperty) {
$name = ($property = $nameOrProperty)->getName();
$propertyType = $property->getType();
if ($property->hasDefaultValue() && !$hasDefault) {
$hasDefault = true;
$default = $property->getDefaultValue();
}
if ($propertyType instanceof \ReflectionType) {
$isNullable ??= $propertyType->allowsNull();
if ($propertyType instanceof \ReflectionNamedType) {
if ($propertyType->isBuiltin()) {
$type ??= $propertyType->getName();
} elseif (is_subclass_of($propertyType->getName(), \DateTimeInterface::class)) {
$type = 'datetime';
}
}
}
} else {
$name = $nameOrProperty;
}
if ($type === null) {
throw new AnnotationException(
"Column type definition is required on `{$class->getName()}`.`{$name}`"
);
}
$field = new Field();
$field->setType($type);
$field->setColumn($columnPrefix . ($column->getColumn() ?? $this->inflector->tableize($name)));
$field->setPrimary($column->isPrimary());
$field->setTypecast($this->resolveTypecast($column->getTypecast(), $class));
if ($isNullable) {
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_NULLABLE, true);
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_DEFAULT, null);
}
if ($hasDefault) {
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_DEFAULT, $default);
}
if ($column->castDefault()) {
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_CAST_DEFAULT, true);
}
return $field;
}
/**
* Resolve class or role name relative to the current class.
*/
public function resolveName(?string $name, \ReflectionClass $class): ?string
{
if ($name === null || class_exists($name, true) || interface_exists($name, true)) {
return $name;
}
$resolved = sprintf(
'%s\\%s',
$class->getNamespaceName(),
ltrim(str_replace('/', '\\', $name), '\\')
);
if (class_exists($resolved, true) || interface_exists($resolved, true)) {
return ltrim($resolved, '\\');
}
return $name;
}
private function resolveTypecast(mixed $typecast, \ReflectionClass $class): mixed
{
if (is_string($typecast) && strpos($typecast, '::') !== false) {
// short definition
$typecast = explode('::', $typecast);
// resolve class name
$typecast[0] = $this->resolveName($typecast[0], $class);
}
if (is_string($typecast)) {
$typecast = $this->resolveName($typecast, $class);
if (class_exists($typecast)) {
$typecast = [$typecast, 'typecast'];
}
}
return $typecast;
}
}