Repository navigation
Expand file tree
/
Copy pathdocs.php
More file actions
2387 lines (1992 loc) · 74.8 KB
/
Copy pathdocs.php
File metadata and controls
2387 lines (1992 loc) · 74.8 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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Reference documentation generator.
*
* It parses the PHP attributes and docblock comments of the traits under the
* vocabulary directory and writes:
*
* - STEPS.md, the step vocabulary, and the step index in README.md.
* - HELPERS.md, the toolbox a project calls from its own domain steps.
* - The generated tables in docs/configuration.md.
*
* It also validates that:
*
* - The steps read in the documented format.
* - Every published helper carries a summary.
* - Registered parametrized tags use `:` as their value separator.
* - Every environment variable the source reads is documented.
*
* Run with --fail-on-change to fail if the documentation is not up to date.
* Run with --path=path/to/dir to use another repository root: the autoloader,
* the sources and the written documents all resolve under it.
*/
declare(strict_types=1);
use Behat\Behat\Definition\Pattern\Policy\TurnipPatternPolicy;
use Behat\Step\Given;
use Behat\Step\Then;
use Behat\Step\When;
use DrevOps\BehatSteps\Behat\Config\ConfigSchemaReader;
use DrevOps\BehatSteps\Behat\Config\GroupName;
use DrevOps\BehatSteps\Behat\Config\Option;
use DrevOps\BehatSteps\Behat\Config\TagOverrideResolver;
use DrevOps\BehatSteps\Behat\Context\DrupalContext;
use DrevOps\BehatSteps\Behat\Context\WebContext;
use DrevOps\BehatSteps\Behat\Context\WebRawContext;
use DrevOps\BehatSteps\Behat\Prerequisite\Prerequisite;
use DrevOps\BehatSteps\Behat\Prerequisite\PrerequisiteReader;
use DrevOps\BehatSteps\Behat\ServiceContainer\BehatStepsExtension;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\BooleanNode;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\IntegerNode;
use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\PrototypedArrayNode;
/**
* Matches a first-person pronoun anywhere in a step.
*
* A `When` narrates what the person does and reads in the first person. A
* `Given` states a precondition and a `Then` names the entity it asserts on,
* so neither refers to the person at all.
*/
const FIRST_PERSON = '/\b(I|[Mm]y|[Mm]e|[Mm]yself|[Ww]e|[Uu]s|[Oo]ur)\b/';
/**
* Directory holding the step vocabulary, relative to the repository root.
*
* Each directory directly below it is a context and gives its traits their
* context name.
*/
const STEPS_DIRECTORY = 'src/Steps';
/**
* Context whose traits are named and sorted without their context prefix.
*
* Its traits head the index, so the documents lead with the steps a suite
* uses first. Their example features carry no name prefix.
*/
const DEFAULT_CONTEXT = 'Web';
/**
* Attribute namespaces that mark a method as registered with Behat.
*
* A method carrying one of these is a step, a hook or a transformation, so it
* is not part of the toolbox.
*/
const REGISTERED_ATTRIBUTE_PREFIXES = [
'Behat\\Step\\',
'Behat\\Hook\\',
'Behat\\Transformation\\',
'DrevOps\\BehatSteps\\Behat\\Hook\\Attribute\\',
];
/**
* Directory holding the helper traits, relative to the repository root.
*/
const HELPERS_DIRECTORY = 'src/Helper';
/**
* Classes published in the toolbox reference alongside the step traits.
*
* The root context contributes the backend access and the scenario plumbing a
* domain step is written against, so that surface is part of the toolbox too.
*/
const TOOLBOX_CLASSES = [WebRawContext::class];
/**
* File holding the toolbox reference, relative to the repository root.
*/
const HELPERS_FILE = 'HELPERS.md';
/**
* File holding the configuration reference, relative to the repository root.
*/
const CONFIGURATION_FILE = 'docs/configuration.md';
// The main function runs only when the script is run directly, not when it
// is included.
// @codeCoverageIgnoreStart
if (basename((string) $_SERVER['SCRIPT_FILENAME']) === 'docs.php') {
$options = getopt('', ['fail-on-change', 'path::']);
main($options);
}
// @codeCoverageIgnoreEnd
/**
* Main function to handle the documentation generation process.
*
* @param array<string, bool|string|array<int, string>> $options
* Command line options.
*
* @codeCoverageIgnoreStart
*/
function main(array $options = []): void {
$base_path = is_string($options['path'] ?? NULL) ? $options['path'] : __DIR__;
require_once $base_path . '/build/vendor/autoload.php';
$contexts = [WebContext::class, DrupalContext::class];
$info = extract_info($contexts, [], $base_path);
$helpers = extract_helpers($contexts, [], $base_path);
$errors = validate($info);
$errors = array_merge($errors, validate_step_patterns($info));
$errors = array_merge($errors, validate_helpers($helpers));
$errors = array_merge($errors, validate_tags($info, $base_path));
$errors = array_merge($errors, validate_env_vars($base_path));
if (!empty($errors)) {
echo 'Errors found:' . PHP_EOL;
foreach ($errors as $error) {
echo $error;
}
exit(1);
}
$targets = [
'STEPS.md' => [
['# Available steps', '[//]: # (END)', PHP_EOL . render_info($info, $base_path) . PHP_EOL],
],
'README.md' => [
['## Available steps', '[//]: # (END)', PHP_EOL . render_info($info, $base_path, 'STEPS.md') . PHP_EOL],
],
HELPERS_FILE => [
['# Available helpers', '[//]: # (END)', PHP_EOL . render_helpers($helpers, $base_path) . PHP_EOL],
],
CONFIGURATION_FILE => [
[
'[//]: # (START_EXTENSION_OPTIONS)',
'[//]: # (END_EXTENSION_OPTIONS)',
PHP_EOL . render_extension_options() . PHP_EOL,
],
['[//]: # (START_TAGS)', '[//]: # (END_TAGS)', PHP_EOL . render_tag_reference() . PHP_EOL],
],
];
$outdated = [];
$updated = [];
foreach ($targets as $file => $regions) {
$path = $base_path . '/' . $file;
$contents = file_get_contents($path);
if ($contents === FALSE) {
printf('Failed to read %s.' . PHP_EOL, $file);
exit(1);
}
$replaced = $contents;
foreach ($regions as $region) {
$replaced = replace_content($replaced, $region[0], $region[1], $region[2]);
}
if ($replaced !== $contents) {
$outdated[] = $file;
$updated[$path] = $replaced;
}
}
if ($outdated === []) {
echo 'Documentation is up to date. No changes were made.' . PHP_EOL;
exit(0);
}
if (isset($options['fail-on-change'])) {
printf('Documentation is outdated: %s. No changes were made.' . PHP_EOL, implode(', ', $outdated));
exit(1);
}
foreach ($updated as $path => $contents) {
file_put_contents($path, $contents);
}
printf('Documentation updated: %s.' . PHP_EOL, implode(', ', $outdated));
}
// @codeCoverageIgnoreEnd
/**
* Check whether a PHP file declares a trait.
*
* @param string $file_path
* Path to the PHP file.
*
* @return bool
* TRUE when the file declares a trait.
*/
function file_declares_trait(string $file_path): bool {
$contents = file_get_contents($file_path);
return $contents !== FALSE && preg_match('/^\s*trait\s+\w+/m', $contents) === 1;
}
/**
* Collect the vocabulary traits composed into the given classes.
*
* Every trait declared under the vocabulary directory has to be composed into
* one of the classes, so a reference document covers the whole vocabulary
* rather than the part one context uses.
*
* @param array<int, class-string> $class_names
* The classes documenting the vocabulary, 1 per context.
* @param array<int, string> $exclude
* Array of trait names to exclude.
* @param string $base_path
* Base path for the repository.
*
* @return array<string, array{reflection: \ReflectionClass<object>, context: string, host: class-string}>
* The trait reflection, its context and the class composing it, keyed by
* trait short name and sorted by that name.
*
* @throws \ReflectionException
*/
function collect_step_traits(array $class_names, array $exclude = [], string $base_path = __DIR__): array {
$traits_path = $base_path . '/' . STEPS_DIRECTORY;
$traits_files = [];
if (is_dir($traits_path)) {
$contexts = scandir($traits_path) ?: [];
foreach ($contexts as $context) {
$context_path = $traits_path . '/' . $context;
if (!is_dir($context_path) || $context === '.' || $context === '..') {
continue;
}
$context_files = scandir($context_path) ?: [];
foreach ($context_files as $context_file) {
$context_file_path = $context_path . '/' . $context_file;
if (is_file($context_file_path) && file_declares_trait($context_file_path)) {
$traits_files[] = basename($context_file, '.php');
}
}
}
sort($traits_files);
}
// Entries are removed from $traits_files as each trait is found, so the
// membership test below reads a copy taken first.
$vocabulary = $traits_files;
$collected = [];
foreach ($class_names as $class_name) {
$reflection = new \ReflectionClass($class_name);
foreach ($reflection->getTraits() as $trait) {
$trait_name = $trait->getShortName();
// A context composes helper traits beside the vocabulary, and only the
// vocabulary belongs in the step reference. The directory a trait sits
// in determines which it is.
if (!in_array($trait_name, $vocabulary, TRUE)) {
continue;
}
if (in_array($trait_name, $traits_files, TRUE)) {
unset($traits_files[array_search($trait_name, $traits_files, TRUE)]);
}
if (in_array($trait_name, $exclude, TRUE)) {
continue;
}
$trait_file_path = $trait->getFileName();
// @codeCoverageIgnoreStart
if (!$trait_file_path) {
throw new \RuntimeException(sprintf('Trait %s does not have a file path', $trait_name));
}
// @codeCoverageIgnoreEnd
$relative_path = str_replace($base_path . DIRECTORY_SEPARATOR . STEPS_DIRECTORY . DIRECTORY_SEPARATOR, '', $trait_file_path);
$context = explode(DIRECTORY_SEPARATOR, $relative_path)[0];
$collected[$trait_name] = ['reflection' => $trait, 'context' => $context, 'host' => $class_name];
}
}
if (!empty($traits_files)) {
throw new \RuntimeException(sprintf('The following traits were not found in the class: %s', implode(', ', $traits_files)));
}
uksort($collected, strcasecmp(...));
return $collected;
}
/**
* Collect the helper traits the package publishes.
*
* Every trait of the directory is published, and the directory marks it as
* plumbing rather than vocabulary. The half it sits in names the context it
* is available to, so the reference groups helpers the way the steps are
* grouped.
*
* @param string $base_path
* Base path for the repository.
*
* @return array<string, array{reflection: \ReflectionClass<object>, context: string}>
* The trait reflection and its half, keyed by short name and sorted by that
* name.
*
* @throws \ReflectionException
*/
function collect_helper_traits(string $base_path = __DIR__): array {
$helpers_path = $base_path . '/' . HELPERS_DIRECTORY;
$collected = [];
if (!is_dir($helpers_path)) {
return $collected;
}
foreach (scandir($helpers_path) ?: [] as $context) {
$context_path = $helpers_path . '/' . $context;
if ($context === '.' || $context === '..' || !is_dir($context_path)) {
continue;
}
foreach (scandir($context_path) ?: [] as $file) {
$file_path = $context_path . '/' . $file;
if (!is_file($file_path) || !file_declares_trait($file_path)) {
continue;
}
$short_name = basename($file, '.php');
/** @var class-string $trait_name */
$trait_name = 'DrevOps\\BehatSteps\\Helper\\' . $context . '\\' . $short_name;
$collected[$short_name] = ['reflection' => new \ReflectionClass($trait_name), 'context' => $context];
}
}
uksort($collected, strcasecmp(...));
return $collected;
}
/**
* Parse info from the classes.
*
* @param array<int, class-string> $class_names
* The classes documenting the vocabulary, 1 per context.
* @param array<int, string> $exclude
* Array of trait names to exclude.
* @param string $base_path
* Base path for the repository.
*
* @return array<string, array<string, mixed>>
* Array of info with 'name', 'name_contextual', 'context', 'methods',
* 'options', 'prerequisites', 'description' and 'description_full' keys.
*
* @throws \ReflectionException
*/
function extract_info(array $class_names, array $exclude = [], string $base_path = __DIR__): array {
$info = [];
foreach (collect_step_traits($class_names, $exclude, $base_path) as $trait_name => $collected) {
$trait = $collected['reflection'];
$context = $collected['context'];
$class_info = [
'name' => $trait_name,
'name_contextual' => ($context !== DEFAULT_CONTEXT ? $context . '\\' : '') . $trait_name,
'context' => $context,
'methods' => [],
'options' => extract_trait_options($collected['host'], $trait_name),
'prerequisites' => extract_trait_prerequisites($collected['host'], $trait->getName()),
];
$class_info += parse_class_comment($trait_name, (string) $trait->getDocComment());
$methods = $trait->getMethods(\ReflectionMethod::IS_PUBLIC);
$trait_prefix = str_replace('Trait', '', $trait_name);
// Methods group by the keyword of their first step, so the reference lists
// Given steps first and Then steps last.
$methods_by_keyword = ['@Given' => [], '@When' => [], '@Then' => []];
foreach ($methods as $method) {
if (!str_starts_with(strtolower($method->getName()), strtolower($trait_prefix))) {
continue;
}
$steps = extract_method_steps($method);
if (empty($steps)) {
continue;
}
$parsed_comment = parse_method_comment((string) $method->getDocComment());
$methods_by_keyword[explode(' ', $steps[0], 2)[0]][] = [
'steps' => $steps,
'description' => $parsed_comment['description'] ?? '',
'example' => $parsed_comment['example'] ?? '',
'name' => $method->getName(),
];
}
$class_info['methods'] = array_merge(...array_values($methods_by_keyword));
$info[$trait_name] = $class_info;
}
return $info;
}
/**
* Read the option declarations of one trait.
*
* Discovery goes through the reader the runtime uses, so the generator rejects
* a malformed declaration with the same message rather than documenting an
* incomplete option table.
*
* @param string $class_name
* The context class composing the trait.
* @param string $trait_name
* The short trait name.
*
* @return array<string, \DrevOps\BehatSteps\Behat\Config\Option>
* Options keyed by name, empty when the trait declares none.
*/
function extract_trait_options(string $class_name, string $trait_name): array {
return (new ConfigSchemaReader())->read($class_name)[trait_option_group($trait_name)] ?? [];
}
/**
* Convert a trait name to the group its options are configured under.
*
* @param string $trait_name
* The short trait name.
*
* @return string
* The group name, in snake case.
*/
function trait_option_group(string $trait_name): string {
return GroupName::fromTraitName($trait_name);
}
/**
* Read the prerequisite declarations of one trait.
*
* Discovery goes through the reader the runtime uses, so the generator rejects
* a malformed declaration with the same message.
*
* @param string $class_name
* The context class composing the trait.
* @param string $trait
* The fully qualified trait name.
*
* @return array<int, \DrevOps\BehatSteps\Behat\Prerequisite\Prerequisite>
* The prerequisites in declaration order, empty when the trait declares
* none.
*/
function extract_trait_prerequisites(string $class_name, string $trait): array {
/** @var class-string $class_name */
$context = (new \ReflectionClass($class_name))->newInstanceWithoutConstructor();
return (new PrerequisiteReader())->read($context, $trait);
}
/**
* Parse class comment.
*
* @param string $trait_name
* The trait name.
* @param string $comment
* The comment.
*
* @return array<string, string>
* Array of 'description' and 'description_full' keys.
*/
function parse_class_comment(string $trait_name, string $comment): array {
if (empty($comment)) {
throw new \RuntimeException(sprintf('Class comment for %s is empty', $trait_name));
}
$comment = preg_replace('#^/\*\*|^\s*\*\/$#m', '', $comment);
$lines = explode("\n", (string) $comment);
// Strips the docblock asterisk and at most 1 space, so any further
// indentation is preserved.
$lines = array_map(static fn(string $line): string => preg_replace('/^\s*\* ?/', '', $line), $lines);
if (count($lines) > 1 && empty($lines[0])) {
array_shift($lines);
}
if (count($lines) > 1 && empty($lines[count($lines) - 1])) {
array_pop($lines);
}
$in_code_block = FALSE;
$lines = array_map(static function (string $line) use (&$in_code_block): string {
if (str_starts_with(trim($line), '@code')) {
$in_code_block = TRUE;
return trim($line);
}
if (str_starts_with(trim($line), '@endcode')) {
$in_code_block = FALSE;
return trim($line);
}
if ($in_code_block) {
return rtrim($line);
}
return trim($line);
}, $lines);
// Static-analysis annotations state the trait's contract for tooling, not
// for the reader of the generated documentation.
$lines = array_values(array_filter($lines, static fn(string $line): bool => !str_starts_with($line, '@phpstan-')));
while ($lines !== [] && end($lines) === '') {
array_pop($lines);
}
if (empty($lines)) {
throw new \RuntimeException(sprintf('Class comment for %s is empty', $trait_name));
}
$description = $lines[0];
if (empty($description)) {
throw new \RuntimeException(sprintf('Class comment for %s is empty', $trait_name));
}
if (str_starts_with($description, 'Trait ')) {
throw new \RuntimeException(sprintf('Class comment should have a descriptive content for %s', $trait_name));
}
$full_description = implode(PHP_EOL, $lines);
if (substr_count($full_description, '`') % 2 !== 0) {
throw new \RuntimeException(sprintf('Class inline code block is not closed for %s', $trait_name));
}
return [
'description' => $description,
'description_full' => $full_description,
];
}
/**
* Parse comment.
*
* Extracts description and example from the docblock comment.
*
* @param string $comment
* The comment.
*
* @return array<string, string>|null
* Array of 'description' and 'example' keys or NULL if the comment is empty.
*/
function parse_method_comment(string $comment): ?array {
if (empty($comment)) {
return NULL;
}
$return = [
'description' => '',
'example' => '',
];
$lines = explode("\n", $comment);
$example_start = FALSE;
foreach ($lines as $line) {
$line = str_replace('/*', '', $line);
$line = str_replace('/**', '', $line);
$line = str_replace('*/', '', $line);
$line = preg_replace('/^\s*\*/', '', $line);
$line = rtrim((string) $line, " \t\n\r\0\x0B");
// All docblock lines start with a space.
$line = substr($line, 1);
if (str_starts_with($line, '@code')) {
$example_start = TRUE;
}
elseif (str_starts_with($line, '@endcode')) {
$example_start = FALSE;
}
else {
if (!$example_start && empty($line)) {
continue;
}
if ($example_start) {
$line = rtrim($line, "\t\n\r\0\x0B");
$return['example'] .= $line . PHP_EOL;
}
if (empty($return['description'])) {
$line = trim($line);
$return['description'] .= $line . ' ';
}
}
}
if ($example_start) {
throw new \RuntimeException('Example not closed');
}
$return['description'] = trim($return['description']);
if (!empty($return['example'])) {
$lines = explode(PHP_EOL, $return['example']);
$first_line = '';
foreach ($lines as $line) {
if ($line !== '') {
$first_line = $line;
break;
}
}
$indentation = strspn($first_line, ' ');
foreach ($lines as $key => $line) {
$line = rtrim($line);
if (strlen($line) > $indentation) {
$lines[$key] = substr($line, $indentation);
}
}
$return['example'] = implode(PHP_EOL, $lines);
}
return $return;
}
/**
* Extract step patterns from method attributes.
*
* @param \ReflectionMethod $method
* The reflection method.
*
* @return array<int, string>
* Array of step patterns prefixed with @Given, @When, or @Then.
*/
function extract_method_steps(\ReflectionMethod $method): array {
$step_classes = [
Given::class => '@Given',
When::class => '@When',
Then::class => '@Then',
];
$steps = [];
foreach ($step_classes as $class => $prefix) {
$attributes = $method->getAttributes($class);
foreach ($attributes as $attribute) {
$args = $attribute->getArguments();
$pattern = $args[0] ?? $args['pattern'] ?? NULL;
if ($pattern !== NULL) {
$steps[] = $prefix . ' ' . $pattern;
}
}
}
$sorted = [];
foreach (['@Given', '@When', '@Then'] as $step_prefix) {
foreach ($steps as $step) {
if (str_starts_with($step, $step_prefix)) {
$sorted[] = $step;
}
}
}
return $sorted;
}
/**
* Check whether a method is registered with Behat.
*
* @param \ReflectionMethod $method
* The reflection method.
*
* @return bool
* TRUE when the method carries a step, hook or transformation attribute.
*/
function method_is_registered(\ReflectionMethod $method): bool {
foreach ($method->getAttributes() as $attribute) {
foreach (REGISTERED_ATTRIBUTE_PREFIXES as $prefix) {
if (str_starts_with($attribute->getName(), $prefix)) {
return TRUE;
}
}
}
return FALSE;
}
/**
* Check whether a docblock excludes the member from the published API.
*
* @param string $comment
* The docblock comment.
*
* @return bool
* TRUE when the comment carries an '@internal' tag.
*/
function comment_is_internal(string $comment): bool {
return preg_match('/^\s*\*\s*@internal\b/m', $comment) === 1;
}
/**
* Render a type declaration as it reads in a signature.
*
* @param \ReflectionType|null $type
* The reflection type, or NULL when the declaration has none.
*
* @return string
* The type with class names shortened, or an empty string when untyped.
*/
function render_type(?\ReflectionType $type): string {
$short = static function (string $name): string {
$position = strrpos($name, '\\');
return $position === FALSE ? $name : substr($name, $position + 1);
};
if ($type instanceof \ReflectionNamedType) {
$name = $short($type->getName());
$is_nullable = $type->allowsNull() && !in_array($name, ['mixed', 'null'], TRUE);
return ($is_nullable ? '?' : '') . $name;
}
if ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) {
$glue = $type instanceof \ReflectionUnionType ? '|' : '&';
$parts = array_map(render_type(...), $type->getTypes());
return implode($glue, $parts);
}
return '';
}
/**
* Render a value as it reads in PHP source.
*
* @param mixed $value
* The value.
*
* @return string
* The rendered value.
*/
function render_value(mixed $value): string {
if ($value === NULL) {
return 'NULL';
}
if (is_bool($value)) {
return $value ? 'TRUE' : 'FALSE';
}
if (is_array($value)) {
return $value === [] ? '[]' : '[...]';
}
if (is_string($value)) {
return "'" . $value . "'";
}
return is_scalar($value) ? (string) $value : 'object';
}
/**
* Render a trait's option declarations as a markdown table.
*
* @param string $trait_name
* The short trait name.
* @param mixed $options
* The options the trait declared, keyed by option name.
*
* @return string
* The table, or an empty string when the trait declares no option.
*/
function render_trait_options(string $trait_name, mixed $options): string {
$group = trait_option_group($trait_name);
$rows = [];
foreach (is_array($options) ? $options : [] as $option) {
if (!$option instanceof Option) {
continue;
}
$tags = array_keys($option->tags);
if ($option->name === Option::ENABLED) {
$tags[] = TagOverrideResolver::SKIP_TAG_PREFIX . $trait_name;
}
$tags = array_map(static fn(string $tag): string => '`@' . $tag . '`', $tags);
$rows[] = [
sprintf('`%s.%s`', $group, $option->name),
trait_option_type($option->default),
sprintf('`%s`', render_value($option->default)),
$tags === [] ? '-' : implode(', ', $tags),
str_replace('|', '\\|', $option->description),
];
}
if ($rows === []) {
return '';
}
return '### Options' . PHP_EOL . PHP_EOL . array_to_markdown_table(['Option', 'Type', 'Default', 'Tag', 'Description'], $rows) . PHP_EOL . PHP_EOL;
}
/**
* Render a trait's prerequisite declarations as a markdown table.
*
* @param mixed $prerequisites
* The prerequisites the trait declared, in declaration order.
*
* @return string
* The table, or an empty string when the trait declares none.
*/
function render_trait_prerequisites(mixed $prerequisites): string {
$rows = [];
foreach (is_array($prerequisites) ? $prerequisites : [] as $prerequisite) {
if (!$prerequisite instanceof Prerequisite) {
continue;
}
$rows[] = [
str_replace('|', '\\|', ucfirst($prerequisite->description)),
sprintf('`%s`', basename(str_replace('\\', '/', $prerequisite->capability))),
];
}
if ($rows === []) {
return '';
}
return '### Prerequisites' . PHP_EOL . PHP_EOL . array_to_markdown_table(['Prerequisite', 'Capability'], $rows) . PHP_EOL . PHP_EOL;
}
/**
* Name the type of an option, taken from the type its default carries.
*
* @param mixed $default
* The declared default.
*
* @return string
* The type name, in the vocabulary the configuration reference uses.
*/
function trait_option_type(mixed $default): string {
return match (get_debug_type($default)) {
'bool' => 'boolean',
'int' => 'integer',
'float' => 'float',
'array' => 'map',
default => 'string',
};
}
/**
* Render a method signature.
*
* @param \ReflectionMethod $method
* The reflection method.
*
* @return string
* The signature, with class names shortened to their class part.
*/
function render_method_signature(\ReflectionMethod $method): string {
$parameters = [];
foreach ($method->getParameters() as $parameter) {
$type = render_type($parameter->getType());
$rendered = $type === '' ? '' : $type . ' ';
$rendered .= ($parameter->isVariadic() ? '...' : '') . '$' . $parameter->getName();
if ($parameter->isDefaultValueAvailable()) {
$rendered .= ' = ' . render_value($parameter->getDefaultValue());
}
$parameters[] = $rendered;
}
$return = render_type($method->getReturnType());
return sprintf(
'%s%s function %s(%s)%s',
$method->isPublic() ? 'public' : 'protected',
$method->isStatic() ? ' static' : '',
$method->getName(),
implode(', ', $parameters),
$return === '' ? '' : ': ' . $return
);
}
/**
* Render the anchor a trait heading resolves to.
*
* @param string $name
* The contextual trait name, such as 'Drupal\ContentTrait'.
*
* @return string
* The anchor, without the leading hash.
*/
function heading_anchor(string $name): string {
return (string) preg_replace('/[^A-Za-z0-9_\-]/', '', strtolower($name));
}
/**
* Parse the toolbox helpers from the class.
*
* A helper is a public method a project calls from its own domain steps: one
* carrying no Behat attribute and no '@internal' tag.
*
* @param array<int, class-string> $class_names
* The classes documenting the vocabulary, 1 per context.
* @param array<int, string> $exclude
* Array of trait names to exclude.
* @param string $base_path
* Base path for the repository.
*
* @return array<string, array<string, mixed>>
* Array of info with 'name', 'name_contextual', 'context', 'source',
* 'steps_anchor', 'helpers', 'description' and 'description_full' keys,
* keyed by trait short name. Traits contributing no helper are left out.
*
* @throws \ReflectionException
*/
function extract_helpers(array $class_names, array $exclude = [], string $base_path = __DIR__): array {
$info = [];
foreach (collect_step_traits($class_names, $exclude, $base_path) as $trait_name => $collected) {
$trait = $collected['reflection'];
$context = $collected['context'];
$helpers = collect_helper_methods($trait, str_replace('Trait', '', $trait_name), (string) $trait->getFileName());
if ($helpers === []) {
continue;
}
$name_contextual = ($context !== DEFAULT_CONTEXT ? $context . '\\' : '') . $trait_name;
$class_info = [
'name' => $trait_name,
'name_contextual' => $name_contextual,
'context' => $context,
'source' => sprintf('%s/%s/%s.php', STEPS_DIRECTORY, $context, $trait_name),
'steps_anchor' => heading_anchor($name_contextual),
'helpers' => $helpers,
];