-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathrunner.php
More file actions
1470 lines (1295 loc) · 50.2 KB
/
Copy pathrunner.php
File metadata and controls
1470 lines (1295 loc) · 50.2 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
namespace WP_Parser;
use phpDocumentor\Reflection\BaseReflector;
use phpDocumentor\Reflection\ClassReflector;
use phpDocumentor\Reflection\ClassReflector\MethodReflector;
use phpDocumentor\Reflection\ClassReflector\PropertyReflector;
use phpDocumentor\Reflection\FunctionReflector;
use phpDocumentor\Reflection\FunctionReflector\ArgumentReflector;
use phpDocumentor\Reflection\ReflectionAbstract;
/**
* @param string $directory
*
* @return array|\WP_Error
*/
function get_wp_files( $directory ) {
$iterableFiles = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator( $directory )
);
$files = array();
try {
foreach ( $iterableFiles as $file ) {
if ( 'php' !== $file->getExtension() ) {
continue;
}
$files[] = $file->getPathname();
}
} catch ( \UnexpectedValueException $exc ) {
return new \WP_Error(
'unexpected_value_exception',
sprintf( 'Directory [%s] contained a directory we can not recurse into', $directory )
);
}
sort( $files );
return $files;
}
/**
* Parses PHP files into records consumed by the importer.
*
* Setup Blueprints flow from file and class DocBlocks to descendants. A
* descendant copies only definitions referenced by one of its snippets.
*
* @param string[] $files PHP source files to parse.
* @param string $root Root path removed from exported file paths.
*
* @return array Parsed file records in input order.
*/
function parse_files( $files, $root ) {
$output = array();
try {
foreach ( $files as $filename ) {
$file = new File_Reflector( $filename );
$path = ltrim( substr( $filename, strlen( $root ) ), DIRECTORY_SEPARATOR );
$file->setFilename( $path );
$file->process();
$file_doc = export_docblock( $file, array(), $path );
$file_setup_blueprints = isset( $file_doc['setup_blueprints'] ) ? $file_doc['setup_blueprints'] : array();
// TODO proper exporter
$out = array(
'file' => $file_doc,
'path' => str_replace( DIRECTORY_SEPARATOR, '/', $file->getFilename() ),
'root' => $root,
);
if ( ! empty( $file->uses ) ) {
$out['uses'] = export_uses( $file->uses );
}
foreach ( $file->getIncludes() as $include ) {
$out['includes'][] = array(
'name' => $include->getName(),
'line' => $include->getLineNumber(),
'type' => $include->getType(),
);
}
foreach ( $file->getConstants() as $constant ) {
$out['constants'][] = array(
'name' => $constant->getShortName(),
'line' => $constant->getLineNumber(),
'value' => export_expression( $constant->getNode()->value ),
);
}
if ( ! empty( $file->uses['hooks'] ) ) {
$out['hooks'] = export_hooks( $file->uses['hooks'], $file_setup_blueprints, $path );
}
foreach ( $file->getFunctions() as $function ) {
$func = array(
'name' => $function->getShortName(),
'namespace' => $function->getNamespace(),
'aliases' => strip_global_namespace_prefixes( $function->getNamespaceAliases() ),
'line' => $function->getLineNumber(),
'end_line' => $function->getNode()->getAttribute( 'endLine' ),
'arguments' => export_arguments( $function->getArguments() ),
'doc' => export_docblock( $function, $file_setup_blueprints, $path ),
'hooks' => array(),
);
if ( ! empty( $function->uses ) ) {
$func['uses'] = export_uses( $function->uses );
if ( ! empty( $function->uses['hooks'] ) ) {
$func['hooks'] = export_hooks( $function->uses['hooks'], $file_setup_blueprints, $path );
}
}
$out['functions'][] = $func;
}
foreach ( $file->getClasses() as $class ) {
$class_doc = export_docblock( $class, $file_setup_blueprints, $path );
$class_setup_blueprints = array_merge( $file_setup_blueprints, isset( $class_doc['setup_blueprints'] ) ? $class_doc['setup_blueprints'] : array() );
$class_data = array(
'name' => $class->getShortName(),
'namespace' => $class->getNamespace(),
'line' => $class->getLineNumber(),
'end_line' => $class->getNode()->getAttribute( 'endLine' ),
'final' => $class->isFinal(),
'abstract' => $class->isAbstract(),
'extends' => strip_global_namespace_prefix( $class->getParentClass() ),
'implements' => strip_global_namespace_prefixes( $class->getInterfaces() ),
'properties' => export_properties( $class->getProperties(), $class_setup_blueprints, $path ),
'methods' => export_methods( $class->getMethods(), $class_setup_blueprints, $path ),
'doc' => $class_doc,
);
$out['classes'][] = $class_data;
}
$output[] = $out;
}
} catch ( \Exception | \Error $e ) {
error_log( \sprintf( 'Error processing file [%s]: %s', $filename, $e->getMessage() ) );
throw $e;
}
return $output;
}
/**
* Remove a synthetic leading namespace prefix from a global name.
*
* @param mixed $name Name to normalize.
*
* @return mixed
*/
function strip_global_namespace_prefix( $name ) {
if ( ! is_string( $name ) ) {
return $name;
}
return preg_replace(
'~^\\\\([A-Z_a-z\x80-\xFF][0-9A-Z_a-z\x80-\xFF]*)([:(\p{Z}]|->|$)~',
'$1$2',
$name
);
}
/**
* Remove synthetic leading namespace prefixes from global names.
*
* @param array $names Names to normalize.
*
* @return array
*/
function strip_global_namespace_prefixes( array $names ) {
foreach ( $names as $key => $name ) {
$names[ $key ] = strip_global_namespace_prefix( $name );
}
return $names;
}
/**
* Export an expression without PHP-Parser's synthetic global namespace prefixes.
*
* @param null|\PhpParser\Node\Expr $expression Expression to export.
*
* @return null|string
*/
function export_expression( $expression ) {
if ( null === $expression ) {
return null;
}
static $printer = null;
if ( null === $printer ) {
$printer = new Pretty_Printer();
}
return $printer->prettyPrintExpr( $expression );
}
/**
* Remove synthetic global namespace prefixes from inline DocBlock references.
*
* A special exception is made for text appearing in `<code>` and `<pre>` tags, as code
* samples are reproduced verbatim and any prefix appearing in them was written by hand.
*
* @param string $text Formatted DocBlock text.
*
* @return string
*/
function strip_global_namespace_prefixes_from_inline_references( $text ) {
// Non-naturally occurring string to use as temporary replacement.
$replacement_string = '{{{{{}}}}}';
// Replace inline tag openings within 'code' and 'pre' tags with replacement string.
$text = preg_replace_callback(
"/(<code[^>]*>)(.+)(?=<\/code>)/sU",
function ( $matches ) use ( $replacement_string ) {
return str_replace( '{@', $replacement_string, $matches[1] . $matches[2] );
},
$text
);
$text = preg_replace_callback(
'~{@(?:link|see)\s+([^}\s]+)~',
static function( $matches ) {
return str_replace(
$matches[1],
strip_global_namespace_prefix( $matches[1] ),
$matches[0]
);
},
$text
);
// Restore inline tag openings into code blocks.
return str_replace( $replacement_string, '{@', $text );
}
/**
* Fixes newline handling in parsed text.
*
* DocBlock lines, particularly for descriptions, generally adhere to a given character width. For sentences and
* paragraphs that exceed that width, what is intended as a manual soft wrap (via line break) is used to ensure
* on-screen/in-file legibility of that text. These line breaks are retained by phpDocumentor. However, consumers
* of this parsed data may believe the line breaks to be intentional and may display the text as such.
*
* This function fixes text by merging consecutive lines of text into a single line. A special exception is made
* for text appearing in `<code>` and `<pre>` tags, as newlines appearing in those tags are always intentional.
*
* @param string $text
*
* @return string
*/
function fix_newlines( $text ) {
// Non-naturally occurring string to use as temporary replacement.
$replacement_string = '{{{{{}}}}}';
// Replace newline characters within 'code' and 'pre' tags with replacement string.
$text = preg_replace_callback(
"/(<pre><code[^>]*>)(.+)(?=<\/code><\/pre>)/sU",
function ( $matches ) use ( $replacement_string ) {
return preg_replace( '/[\n\r]/', $replacement_string, $matches[1] . $matches[2] );
},
$text
);
// Insert a newline when \n follows `.`.
$text = preg_replace(
"/\.[\n\r]+(?!\s*[\n\r])/m",
'.<br>',
$text
);
// Insert a new line when \n is followed by what appears to be a list.
$text = preg_replace(
"/[\n\r]+(\s+[*-] )(?!\s*[\n\r])/m",
'<br>$1',
$text
);
// Merge consecutive non-blank lines together by replacing the newlines with a space.
$text = preg_replace(
"/[\n\r](?!\s*[\n\r])/m",
' ',
$text
);
// Restore newline characters into code blocks.
$text = str_replace( $replacement_string, "\n", $text );
return $text;
}
/**
* Exports one reflected DocBlock and its runnable snippet metadata.
*
* Fenced descriptions are recovered from source because phpDocumentor may
* interpret PHP lines beginning with `@` as tags. Named setup references may
* resolve against definitions inherited from the enclosing file or class.
*
* @param BaseReflector|ReflectionAbstract $element Reflected DocBlock owner.
* @param array $inherited_setup_blueprints Setup Blueprints visible from enclosing scopes.
* @param string $source_file Source path used in metadata errors.
*
* @throws \InvalidArgumentException When snippet metadata is invalid or ambiguous.
*
* @return array Exported descriptions, tags, snippets, and referenced setup Blueprints.
*/
function export_docblock( $element, array $inherited_setup_blueprints = array(), $source_file = '' ) {
$node_docblock = null;
$node_docblock_key = null;
$node_comments = array();
$node_source_docblock = null;
$docblock_was_sanitized = $element instanceof File_Reflector && $element->wasDocBlockSanitized();
if ( ! ( $element instanceof File_Reflector ) && method_exists( $element, 'getNode' ) ) {
$node = $element->getNode();
if ( $node && method_exists( $node, 'getDocComment' ) ) {
$node_docblock = $node->getDocComment();
if ( $node_docblock ) {
$node_comments = (array) $node->getAttribute( 'comments' );
$node_docblock_key = array_search( $node_docblock, $node_comments, true );
$node_source_docblock = (string) $node_docblock;
}
}
}
$docblock = $element->getDocBlock();
if ( ! $docblock && null !== $node_source_docblock && false !== strpos( $node_source_docblock, '```' ) ) {
/*
* phpDocumentor does not recognize fences. A fenced line beginning with `@`
* starts its tag block, and a later PHP expression such as `@! file_exists()`
* can make the whole DocBlock fail to parse.
*
* Blank only the bodies of complete fences and retry, leaving the fence
* markers and line structure intact. Restore the original AST comment
* immediately afterward. The parsed object supplies tags and namespace
* context; the untouched $node_source_docblock supplies descriptions and
* snippet code below.
*/
$sanitized_docblock = sanitize_docblock_fenced_contents( $node_source_docblock );
if ( $sanitized_docblock !== $node_source_docblock ) {
$node_comments[ $node_docblock_key ] = new \PhpParser\Comment\Doc(
$sanitized_docblock,
$node_docblock->getStartLine(),
$node_docblock->getStartFilePos(),
$node_docblock->getStartTokenPos(),
$node_docblock->getEndLine(),
$node_docblock->getEndFilePos(),
$node_docblock->getEndTokenPos()
);
$node->setAttribute( 'comments', $node_comments );
try {
$docblock = $element->getDocBlock();
} finally {
$node_comments[ $node_docblock_key ] = $node_docblock;
$node->setAttribute( 'comments', $node_comments );
}
$docblock_was_sanitized = (bool) $docblock;
}
}
if ( ! $docblock ) {
return array(
'description' => '',
'long_description' => '',
'tags' => array(),
);
}
$fenced_docblock_tag_names = array();
try {
$short_description = $docblock->getShortDescription();
$raw_long_description = $docblock->getLongDescription()->getContents();
$source_docblock = null;
/*
* phpDocumentor can split one fenced block across its short and long
* descriptions, alter its line structure, and parse `@` code as tags. For
* example, this source:
*
* ```php interactive
* <?php
*
* echo 'before';
* @unlink( '/tmp/example' );
* ```
*
* can leave the opening lines in the short description, the `echo` line in the
* long description, and `@unlink` in the tag list. If either description
* contains a possible fence, recover the original DocBlock before tokenizing
* it below. File reflectors require slicing the comment from the file contents;
* node-backed reflectors use the raw comment captured above.
*/
if ( false !== strpos( $short_description, '```' ) || false !== strpos( $raw_long_description, '```' ) ) {
if ( $element instanceof File_Reflector ) {
$location = $docblock->getLocation();
if ( $location && $location->getLineNumber() ) {
$source_lines = explode( "\n", preg_replace( "/\r\n?/", "\n", $element->getContents() ) );
$source_line = $location->getLineNumber() - 1;
$source_line_count = count( $source_lines );
if ( isset( $source_lines[ $source_line ] ) ) {
$opening = strpos( $source_lines[ $source_line ], '/**' );
if ( false !== $opening ) {
$source_lines[ $source_line ] = substr( $source_lines[ $source_line ], $opening );
$source_docblock_lines = array();
for ( ; $source_line < $source_line_count; $source_line++ ) {
$source_docblock_lines[] = $source_lines[ $source_line ];
if ( false !== strpos( $source_lines[ $source_line ], '*/' ) ) {
break;
}
}
$source_docblock = implode( "\n", $source_docblock_lines );
}
}
}
} elseif ( null !== $node_source_docblock ) {
$source_docblock = $node_source_docblock;
}
}
if ( null !== $source_docblock ) {
/*
* Recover exact description lines from source and stop at the first tag
* outside a fence. For example:
*
* ```php
* @since( 'inside-fence' );
* ```
* @since 1.0.0
*
* The first `@since` remains snippet code; the second ends the description.
* Record the first name so only phpDocumentor's false in-fence tag is
* removed from the parsed tags, leaving the real `@since 1.0.0` tag.
*/
$source_docblock = preg_replace( "/\r\n?/", "\n", $source_docblock );
$source_docblock = preg_replace( '/\A[ \t]*\/\*\*[ \t]?/', '', $source_docblock );
$source_docblock = preg_replace( '/[ \t]*\*\/[ \t]*\z/', '', $source_docblock );
$source_lines = explode( "\n", $source_docblock );
foreach ( $source_lines as $key => $source_line ) {
$source_lines[ $key ] = preg_replace( '/^[ \t]*\*[ \t]?/', '', $source_line );
}
// Reuse tokenizer boundaries so source recovery and snippet export agree
// on which exact backtick runs delimit complete fences.
$source_fences = tokenize_docblock_code_fences( implode( "\n", $source_lines ) );
$source_fence_index = 0;
$description_lines = array();
$parsed_tag_block_started = false;
foreach ( $source_lines as $source_line_number => $source_line ) {
while (
isset( $source_fences[ $source_fence_index ] ) &&
$source_line_number >= $source_fences[ $source_fence_index ]['end']
) {
$source_fence_index++;
}
$is_in_fence = isset( $source_fences[ $source_fence_index ] ) &&
$source_line_number > $source_fences[ $source_fence_index ]['start'];
/*
* Before tag parsing starts, `^[ \t]*` permits indentation and `\pL`
* requires a Unicode letter: ` @since` matches, while `@_before` does not.
* Once started, `^@` requires column zero and the broader name class permits
* an initial underscore or digit: `@_same` and `@2inside` match, while
* ` @author` remains part of the preceding tag.
*/
$tag_pattern = $parsed_tag_block_started
? '/^@([\w\-_\\\\]+)/u'
: '/^[ \t]*@([\pL][\w\-_\\\\]*)/u';
if ( preg_match( $tag_pattern, $source_line, $tag_match ) ) {
if ( ! $is_in_fence ) {
break;
}
$parsed_tag_block_started = true;
$fenced_docblock_tag_names[] = $tag_match[1];
}
$description_lines[] = $source_line;
}
// Remove blank wrapper lines without stripping indentation from a fence
// that begins or ends the description. That indentation controls both
// content dedenting and the fence's Markdown nesting level.
$description_edge_pattern = '/\A(?:[ \t]*\n)+|(?:\n[ \t]*)+\z/';
$source_description = preg_replace( $description_edge_pattern, '', implode( "\n", $description_lines ) );
if ( $docblock_was_sanitized ) {
// Sanitized parsing never created the false in-fence tags, so every
// parsed tag belongs to the actual DocBlock tag section.
$fenced_docblock_tag_names = array();
}
if ( preg_match( '/(?:\A|\n)[ \t]*`{3,}[^`\n]*(?=\n|\z)/', $short_description ) ) {
$raw_long_description = $source_description;
$short_description = '';
} elseif ( '' !== $short_description && 0 === strpos( $source_description, $short_description ) ) {
$raw_long_description = preg_replace( $description_edge_pattern, '', substr( $source_description, strlen( $short_description ) ) );
} elseif ( '' !== $raw_long_description ) {
$long_description_start = strpos( $source_description, $raw_long_description );
if ( false !== $long_description_start ) {
$raw_long_description = preg_replace( $description_edge_pattern, '', substr( $source_description, $long_description_start ) );
}
}
}
// phpDocumentor assigns the first DocBlock paragraph to the short
// description and can split it at a blank line inside a fence. Detect an
// opening line without requiring its closer, then rejoin both descriptions
// before parsing so the fence retains its line structure and metadata pairing.
if ( '' !== $short_description && preg_match( '/(?:\A|\n)[ \t]*`{3,}[^`\n]*(?=\n|\z)/', $short_description ) ) {
$raw_long_description = $short_description . ( '' === $raw_long_description ? '' : "\n\n" . $raw_long_description );
$short_description = '';
}
$fences = get_docblock_code_fences( $raw_long_description );
// Reusing an enclosing name would make the same reference resolve to
// different setup depending on which DocBlock is being exported.
foreach ( $fences as $fence ) {
if (
null !== $fence['setup_name'] &&
array_key_exists( $fence['setup_name'], $inherited_setup_blueprints )
) {
throw new \InvalidArgumentException(
'Setup Blueprint "' . $fence['setup_name'] . '" on line ' . ( $fence['start'] + 1 ) .
' of the long description is already defined in an enclosing DocBlock.'
);
}
}
$setup_blueprints = array();
$code_snippets = export_docblock_code_snippets( $raw_long_description, $setup_blueprints, $fences );
// Copy only referenced inherited setups into this DocBlock's output. Each
// imported post then contains everything its snippets need without copying
// every file- or class-level setup into every descendant.
$referenced_inherited_setup_blueprints = array();
$snippet_lines = array();
foreach ( $fences as $fence ) {
if ( $fence['is_interactive_php'] ) {
$snippet_lines[ $fence['snippet_index'] ] = $fence['start'] + 1;
}
}
foreach ( $code_snippets as $index => $snippet ) {
if ( ! isset( $snippet['blueprint'] ) || ! is_string( $snippet['blueprint'] ) ) {
continue;
}
if ( array_key_exists( $snippet['blueprint'], $inherited_setup_blueprints ) ) {
$referenced_inherited_setup_blueprints[ $snippet['blueprint'] ] = $inherited_setup_blueprints[ $snippet['blueprint'] ];
continue;
}
if ( ! array_key_exists( $snippet['blueprint'], $setup_blueprints ) ) {
throw new \InvalidArgumentException(
'Setup Blueprint "' . $snippet['blueprint'] . '" referenced on line ' .
$snippet_lines[ $index ] . ' of the long description is not defined.'
);
}
}
$setup_blueprints = array_merge( $referenced_inherited_setup_blueprints, $setup_blueprints );
} catch ( \InvalidArgumentException $exception ) {
throw new \InvalidArgumentException(
describe_docblock_source( $element, $docblock, $source_file ) . ': ' . $exception->getMessage(),
0,
$exception
);
}
$output = array(
'description' => strip_global_namespace_prefixes_from_inline_references(
preg_replace( '/[\n\r]+/', ' ', $short_description )
),
'long_description' => strip_global_namespace_prefixes_from_inline_references(
format_long_description( strip_docblock_code_snippet_fences( $raw_long_description, $fences ) )
),
'tags' => array(),
);
if ( ! empty( $code_snippets ) ) {
$output['code_snippets'] = $code_snippets;
}
if ( ! empty( $setup_blueprints ) ) {
$output['setup_blueprints'] = $setup_blueprints;
}
$fenced_docblock_tag_counts = array_count_values( $fenced_docblock_tag_names );
foreach ( $docblock->getTags() as $tag ) {
if ( ! empty( $fenced_docblock_tag_counts[ $tag->getName() ] ) ) {
$fenced_docblock_tag_counts[ $tag->getName() ]--;
continue;
}
$tag_data = array(
'name' => $tag->getName(),
'content' => strip_global_namespace_prefixes_from_inline_references(
preg_replace( '/[\n\r]+/', ' ', format_description( $tag->getDescription() ) )
),
);
if ( method_exists( $tag, 'getTypes' ) ) {
$tag_data['types'] = strip_global_namespace_prefixes( $tag->getTypes() );
}
if ( method_exists( $tag, 'getLink' ) ) {
$tag_data['link'] = strip_global_namespace_prefix( $tag->getLink() );
}
if ( method_exists( $tag, 'getVariableName' ) ) {
$tag_data['variable'] = $tag->getVariableName();
}
if ( method_exists( $tag, 'getReference' ) ) {
$tag_data['refers'] = strip_global_namespace_prefix( $tag->getReference() );
}
if ( method_exists( $tag, 'getVersion' ) ) {
// Version string.
$version = $tag->getVersion();
if ( ! empty( $version ) ) {
$tag_data['content'] = $version;
}
// Description string.
if ( method_exists( $tag, 'getDescription' ) ) {
$description = strip_global_namespace_prefixes_from_inline_references(
preg_replace( '/[\n\r]+/', ' ', format_description( $tag->getDescription() ) )
);
if ( ! empty( $description ) ) {
$tag_data['description'] = $description;
}
}
}
$output['tags'][] = $tag_data;
}
return $output;
}
/**
* Returns a parser-safe DocBlock with complete fence bodies replaced by blanks.
*
* phpDocumentor does not recognize Markdown fences. It can mistake a fenced
* `@unlink(...)` call for a DocBlock tag, then reject a later expression such as
* `@! file_exists(...)` as a malformed tag. For example, these comment lines:
*
* * ```php
* * @unlink( '/tmp/example' );
* * @! file_exists( '/tmp/example' );
* * ```
* * @since 1.0.0
*
* are returned as:
*
* * ```php
* *
* *
* * ```
* * @since 1.0.0
*
* The fence delimiters and physical line count remain. Decorated body lines
* retain their indentation and `*`, and tags outside fences remain unchanged.
* phpDocumentor can therefore parse the real `@since` tag, while callers read
* descriptions and snippets from the original DocBlock. Keeping the fence
* delimiters also tells export_docblock() to recover that original source.
*
* An unmatched outer fence is not blanked because its body boundary is unknown.
*
* @param string $source_docblock Raw DocBlock including comment delimiters.
*
* @return string Parser-safe DocBlock, or the unchanged input when it contains
* no complete fence.
*/
function sanitize_docblock_fenced_contents( $source_docblock ) {
$original_source_docblock = $source_docblock;
// Normalize line endings so tokenizer indexes map to physical source lines.
$source_docblock = preg_replace( "/\r\n?/", "\n", $source_docblock );
// Remove the opener and at most one decorative whitespace byte.
$contents = preg_replace( '/\A[ \t]*\/\*\*[ \t]?/', '', $source_docblock );
// Remove only the end-anchored closing delimiter and its indentation.
$contents = preg_replace( '/[ \t]*\*\/[ \t]*\z/', '', $contents );
$content_lines = explode( "\n", $contents );
foreach ( $content_lines as $key => $line ) {
// Remove the decorative star and at most one following whitespace byte.
$content_lines[ $key ] = preg_replace( '/^[ \t]*\*[ \t]?/', '', $line );
}
$fences = tokenize_docblock_code_fences( implode( "\n", $content_lines ) );
if ( empty( $fences ) ) {
return $original_source_docblock;
}
$source_lines = explode( "\n", $source_docblock );
foreach ( $fences as $fence ) {
for ( $line = $fence['start'] + 1; $line < $fence['end']; $line++ ) {
// Retain indentation and the decorative star while blanking body text.
$source_lines[ $line ] = preg_match( '/^([ \t]*\*)/', $source_lines[ $line ], $prefix ) ? $prefix[1] : '';
}
}
return implode( "\n", $source_lines );
}
/**
* Describes the source DocBlock that contains invalid snippet metadata.
*
* @param BaseReflector|ReflectionAbstract $element
* @param \phpDocumentor\Reflection\DocBlock $docblock
* @param string $source_file Optional source path.
*
* @return string
*/
function describe_docblock_source( $element, $docblock, $source_file = '' ) {
if ( $element instanceof File_Reflector ) {
$entity = 'file';
} elseif ( $element instanceof Hook_Reflector ) {
$entity = 'hook "' . $element->getName() . '"';
} elseif ( $element instanceof PropertyReflector ) {
$entity = 'property "' . $element->getName() . '"';
} elseif ( $element instanceof MethodReflector ) {
$entity = 'method "' . $element->getShortName() . '"';
} elseif ( $element instanceof FunctionReflector ) {
$entity = 'function "' . $element->getShortName() . '"';
} elseif ( $element instanceof ClassReflector ) {
$entity = 'class "' . $element->getShortName() . '"';
} else {
$entity = 'element';
}
$source = '' !== $source_file ? ' in ' . $source_file : '';
if ( $docblock->getLocation() && $docblock->getLocation()->getLineNumber() ) {
$source .= ' starting on source line ' . $docblock->getLocation()->getLineNumber();
}
return 'DocBlock for ' . $entity . $source;
}
/**
* @param Hook_Reflector[] $hooks
* @param array $inherited_setup_blueprints Optional. Setup Blueprints inherited from the enclosing file or class.
* @param string $source_file Optional. Source path used in invalid snippet metadata errors.
*
* @return array
*/
function export_hooks( array $hooks, array $inherited_setup_blueprints = array(), $source_file = '' ) {
$out = array();
foreach ( $hooks as $hook ) {
$out[] = array(
'name' => $hook->getName(),
'line' => $hook->getLineNumber(),
'end_line' => $hook->getNode()->getAttribute( 'endLine' ),
'type' => $hook->getType(),
'arguments' => $hook->getArgs(),
'doc' => export_docblock( $hook, $inherited_setup_blueprints, $source_file ),
);
}
return $out;
}
/**
* @param ArgumentReflector[] $arguments
*
* @return array
*/
function export_arguments( array $arguments ) {
$output = array();
foreach ( $arguments as $argument ) {
$output[] = array(
'name' => $argument->getName(),
'default' => export_expression( $argument->getNode()->default ),
'type' => strip_global_namespace_prefix( $argument->getType() ),
);
}
return $output;
}
/**
* @param PropertyReflector[] $properties
* @param array $inherited_setup_blueprints Optional. Setup Blueprints inherited from the file or class DocBlock.
* @param string $source_file Optional. Source path used in invalid snippet metadata errors.
*
* @return array
*/
function export_properties( array $properties, array $inherited_setup_blueprints = array(), $source_file = '' ) {
$out = array();
foreach ( $properties as $property ) {
$out[] = array(
'name' => $property->getName(),
'line' => $property->getLineNumber(),
'end_line' => $property->getNode()->getAttribute( 'endLine' ),
'default' => export_expression( $property->getNode()->default ),
// 'final' => $property->isFinal(),
'static' => $property->isStatic(),
'visibility' => $property->getVisibility(),
'doc' => export_docblock( $property, $inherited_setup_blueprints, $source_file ),
);
}
return $out;
}
/**
* @param MethodReflector[] $methods
* @param array $inherited_setup_blueprints Optional. Setup Blueprints inherited from the file or class DocBlock.
* @param string $source_file Optional. Source path used in invalid snippet metadata errors.
*
* @return array
*/
function export_methods( array $methods, array $inherited_setup_blueprints = array(), $source_file = '' ) {
$output = array();
foreach ( $methods as $method ) {
$method_data = array(
'name' => $method->getShortName(),
'namespace' => $method->getNamespace(),
'aliases' => strip_global_namespace_prefixes( $method->getNamespaceAliases() ),
'line' => $method->getLineNumber(),
'end_line' => $method->getNode()->getAttribute( 'endLine' ),
'final' => $method->isFinal(),
'abstract' => $method->isAbstract(),
'static' => $method->isStatic(),
'visibility' => $method->getVisibility(),
'arguments' => export_arguments( $method->getArguments() ),
'doc' => export_docblock( $method, $inherited_setup_blueprints, $source_file ),
);
if ( ! empty( $method->uses ) ) {
$method_data['uses'] = export_uses( $method->uses );
if ( ! empty( $method->uses['hooks'] ) ) {
$method_data['hooks'] = export_hooks( $method->uses['hooks'], $inherited_setup_blueprints, $source_file );
}
}
$output[] = $method_data;
}
return $output;
}
/**
* Returns Markdown-like backtick fences from a DocBlock's raw long description.
*
* @param string $text Raw DocBlock long description.
*
* @return array
*/
function get_docblock_code_fences( $text ) {
if ( preg_match( '/<!--[ \t]wp-parser-code-snippet(?:-placeholder)?:[0-9]+[ \t]-->/', $text ) ) {
throw new \InvalidArgumentException(
'The DocBlock placeholder comment syntax is reserved for generated snippet placement.'
);
}
$fences = tokenize_docblock_code_fences( $text );
foreach ( $fences as $key => $fence ) {
$info_parts = '' === $fence['info'] ? array() : preg_split( '/\s+/', $fence['info'] );
// Match the complete public grammar before validating any option value.
// Setup-looking text on a non-interactive PHP fence remains ordinary
// documentation and must not make an existing DocBlock fail to parse.
$referenced_setup = null;
$is_interactive_php = false;
if ( 'php' === $fence['language'] && isset( $info_parts[1] ) && 'interactive' === $info_parts[1] ) {
if ( 2 === count( $info_parts ) ) {
$is_interactive_php = true;
} elseif ( 3 === count( $info_parts ) && 0 === strpos( $info_parts[2], 'setup-blueprint=' ) ) {
$referenced_setup = substr( $info_parts[2], strlen( 'setup-blueprint=' ) );
validate_docblock_setup_blueprint_name( $referenced_setup, $fence['start'] );
$is_interactive_php = true;
}
}
$setup_name = null;
if ( 'setup-blueprint' === $fence['language'] && 2 === count( $info_parts ) ) {
$setup_name = $info_parts[1];
validate_docblock_setup_blueprint_name( $setup_name, $fence['start'] );
}
$is_expected_output = 'expected-output' === $fence['language'] && 1 === count( $info_parts );
$is_blueprint = 'setup-blueprint' === $fence['language'] && 1 === count( $info_parts );
$fences[ $key ]['referenced_setup'] = $referenced_setup;
$fences[ $key ]['is_interactive_php'] = $is_interactive_php;
$fences[ $key ]['is_expected_output'] = $is_expected_output;
$fences[ $key ]['is_blueprint'] = $is_blueprint;
$fences[ $key ]['setup_name'] = $setup_name;
$fences[ $key ]['is_code_snippet'] = $is_interactive_php || $is_expected_output || $is_blueprint || null !== $setup_name;
}
// Number the interactive PHP fences so the exporter and the stripper agree on each
// snippet's index without counting independently.
$snippet_index = 0;
foreach ( $fences as $key => $fence ) {
$fences[ $key ]['snippet_index'] = $fence['is_interactive_php'] ? $snippet_index++ : null;
}
return $fences;
}
/**
* Tokenizes complete backtick fences without interpreting their info strings.
*
* The raw-source recovery path needs fence boundaries before phpDocumentor has
* successfully parsed the comment. Keeping that lexical pass separate prevents
* invalid snippet metadata from escaping before export_docblock() can add source
* context to the resulting error.
*
* @param string $text Raw DocBlock contents or long description.
*
* @return array
*/
function tokenize_docblock_code_fences( $text ) {
$text = preg_replace( "/\r\n?/", "\n", $text );
$lines = explode( "\n", $text );
$line_count = count( $lines );
$fences = array();
// Advance the outer cursor to each matching closer. Every line is examined
// at most once, and matching does not depend on PCRE recursion or JIT stack
// size. An opener without a matching closer stops parsing so later fence-like
// lines remain part of that unterminated block.
for ( $line_no = 0; $line_no < $line_count; $line_no++ ) {
if ( ! preg_match( '/^([ \t]*)(`{3,})([^`]*)$/', $lines[ $line_no ], $opening ) ) {
continue;
}
$indent = $opening[1];
$backticks = $opening[2];
$closing_pattern = '/^[ \t]*' . preg_quote( $backticks, '/' ) . '[ \t]*$/';
$end = $line_no + 1;
while ( $end < $line_count && ! preg_match( $closing_pattern, $lines[ $end ] ) ) {
$end++;
}
if ( $end === $line_count ) {
break;
}
$code_lines = array_slice( $lines, $line_no + 1, $end - $line_no - 1 );
if ( '' !== $indent ) {
// Content may be less indented than its fence, so remove as much of the
// opening prefix as each line repeats. Stop where tabs and spaces differ
// rather than guessing that unlike whitespace occupies equal columns.
foreach ( $code_lines as $key => $code_line ) {
$remove_length = 0;
$max_length = min( strlen( $indent ), strlen( $code_line ) );
while ( $remove_length < $max_length && $indent[ $remove_length ] === $code_line[ $remove_length ] ) {
$remove_length++;
}
if ( 0 < $remove_length ) {
$code_lines[ $key ] = substr( $code_line, $remove_length );
}
}
}
$info = trim( $opening[3] );
$language = $info;
if ( preg_match( '/^\S+/', $language, $language_matches ) ) {
$language = $language_matches[0];
}
$fence = array(
'language' => $language,
'info' => $info,
'code' => rtrim( implode( "\n", $code_lines ), "\n" ),
'start' => $line_no,
'end' => $end,
);
$fences[] = $fence;
$line_no = $end;
}
return $fences;
}
/**
* Extract PHP fences marked `interactive` from a DocBlock's raw long description.
*
* Backtick fences may be indented in DocBlocks or nested Markdown lists. The
* closing fence must use the same number of backticks as the opener so
* different-length fences can appear inside a fenced snippet. Blueprint fences
* before a PHP fence apply to that fence, while immediately following metadata
* fences apply to the preceding PHP fence. Named setup Blueprint fences are
* exported once and snippets refer to them by name. Fence info words are
* case-sensitive so the documented lowercase forms are the only accepted syntax.
* Reusable setup Blueprint names use lowercase kebab-case starting with a letter.