-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathDocBlockHelper.php
More file actions
347 lines (311 loc) · 12.9 KB
/
DocBlockHelper.php
File metadata and controls
347 lines (311 loc) · 12.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
<?php
declare(strict_types=1);
namespace Bake\View\Helper;
use Cake\Collection\Collection;
use Cake\Core\App;
use Cake\Database\Type\EnumType;
use Cake\Database\TypeFactory;
use Cake\ORM\Association;
use Cake\Utility\Inflector;
use Cake\View\Helper;
/**
* DocBlock helper
*
* @extends \Cake\View\Helper<\Cake\View\View>
*/
class DocBlockHelper extends Helper
{
/**
* @var bool Whether to add a blank line between different class annotations
*/
protected bool $_annotationSpacing = true;
/**
* Writes the DocBlock header for a class which includes the property and method declarations. Annotations are
* sorted and grouped by type and value. Groups of annotations are separated by blank lines.
*
* @param string $className The class this comment block is for.
* @param string $classType The type of class (example, Entity)
* @param array<string> $annotations An array of PHP comment block annotations.
* @return string The DocBlock for a class header.
*/
public function classDescription(string $className, string $classType, array $annotations): string
{
$lines = [];
if ($className && $classType) {
$lines[] = "{$className} {$classType}";
}
if ($annotations && $lines) {
$lines[] = '';
}
$previous = false;
foreach ($annotations as $annotation) {
if (strlen($annotation) > 1 && $annotation[0] === '@' && strpos($annotation, ' ') > 0) {
$type = substr($annotation, 0, strpos($annotation, ' '));
if (
$this->_annotationSpacing &&
$previous !== false &&
$previous !== $type
) {
$lines[] = '';
}
$previous = $type;
}
$lines[] = $annotation;
}
$lines = array_merge(['/**'], (new Collection($lines))->map(function ($line) {
return rtrim(" * {$line}");
})->toArray(), [' */']);
return implode("\n", $lines);
}
/**
* Converts an entity class type to its DocBlock hint type counterpart.
*
* @param string $type The entity class type (a fully qualified class name).
* @param \Cake\ORM\Association $association The association related to the entity class.
* @return string The DocBlock type
*/
public function associatedEntityTypeToHintType(string $type, Association $association): string
{
$annotationType = $association->type();
if (
$annotationType === Association::MANY_TO_MANY ||
$annotationType === Association::ONE_TO_MANY
) {
return $type . '[]';
}
return $type;
}
/**
* Builds a map of entity columns as DocBlock types for use
* in generating `@property` hints.
*
* This method expects a property schema as generated by
* `\Bake\Command\ModelCommand::getEntityPropertySchema()`.
*
* The generated map has the format of
*
* ```
* [
* 'property-name' => 'doc-block-type',
* ...
* ]
* ```
*
* @see \Bake\Command\ModelCommand::getEntityPropertySchema
* @param array $propertySchema The property schema to use for generating the type map.
* @return array The property DocType map.
*/
public function buildEntityPropertyHintTypeMap(array $propertySchema): array
{
$properties = [];
foreach ($propertySchema as $property => $info) {
if ($info['kind'] === 'column') {
$type = $this->columnTypeToHintType($info['type']);
if (!empty($info['null'])) {
$type .= '|null';
}
$properties[$property] = $type;
}
}
return $properties;
}
/**
* Builds a map of entity associations as DocBlock types for use
* in generating `@property` hints.
*
* This method expects a property schema as generated by
* `\Bake\Command\ModelCommand::getEntityPropertySchema()`.
*
* The generated map has the format of
*
* ```
* [
* 'property-name' => 'doc-block-type',
* ...
* ]
* ```
*
* @see \Bake\Command\ModelCommand::getEntityPropertySchema
* @param array $propertySchema The property schema to use for generating the type map.
* @return array The property DocType map.
*/
public function buildEntityAssociationHintTypeMap(array $propertySchema): array
{
$properties = [];
foreach ($propertySchema as $property => $info) {
if ($info['kind'] === 'association') {
$type = $this->associatedEntityTypeToHintType($info['type'], $info['association']);
if ($info['association']->type() === Association::MANY_TO_ONE) {
$properties = $this->_insertAfter(
$properties,
$info['association']->getForeignKey(),
[$property => $type],
);
} else {
$properties[$property] = $type;
}
}
}
return $properties;
}
/**
* Converts a column type to its DocBlock type counterpart.
*
* This method only supports the default CakePHP column types,
* for custom column/database types `'string'` will be returned.
*
* @see \Cake\Database\Type
* @param string $type The column type.
* @return string|null The DocBlock type, or `'string'` for unsupported column types.
*/
public function columnTypeToHintType(string $type): ?string
{
switch ($type) {
case 'char':
case 'string':
case 'text':
case 'uuid':
case 'decimal':
return 'string';
case 'integer':
case 'biginteger':
case 'smallinteger':
case 'tinyinteger':
return 'int';
case 'float':
return 'float';
case 'boolean':
return 'bool';
case 'array':
case 'json':
return 'array';
case 'binary':
return 'string|resource';
case 'date':
$dbType = TypeFactory::build($type);
if (method_exists($dbType, 'getDateClassName')) {
// allow custom Date class which should extend \Cake\I18n\Date
return '\\' . $dbType->getDateClassName();
}
return '\Cake\I18n\Date';
case 'datetime':
case 'datetimefractional':
case 'timestamp':
case 'timestampfractional':
case 'timestamptimezone':
$dbType = TypeFactory::build($type);
if (method_exists($dbType, 'getDateTimeClassName')) {
// allow custom DateTime class which should extend \Cake\I18n\DateTime
return '\\' . $dbType->getDateTimeClassName();
}
return '\Cake\I18n\DateTime';
case 'time':
$dbType = TypeFactory::build($type);
if (method_exists($dbType, 'getTimeClassName')) {
// allow custom Time class which should extend \Cake\I18n\Time
return '\\' . $dbType->getTimeClassName();
}
return '\Cake\I18n\Time';
default:
if (str_starts_with($type, 'enum-')) {
$dbType = TypeFactory::build($type);
if ($dbType instanceof EnumType) {
return '\\' . $dbType->getEnumClassName();
}
}
}
// Any unique or custom types will have a `string` type hint
return 'string';
}
/**
* Renders a map of DocBlock property types as an array of
* `@property` hints.
*
* @param array<string> $properties A key value pair where key is the name of a property and the value is the type.
* @return array<string>
*/
public function propertyHints(array $properties): array
{
$lines = [];
foreach ($properties as $property => $type) {
$type = $type ? $type . ' ' : '';
$lines[] = "@property {$type}\${$property}";
}
return $lines;
}
/**
* Build property, method, mixing annotations for table class.
*
* @param array $associations Associations list.
* @param array $associationInfo Association info.
* @param array $behaviors Behaviors list.
* @param string $entity Entity name.
* @param string $namespace Namespace.
* @return array<string>
*/
public function buildTableAnnotations(
array $associations,
array $associationInfo,
array $behaviors,
string $entity,
string $namespace,
): array {
$annotations = [];
foreach ($associations as $type => $assocs) {
foreach ($assocs as $assoc) {
$typeStr = Inflector::camelize($type);
if (isset($associationInfo[$assoc['alias']])) {
$tableFqn = $associationInfo[$assoc['alias']]['targetFqn'];
$annotations[] = "@property {$tableFqn}&\Cake\ORM\Association\\{$typeStr} \${$assoc['alias']}";
}
}
}
// phpcs:disable
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity} newEmptyEntity()";
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity} newEntity(array \$data, array \$options = [])";
$annotations[] = "@method array<\\{$namespace}\\Model\\Entity\\{$entity}> newEntities(array \$data, array \$options = [])";
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity} get(mixed \$primaryKey, array|string \$finder = 'all', \\Psr\\SimpleCache\\CacheInterface|string|null \$cache = null, \Closure|string|null \$cacheKey = null, mixed ...\$args)";
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity} findOrCreate(\$search, ?callable \$callback = null, array \$options = [])";
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity} patchEntity(\\Cake\\Datasource\\EntityInterface \$entity, array \$data, array \$options = [])";
$annotations[] = "@method array<\\{$namespace}\\Model\\Entity\\{$entity}> patchEntities(iterable \$entities, array \$data, array \$options = [])";
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity}|false save(\\Cake\\Datasource\\EntityInterface \$entity, array \$options = [])";
$annotations[] = "@method \\{$namespace}\\Model\\Entity\\{$entity} saveOrFail(\\Cake\\Datasource\\EntityInterface \$entity, array \$options = [])";
$annotations[] = "@method iterable<\\{$namespace}\\Model\\Entity\\{$entity}>|\Cake\Datasource\ResultSetInterface<\\{$namespace}\\Model\\Entity\\{$entity}>|false saveMany(iterable \$entities, array \$options = [])";
$annotations[] = "@method iterable<\\{$namespace}\\Model\\Entity\\{$entity}>|\Cake\Datasource\ResultSetInterface<\\{$namespace}\\Model\\Entity\\{$entity}> saveManyOrFail(iterable \$entities, array \$options = [])";
$annotations[] = "@method iterable<\\{$namespace}\\Model\\Entity\\{$entity}>|\Cake\Datasource\ResultSetInterface<\\{$namespace}\\Model\\Entity\\{$entity}>|false deleteMany(iterable \$entities, array \$options = [])";
$annotations[] = "@method iterable<\\{$namespace}\\Model\\Entity\\{$entity}>|\Cake\Datasource\ResultSetInterface<\\{$namespace}\\Model\\Entity\\{$entity}> deleteManyOrFail(iterable \$entities, array \$options = [])";
// phpcs:enable
foreach ($behaviors as $behavior => $behaviorData) {
$className = App::className($behavior, 'Model/Behavior', 'Behavior');
if (!$className) {
$className = "Cake\ORM\Behavior\\{$behavior}Behavior";
}
$annotations[] = '@mixin \\' . $className;
}
return $annotations;
}
/**
* Inserts a value after a specific key in an associative array.
*
* In case the given key cannot be found, the value will be appended.
*
* @param array $target The array in which to insert the new value.
* @param string $key The array key after which to insert the new value.
* @param mixed $value The entry to insert.
* @return array The array with the new value inserted.
*/
protected function _insertAfter(array $target, string $key, mixed $value): array
{
$index = array_search($key, array_keys($target));
if ($index !== false) {
$target = array_merge(
array_slice($target, 0, $index + 1),
$value,
array_slice($target, $index + 1, null),
);
} else {
$target += (array)$value;
}
return $target;
}
}