-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathPHPFunction.php
More file actions
559 lines (490 loc) · 19.7 KB
/
PHPFunction.php
File metadata and controls
559 lines (490 loc) · 19.7 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<?php
namespace DrupalCodeBuilder\Generator;
use MutableTypedData\Definition\PropertyListInterface;
use DrupalCodeBuilder\Generator\FormattingTrait\PHPFormattingTrait;
use DrupalCodeBuilder\Definition\PropertyDefinition;
use DrupalCodeBuilder\Generator\Render\DocBlock;
use DrupalCodeBuilder\Generator\Render\PhpAttributes;
use DrupalCodeBuilder\Generator\Render\PhpValue;
use MutableTypedData\Definition\DefaultDefinition;
/**
* Generator base class for functions.
*
* (We can't call this 'Function', as that's a reserved word.)
*
* This generator has properties that can be used in several different
* combinations:
*
* - For the declaration, either set complete declaration string, or the
* separate name, prefixes, parameters, and return type. The reason for this
* is that analysis data will have the declaration string, but for functions
* completely assembled in code it's easier to define each element of the
* declaration.
* - The code of the function can either come from:
* - The getFunctionBody() method if a subclass overrides it.
* - The property value.
* - Contained PHPFunctionBodyLines components.
* - Both the property value and contained PHPFunctionBodyLines components,
* in which case contained component lines either go last, or are inserted
* to replace a token: see self::getContents().
*
* Properties include:
* - 'declaration': The function declaration, including the function name
* and parameters, up to the closing parenthesis. Should not however
* include the opening brace of the function body.
* - 'body' The code of the function. The character '£' is replaced with
* '$' as a convenience to avoid having to keep escaping names of
* variables. This can be in one of the following forms:
* - a string, not including the enclosing function braces or the opening
* or closing newlines.
* TODO: This is not currently working, but doesn't matter as
* Hooks::getTemplates() always returns an array of lines in 'template'
* even if that's just the analysis body code.
* - an array of lines of code. These should not have their newlines.
*/
class PHPFunction extends BaseGenerator {
use PHPFormattingTrait;
/**
* {@inheritdoc}
*/
public static function addToGeneratorDefinition(PropertyListInterface $definition) {
parent::addToGeneratorDefinition($definition);
$definition->addProperties([
// The method name (without the ()).
// TODO: make this required when https://github.com/joachim-n/mutable-typed-data/issues/7
// is fixed.
'function_name' => PropertyDefinition::create('string')
->setInternal(TRUE),
'docblock_inherit' => PropertyDefinition::create('boolean')
->setInternal(TRUE)
->setLiteralDefault(FALSE),
// Lines for the class docblock.
// If there is more than one line, a blank link is inserted automatically
// after the first one.
// Or multiple string?
'function_docblock_lines' => PropertyDefinition::create('mapping')
->setInternal(TRUE)
->setDefault(DefaultDefinition::create()
->setCallable([static::class, 'defaultDocblockLines'])
),
'doxygen_tag_lines' => PropertyDefinition::create('mapping')
->setLabel("Doxygen tags to go after the standard ones")
->setInternal(TRUE),
// An attribute class for the method.
// WARNING: Only for methods, only supports one attribute, only supports
// a class with no parameters.
'attribute' => PropertyDefinition::create('string')
->setInternal(TRUE),
'declaration' => PropertyDefinition::create('string')
->setInternal(TRUE),
// An array of prefixes such as 'static', 'public'.
// Not yet compatible with 'declaration' property.
'prefixes' => PropertyDefinition::create('string')
->setInternal(TRUE)
->setMultiple(TRUE),
// Not yet compatible with 'declaration' property.
// Has no effect if 'parameters' is empty.
'break_declaration' => PropertyDefinition::create('boolean')
->setInternal(TRUE)
->setDescription('If TRUE, the declaration parameters are each on a single line.'),
'parameters' => PropertyDefinition::create('complex')
->setMultiple(TRUE)
->setInternal(TRUE)
->setProperties([
// The name of the parameter, without the initial $.
'name' => PropertyDefinition::create('string'),
'by_reference' => PropertyDefinition::create('boolean'),
// The typehint of the parameter. If this is a class or interface, use
// the fully-qualified form: this will produce import statements for
// the file automatically.
'typehint' => PropertyDefinition::create('string')
// Need to give a type, otherwise PHPCS will complain in tests!
->setLiteralDefault('string'),
// The description of the parameter. This may be omitted if
// 'docblock_inherit' is TRUE.
'nullable' => PropertyDefinition::create('boolean'),
'description' => PropertyDefinition::create('string')
->setLiteralDefault('Parameter description.'),
'default_value' => PropertyDefinition::create('string'),
]),
// Whether to put parameter type declarations for PHP primitive types.
// Defaults to FALSE as lots of Drupal functions do this for BC.
'use_primitive_parameter_type_declarations' => PropertyDefinition::create('boolean')
->setInternal(TRUE)
->setLiteralDefault(FALSE),
// NOTE: only affects the code return type when 'declaration' is not used.
'return' => PropertyDefinition::create('complex')
->setInternal(TRUE)
->setProperties([
// Forces no return tag in the docblock.
'omit_return_tag' => PropertyDefinition::create('boolean')
->setLiteralDefault(FALSE),
// The type used in the declaration.
'return_type' => PropertyDefinition::create('string'),
// The type used in the docblock, if this is different from the type
// in the declaration. E.g '\Class[]' where the declaration would have
// 'array'.
'doc_type' => PropertyDefinition::create('string'),
'description' => PropertyDefinition::create('string'),
]),
'body' => PropertyDefinition::create('string')
->setMultiple(TRUE)
->setInternal(TRUE),
// Whether the contents of contained components of content type 'line'
// overrides the 'body' property, or are merged. If merging, the magic
// string 'CONTAINED_COMPONENTS' can be used to insert the components
// instead of appending them.
'body_overriden_by_contained' => PropertyDefinition::create('string')
->setInternal(TRUE)
->setLiteralDefault(FALSE),
// Whether code lines in the 'body' property are already indented relative
// to the indentation of function as a whole.
'body_indented' => PropertyDefinition::create('boolean')
->setInternal(TRUE)
->setLiteralDefault(FALSE),
// Whether this is a procedural function or a class method. Fiddly but
// less so than making a subclass just for this, probably. Defaults to
// TRUE as most things are methods.
'method' => PropertyDefinition::create('boolean')
->setInternal(TRUE)
->setLiteralDefault(TRUE),
]);
}
public static function defaultDocblockLines($data_item) {
if ($data_item->getParent()->docblock_inherit->value) {
return [
'{@inheritdoc}',
];
}
else {
return [
'TODO: write function documentation.',
];
}
}
/**
* {@inheritdoc}
*/
public function getContentType(): string {
return 'function';
}
/**
* {@inheritdoc}
*/
public function getContents(): array {
$function_code = [];
$function_code = array_merge($function_code, $this->getFunctionDocBlockLines());
if ($function_attributes = $this->getFunctionAttributes()) {
$function_code = array_merge(
$function_code,
...array_map(
fn ($attribute) => $attribute->render(),
$function_attributes,
),
);
}
// If the declaration isn't set, built it from property values and contained
// parameter components.
if (empty($this->component_data->declaration->value)) {
$parameters = [];
// Handle parameters set as a property first, then contained components.
foreach ($this->component_data->parameters as $parameter_data) {
$parameters[] = $parameter_data->export();
}
$declaration_lines = $this->buildMethodDeclaration(
$this->component_data->function_name->value,
$parameters,
[
'prefixes' => $this->component_data->prefixes->values(),
'break_declaration' => $this->component_data->break_declaration->value,
],
$this->component_data->return->return_type->value,
);
$function_code = array_merge($function_code, $declaration_lines);
}
else {
$declaration = str_replace('£', '$', $this->component_data['declaration']);
if (!$this->component_data->parameters->isEmpty()) {
// Remove the final closing ')'.
$declaration = rtrim($declaration, ')');
$parameters = [];
foreach ($this->component_data->parameters as $parameter_data) {
$parameter = '';
if (!$parameter_data->typehint->isEmpty()) {
$parameter .= $parameter_data->typehint->value . ' ';
}
$parameter .= '$' . $parameter_data->name->value;
if (!$parameter_data->default_value->isEmpty()) {
$parameter .= ' = ' . $parameter_data->default_value->value;
}
$parameters[] = $parameter;
}
$declaration .= implode(', ', $parameters) . ')';
}
$function_code[] = $declaration . ' {';
}
$body = $this->getFunctionBody();
// Little bit of sugar: to save endless escaping of $ in front of
// variables in code body, you can use £.
$body = array_map(function($line) {
return str_replace('£', '$', $line);
}, $body);
// Add indent.
if (empty($this->component_data->body_indented->value)) {
$body = $this->indentCodeLines($body);
}
$function_code = array_merge($function_code, $body);
$function_code[] = "}";
// TODO: remove this when https://github.com/joachim-n/mutable-typed-data/issues/7
// is fixed.
assert(!empty($this->component_data['function_name']));
return $function_code;
}
/**
* Gets the docblock lines, with docblock formatting.
*
* @return string[]
* An array of lines.
*/
protected function getFunctionDocBlockLines() {
if ($this->component_data->method->value) {
$docblock = DocBlock::method();
}
else {
$docblock = DocBlock::function();
}
// TODO: no need for default value in properties
// An inherit docblock is handled as a default value. Nothing else to do.
if ($this->component_data->docblock_inherit->value) {
return $docblock->inheritdoc()->render();
}
$lines = $this->component_data->function_docblock_lines->value;
foreach ($lines as $line) {
$docblock[] = $line;
}
if (!$this->component_data->parameters->isEmpty() || isset($this->containedComponents['parameter'])) {
// Handle parameters set as a property first, then contained components.
$seen_parameters = [];
foreach ($this->component_data->parameters as $parameter_data) {
// Property parameters may be repeated if they are injected dependencies
// which assign to multiple properties, e.g. pseudoservices.
if (isset($seen_parameters[$parameter_data->name->value])) {
continue;
}
$seen_parameters[$parameter_data->name->value] = TRUE;
// ARGH TODO! Shouldn't this happen somewhere else???
$parameter_data->typehint->applyDefault();
$docblock->param($parameter_data->typehint->value, $parameter_data->name->value, $parameter_data->description->value, $parameter_data->by_reference->value);
}
foreach ($this->containedComponents['parameter'] as $parameter_component) {
$parameter_data = $parameter_component->getContents();
$docblock->param($parameter_data['typehint'], $parameter_data['parameter_name'], $parameter_data['description'], $parameter_data['by_reference'] ?? FALSE);
}
}
// Add a @return tag to the docblock, unless one of the following applies:
// - the function is a constructor
// - omit_return_tag is TRUE,
// - the docblock is an @inheritdoc,
// - the return type is 'void'.
if (
$this->component_data->function_name->value != '__construct'
&& !$this->component_data->return->omit_return_tag->value
&& !$this->component_data->docblock_inherit->value
&& $this->component_data->return->return_type->value != 'void'
) {
if (!$this->component_data->return->doc_type->isEmpty()) {
// Use a documentation-specific return type if there is one.
$doc_return_type = $this->component_data->return->doc_type->value;
}
elseif (!$this->component_data->return->return_type->isEmpty()) {
// Otherwise, use a code return type if there is one.
$doc_return_type = $this->component_data->return->return_type->value;
}
else {
$doc_return_type = NULL;
}
if ($doc_return_type) {
$docblock->return(
$doc_return_type,
$this->component_data->return->description->value ?: 'TODO: write return documentation.',
);
}
else {
$docblock->return(
$this->component_data->return->description->value ?: 'TODO: write return documentation.',
);
}
}
if (!$this->component_data->doxygen_tag_lines->isEmpty()) {
foreach ($this->component_data->doxygen_tag_lines->value as $tag_data) {
$tag = array_shift($tag_data);
$docblock->$tag(...$tag_data);
}
}
return $docblock->render();
}
/**
* Produces the function attributes.
*
* @return \DrupalCodeBuilder\Generator\Render\PhpAttributes[]
* An array of attribute objects if this function has attributes.
*/
protected function getFunctionAttributes(): array {
if ($this->component_data->attribute->isEmpty()) {
return [];
}
else {
return [
PhpAttributes::method($this->component_data->attribute->value),
];
}
}
/**
* Builds the declaration code lines.
*
* @param string $name
* The function name.
* @param array $parameters
* An array of parameters. The key is ignored. Each item is an array with
* keys:
* - 'name'
* - 'typehint'
* - 'by_reference'
* - 'nullable'
* - 'default_value'
* @param array $options
* An array of options:
* - 'prefixes': An array of the function's prefixes.
* - 'break_declaration': Boolean to set whether to put each parameter on
* its own line.
* @param string $return_type
* The return type.
*
* @return array
* An array of code lines.
*/
protected function buildMethodDeclaration($name, $parameters = [], $options = [], string $return_type = NULL): array {
$options += [
'prefixes' => [],
'break_declaration' => FALSE,
];
// Override break_declaration if there are no parameters.
if (empty($parameters)) {
$options['break_declaration'] = FALSE;
}
$code = [];
if ($return_type) {
$closing = "): $return_type {";
}
else {
$closing = ') {';
}
$declaration_line = '';
foreach ($options['prefixes'] as $prefix) {
$declaration_line .= $prefix . ' ';
}
$declaration_line .= 'function ' . $name . '(';
$declaration_line_params = [];
$seen_parameters = [];
foreach ($parameters as $parameter_info) {
if (isset($seen_parameters[$parameter_info['name']])) {
continue;
}
$seen_parameters[$parameter_info['name']] = TRUE;
$declaration_line_params[] = $this->buildParameter($parameter_info);
}
if ($options['break_declaration']) {
// The function declaration up to the opening '(' is one line.
$code[] = $declaration_line;
$last_index = count($declaration_line_params) - 1;
foreach ($declaration_line_params as $index => $param) {
$code[] = ' ' . $param . ',';
}
$code[] = $closing;
}
else {
$declaration_line .= implode(', ', $declaration_line_params);
$declaration_line .= $closing;
$code[] = $declaration_line;
}
return $code;
}
/**
* Builds the string for a single function parameter.
*
* @param array $parameter_info
* The array of data for the parameter from the 'parameters' property.
*
* @return string
* The string for the parameter in the function declaration, with any
* prefixes and the type.
*/
protected function buildParameter(array $parameter_info): string {
$parameter_pieces = [];
$parameter_has_type = !empty($parameter_info['typehint']);
if ($parameter_has_type) {
// Don't type hint primitive types unless explicitly set to do so.
$parameter_should_use_type =
!in_array($parameter_info['typehint'], ['string', 'bool', 'mixed', 'int'])
||
$this->component_data->use_primitive_parameter_type_declarations->value;
}
if (!empty($parameter_should_use_type)) {
$parameter_pieces[] =
(!empty($parameter_info['nullable']) ? '?' : '')
. $parameter_info['typehint'];
}
$parameter_symbol =
(!empty($parameter_info['by_reference']) ? '&' : '')
. '$'
. $parameter_info['name'];
$parameter_pieces[] = $parameter_symbol;
if (isset($parameter_info['default_value'])) {
$parameter_pieces[] = '= ' . PhpValue::create($parameter_info['default_value'])->renderInline();
}
return implode(' ', $parameter_pieces);
}
/**
* Gets body lines of the function.
*
* Overriding this method will override the code lines from the property value
* and contents.
*
* @return string[]
* An array of lines.
*/
protected function getFunctionBody(): array {
$body = [];
// There may be both property data and contained components. Contained
// components override the body if it is set and if
// 'body_overriden_by_contained' is TRUE.
// Check values() rather than isEmpty() so defaults get applied.
$has_body_from_component_data = !empty($this->component_data->body->values());
$has_body_from_contained_components = $this->hasContainedComponentsOfContentType('line');
$let_body_from_contained_components_override_body_from_component_data =
$this->component_data->body_overriden_by_contained->value
&&
$has_body_from_contained_components;
if ($has_body_from_component_data && !$let_body_from_contained_components_override_body_from_component_data) {
$body = is_array($this->component_data['body'])
? $this->component_data['body']
: [$this->component_data['body']];
}
if (isset($this->containedComponents['line'])) {
$contained_component_code_lines = [];
foreach ($this->containedComponents['line'] as $parameter_component) {
$contained_component_code_lines = array_merge($contained_component_code_lines, $parameter_component->getContents());
}
// Contained component content lines are either added at the end, or
// to replace the magic 'CONTAINED_COMPONENTS' lines.
if (in_array('CONTAINED_COMPONENTS', $body)) {
$index = array_search('CONTAINED_COMPONENTS', $body);
array_splice($body, $index, 1, $contained_component_code_lines);
}
else {
$body = array_merge($body, $contained_component_code_lines);
}
}
return $body;
}
}