-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathgenerate-parsed-md.php
745 lines (643 loc) · 20.6 KB
/
generate-parsed-md.php
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
#!/usr/bin/env php
<?php
/**
* Generate parsed markdown documentation from PHP source files.
*
* @package wordpress/secure-custom-fields
*/
namespace WordPress\SCF\Docs;
// phpcs:disable WordPress.WP.AlternativeFunctions
require dirname( dirname( __DIR__ ) ) . '/vendor/autoload.php';
use PhpParser\{ParserFactory, NodeTraverser, Node, Node\Stmt\Class_};
use PhpParser\NodeVisitor\NameResolver;
use Symfony\Component\Finder\Finder;
/**
* Documentation generator class that parses PHP files and generates markdown.
*/
class DocGenerator {
/**
* PHP Parser instance.
*
* @var \PhpParser\Parser
*/
private $parser;
/**
* Node traverser instance.
*
* @var NodeTraverser
*/
private $traverser;
/**
* Output directory path.
*
* @var string
*/
private $output_dir;
/**
* Files organized by directory.
*
* @var array
*/
private $files_by_directory = array();
/**
* WordPress hook functions to document.
*
* @var array
*/
private $hook_functions = array(
'do_action',
'do_action_ref_array',
'do_action_deprecated',
'apply_filters',
'apply_filters_ref_array',
'apply_filters_deprecated',
);
/**
* Mapping of hook functions to their types.
*
* @var array
*/
private $hook_type_map = array(
'do_action' => 'action',
'do_action_ref_array' => 'action',
'do_action_deprecated' => 'deprecated',
'apply_filters' => 'filter',
'apply_filters_ref_array' => 'filter',
'apply_filters_deprecated' => 'deprecated',
);
/**
* Tracks undocumented code elements.
*
* @var array
*/
private $undocumented_elements = array();
/**
* File suffix and extension constants.
*/
private const FILE_SUFFIX = '-file';
private const MD_EXT = '.md';
private const PHP_EXT = '.php';
/**
* Constructor.
*
* @param string $output_dir Directory where documentation will be generated.
*/
public function __construct( $output_dir ) {
$parser_factory = new ParserFactory();
$this->parser = $parser_factory->create( ParserFactory::PREFER_PHP7 );
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor( new NameResolver() );
$this->output_dir = rtrim( $output_dir, '/' );
// Clean up existing documentation
if ( is_dir( $this->output_dir ) ) {
$this->cleanup_directory( $this->output_dir );
}
if ( ! is_dir( $this->output_dir ) ) {
mkdir( $this->output_dir, 0755, true );
}
}
/**
* Recursively remove all files and subdirectories from a directory.
*
* @param string $dir Directory path to clean.
*/
private function cleanup_directory( $dir ) {
$files = array_diff( scandir( $dir ), array( '.', '..' ) );
foreach ( $files as $file ) {
$path = $dir . '/' . $file;
if ( is_dir( $path ) ) {
$this->cleanup_directory( $path );
rmdir( $path );
} else {
unlink( $path );
}
}
}
/**
* Generate documentation for all PHP files.
*/
public function generate() {
$finder = new Finder();
$finder->files()
->name( '*.php' )
->in( dirname( dirname( __DIR__ ) ) . '/includes' )
->exclude( 'vendor' );
foreach ( $finder as $file ) {
$this->process_file( $file );
}
// Generate META.md with undocumented elements
$this->generate_meta_file();
// After processing all files, generate index files
$this->generate_index_files();
}
/**
* Process a single PHP file to extract documentation.
*
* @param \Symfony\Component\Finder\SplFileInfo $file The file to process.
*/
private function process_file( $file ) {
$code = file_get_contents( $file->getRealPath() );
$ast = $this->parser->parse( $code );
if ( ! $ast ) {
return;
}
// Track relative path for undocumented elements
$relative_path = str_replace(
dirname( dirname( __DIR__ ) ) . '/includes/',
'',
$file->getRealPath()
);
$docs = $this->extract_docs( $ast, $relative_path );
if ( $docs ) {
$this->save_markdown( $file, $docs );
}
}
/**
* Extract documentation from an AST.
*
* @param array $ast The PHP Parser AST.
* @param string $file_path The relative path to the file being processed.
* @return array Extracted documentation organized by type.
*/
private function extract_docs( array $ast, $file_path ) {
$docs = array();
foreach ( $ast as $node ) {
// Handle standalone functions
if ( $node instanceof Node\Stmt\Function_ ) {
if ( ! isset( $docs['functions'] ) ) {
$docs['functions'] = array();
}
$doc = $node->getDocComment();
if ( $doc ) {
$docs['functions'][ $node->name->toString() ] = $this->format_doc_block( $doc );
} else {
// Track undocumented function
$this->track_undocumented( $file_path, 'function', $node->name->toString() );
}
}
// Handle classes
if ( $node instanceof Node\Stmt\Class_ ) {
$docs['class'] = $this->extract_class_docs( $node, $file_path );
}
// Handle hooks
$hooks = $this->extract_hooks( $node, $file_path );
if ( ! empty( $hooks ) ) {
if ( ! isset( $docs['hooks'] ) ) {
$docs['hooks'] = array();
}
$docs['hooks'] = array_merge( $docs['hooks'], $hooks );
}
}
return $docs;
}
/**
* Extract documentation from a class node.
*
* @param Node\Stmt\Class_ $node The class node.
* @param string $file_path The relative path to the file.
* @return array Class documentation including properties and methods.
*/
private function extract_class_docs( Node\Stmt\Class_ $node, $file_path ) {
$doc = $node->getDocComment();
if ( ! $doc ) {
$this->track_undocumented( $file_path, 'class', $node->name->toString() );
}
$docs = array(
'name' => $node->name->toString(),
'doc' => $doc ? $this->format_doc_block( $doc ) : '',
'properties' => $this->extract_property_docs( $node, $file_path ),
'methods' => $this->extract_method_docs( $node, $file_path ),
);
return $docs;
}
/**
* Extract documentation from class properties.
*
* @param Node\Stmt\Class_ $node The class node.
* @param string $file_path The relative path to the file.
* @return array Property documentation keyed by property name.
*/
private function extract_property_docs( Node\Stmt\Class_ $node, $file_path ) {
$properties = array();
foreach ( $node->getProperties() as $property ) {
$doc = $property->getDocComment();
if ( $doc ) {
foreach ( $property->props as $prop ) {
$properties[ $prop->name->toString() ] = $this->format_doc_block( $doc );
}
} else {
foreach ( $property->props as $prop ) {
$this->track_undocumented( $file_path, 'property', $prop->name->toString() );
}
}
}
return $properties;
}
/**
* Extract documentation from class methods.
*
* @param Node\Stmt\Class_ $node The class node.
* @param string $file_path The relative path to the file.
* @return array Method documentation keyed by method name.
*/
private function extract_method_docs( Node\Stmt\Class_ $node, $file_path ) {
$methods = array();
foreach ( $node->getMethods() as $method ) {
$doc = $method->getDocComment();
if ( $doc ) {
$methods[ $method->name->toString() ] = $this->format_doc_block( $doc );
} else {
$this->track_undocumented( $file_path, 'method', $method->name->toString() );
}
}
return $methods;
}
/**
* Extract WordPress hooks from an AST node.
*
* @param Node $node The AST node to check.
* @param string $file_path The relative path to the file.
* @return array Extracted hook documentation.
*/
private function extract_hooks( $node, $file_path ) {
$hooks = array();
if ( $node instanceof Node\Expr\FuncCall && $node->name instanceof Node\Name ) {
$function_name = $node->name->toString();
if ( in_array( $function_name, $this->hook_functions, true ) ) {
if ( isset( $node->args[0] ) && $node->args[0]->value instanceof Node\Scalar\String_ ) {
$hook_name = $node->args[0]->value->value;
$doc = '';
if ( $node->getAttribute( 'comments' ) ) {
foreach ( $node->getAttribute( 'comments' ) as $comment ) {
if ( $comment instanceof \PhpParser\Comment\Doc ) {
$doc = $this->format_doc_block( $comment );
break;
}
}
}
if ( ! $doc ) {
$this->track_undocumented( $file_path, 'hook', $hook_name );
}
$hooks[] = array(
'type' => $this->hook_type_map[ $function_name ],
'name' => $hook_name,
'doc' => $doc,
'function' => $function_name,
);
}
}
}
// Recursively check child nodes
foreach ( $node->getSubNodeNames() as $node_name ) {
$sub_node = $node->$node_name;
if ( $sub_node instanceof Node || is_array( $sub_node ) ) {
if ( is_array( $sub_node ) ) {
foreach ( $sub_node as $sub_sub_node ) {
if ( $sub_sub_node instanceof Node ) {
$hooks = array_merge( $hooks, $this->extract_hooks( $sub_sub_node, $file_path ) );
}
}
} else {
$hooks = array_merge( $hooks, $this->extract_hooks( $sub_node, $file_path ) );
}
}
}
return $hooks;
}
/**
* Format a docblock comment by removing comment markers.
*
* @param \PhpParser\Comment\Doc $doc The docblock comment.
* @return string Cleaned documentation text.
*/
private function format_doc_block( $doc ) {
$text = $doc->getText();
// Clean up the doc block
$text = preg_replace( '/^\s*\/\*\*\s*/m', '', $text );
$text = preg_replace( '/^\s*\*\s*/m', '', $text );
$text = preg_replace( '/\s*\*\/\s*$/', '', $text );
$text = preg_replace( '/\s*\/\s*$/', '', $text );
$text = preg_replace( '/\n\s*$/', '', $text );
$text = trim( $text );
// Normalize URL formatting - remove angle brackets
$text = preg_replace( '/<(https?:\/\/[^>]+)>/', '$1', $text );
// Convert @param, @return, @since, etc. into list items
$text = preg_replace(
'/^@(param|return|since|date|deprecated|var|package|type)\s+/m',
'* @$1 ',
$text
);
return $text;
}
/**
* Track an undocumented code element.
*
* @param string $file The file path where the element was found.
* @param string $type The type of element (class, method, property, etc.).
* @param string $name The name of the undocumented element.
*/
private function track_undocumented( $file, $type, $name ) {
if ( ! isset( $this->undocumented_elements[ $file ] ) ) {
$this->undocumented_elements[ $file ] = array();
}
if ( ! isset( $this->undocumented_elements[ $file ][ $type ] ) ) {
$this->undocumented_elements[ $file ][ $type ] = array();
}
$this->undocumented_elements[ $file ][ $type ][] = $name;
}
/**
* Generate index files for each directory of documentation.
*/
private function generate_index_files() {
foreach ( $this->files_by_directory as $dir => $files ) {
// Sort files for consistent order
sort( $files );
// Handle root directory differently
if ( '' === $dir || '.' === $dir ) {
$index_path = $this->output_dir . '/index.md';
} else {
// For subdirectories, just use index.md
$index_path = $this->output_dir . '/' . $dir . '/index.md';
}
// Special handling for root code reference index
if ( '' === $dir ) {
$index_content = '# Code Reference' . "\n\n";
} else {
// Format directory name for title
$dir_title = $this->format_directory_title( $dir );
$index_content = '# ' . $dir_title . "\n\n";
}
$index_content .= '## Files' . "\n\n";
foreach ( $files as $file ) {
$basename = basename( $file, '.md' );
$title = $this->format_file_title( $basename );
$index_content .= '- [' . $title . '](' . $basename . ')' . "\n";
}
// Ensure file ends with single newline and no trailing spaces
$index_content = rtrim( rtrim( $index_content ), "\n" ) . "\n";
// Create directory if it doesn't exist
$dir_path = dirname( $index_path );
if ( ! is_dir( $dir_path ) ) {
mkdir( $dir_path, 0755, true );
}
file_put_contents( $index_path, $index_content );
}
}
/**
* Format directory title with special cases.
*
* @param string $dir Directory name.
* @return string Formatted title.
*/
private function format_directory_title( $dir ) {
if ( 'rest-api' === $dir ) {
return 'REST API';
}
return '.' === $dir ? 'Code Reference' : ucwords( str_replace( '/', ' ', $dir ) );
}
/**
* Format file title with special cases.
*
* @param string $basename File basename.
* @return string Formatted title.
*/
private function format_file_title( $basename ) {
// Replace common patterns
$title = str_replace(
array(
'rest-api',
'acf-rest-api',
'class-acf-rest',
'-file',
),
array(
'REST API',
'ACF REST API',
'Class ACF REST',
'',
),
$basename
);
// Convert to title case and handle special words
$title = ucwords( str_replace( '-', ' ', $title ) );
return $title;
}
/**
* Generate the META.md file containing undocumented elements and duplicate hooks.
*/
private function generate_meta_file() {
if ( empty( $this->undocumented_elements ) ) {
return;
}
$markdown = "# Undocumented Code Elements\n\n";
$markdown .= "This file tracks code elements that need documentation.\n\n";
// Track duplicate hooks
$hook_counts = array();
foreach ( $this->files_by_directory['hooks'] ?? array() as $hook_file ) {
$file_path = $this->output_dir . '/hooks/' . $hook_file;
if ( file_exists( $file_path ) ) {
$content = file_get_contents( $file_path );
preg_match_all( '/^## `([^`]+)`/m', $content, $matches );
foreach ( $matches[1] as $hook_name ) {
if ( ! isset( $hook_counts[ $hook_name ] ) ) {
$hook_counts[ $hook_name ] = 0;
}
++$hook_counts[ $hook_name ];
}
}
}
// Add duplicate hooks section if any found
$duplicate_hooks = array_filter(
$hook_counts,
function ( $count ) {
return $count > 1;
}
);
if ( ! empty( $duplicate_hooks ) ) {
$markdown .= "# Duplicate Hooks\n\n";
arsort( $duplicate_hooks ); // Sort by count, highest first
foreach ( $duplicate_hooks as $hook => $count ) {
$markdown .= "- `{$hook}` (used {$count} times)\n";
}
$markdown .= "\n";
}
// Sort files alphabetically
ksort( $this->undocumented_elements );
foreach ( $this->undocumented_elements as $file => $types ) {
$markdown .= '## ' . $file . "\n\n";
// Sort types of elements(class, method, property, hook, function).
ksort( $types );
foreach ( $types as $type => $elements ) {
$markdown .= '### ' . ucfirst( $type ) . "s\n\n";
// Sort elements alphabetically
sort( $elements );
foreach ( $elements as $element ) {
$markdown .= '- `' . $element . "`\n";
}
$markdown .= "\n";
}
}
file_put_contents( $this->output_dir . '/META.md', $markdown );
}
/**
* Save markdown documentation to appropriate files.
*
* @param \Symfony\Component\Finder\SplFileInfo $file The source file.
* @param array $docs The documentation to save.
*/
private function save_markdown( $file, $docs ) {
if ( empty( $docs ) ) {
return;
}
// Handle hooks separately
if ( ! empty( $docs['hooks'] ) ) {
$markdown = '';
// Group hooks by type
$grouped_hooks = array();
foreach ( $docs['hooks'] as $hook ) {
$type = $hook['type'];
if ( ! isset( $grouped_hooks[ $type ] ) ) {
$grouped_hooks[ $type ] = array();
}
$grouped_hooks[ $type ][] = $hook;
}
// Create hooks directory if it doesn't exist
$hooks_dir = $this->output_dir . '/hooks';
if ( ! is_dir( $hooks_dir ) ) {
mkdir( $hooks_dir, 0755, true );
}
// Save each hook type to its own file
foreach ( $grouped_hooks as $type => $hooks ) {
$hook_markdown = '# ' . ucfirst( str_replace( '_', ' ', $type ) ) . "\n\n";
foreach ( $hooks as $hook ) {
$hook_markdown .= "## `{$hook['name']}`\n\n";
if ( ! empty( $hook['doc'] ) ) {
$hook_markdown .= "{$hook['doc']}\n\n";
}
// Add file reference
$hook_markdown .= '_Defined in: ' . str_replace( dirname( dirname( __DIR__ ) ) . '/includes/', '', $file->getRealPath() ) . "_\n\n";
}
$hook_file = $hooks_dir . '/' . $type . '.md';
// Load existing content
$existing_content = file_exists( $hook_file ) ? file_get_contents( $hook_file ) . "\n" : '';
$hook_markdown = $existing_content . $hook_markdown;
// Track hook files for index generation
if ( ! isset( $this->files_by_directory['hooks'] ) ) {
$this->files_by_directory['hooks'] = array();
}
if ( ! in_array( basename( $hook_file ), $this->files_by_directory['hooks'], true ) ) {
$this->files_by_directory['hooks'][] = basename( $hook_file );
}
}
// After processing all hooks, sort each file
foreach ( $this->files_by_directory['hooks'] as $hook_file ) {
$file_path = $hooks_dir . '/' . $hook_file;
if ( file_exists( $file_path ) ) {
// Read the file
$content = file_get_contents( $file_path );
// Split into sections (each hook documentation)
$sections = preg_split( '/(?=^## )/m', $content );
// Keep the title section (first section starting with # )
$title = array_shift( $sections );
// Sort the remaining sections
sort( $sections, SORT_STRING | SORT_FLAG_CASE );
// Combine and write back
file_put_contents( $file_path, $title . implode( '', $sections ) );
}
}
// Remove hooks from docs array so they're not included in the main file
unset( $docs['hooks'] );
}
// Handle regular documentation
if ( ! empty( $docs ) ) {
$relative_path = str_replace(
dirname( dirname( __DIR__ ) ) . '/includes/',
'',
$file->getRealPath()
);
// Add -file suffix before .md extension
$output_path = $this->output_dir . '/' . preg_replace(
'/' . self::PHP_EXT . '$/',
self::FILE_SUFFIX . self::MD_EXT,
$relative_path
);
$output_dir = dirname( $output_path );
if ( ! is_dir( $output_dir ) ) {
mkdir( $output_dir, 0755, true );
}
$markdown = $this->generate_markdown( $docs, $relative_path );
file_put_contents( $output_path, $markdown );
// Track files by directory for index generation
$relative_dir = dirname( $relative_path );
if ( ! isset( $this->files_by_directory[ $relative_dir ] ) ) {
$this->files_by_directory[ $relative_dir ] = array();
}
$this->files_by_directory[ $relative_dir ][] = basename( $output_path );
}
}
/**
* Generate markdown content from documentation array.
*
* @param array $docs Documentation organized by type.
* @param string $source_path The relative path to the source file.
* @return string Generated markdown content.
*/
private function generate_markdown( $docs, $source_path ) {
$markdown = '';
// Generate standalone functions documentation
if ( ! empty( $docs['functions'] ) ) {
// Convert file path to title
// e.g., "api/api-helpers.php" becomes "API Helpers"
$file_title = basename( $source_path, self::PHP_EXT );
$file_title = str_replace( '-', ' ', $file_title );
$file_title = ucwords( $file_title );
// Special handling for "api" to become "API"
$file_title = preg_replace( '/\b[Aa]pi\b/', 'API', $file_title );
$markdown .= $this->format_title( $file_title . ' Global Functions' ) . "\n\n";
foreach ( $docs['functions'] as $name => $doc ) {
$markdown .= '## `' . $name . '()`' . "\n\n";
$markdown .= trim( $doc ) . "\n\n\n"; // Add extra newline after each function
}
$markdown .= "---\n\n";
}
// Handle class documentation (unchanged)
if ( isset( $docs['class'] ) ) {
$markdown .= $this->format_title( $docs['class']['name'] ) . "\n\n";
$markdown .= trim( $docs['class']['doc'] ) . "\n\n";
// Add properties section
if ( ! empty( $docs['class']['properties'] ) ) {
$markdown .= '## Properties' . "\n\n";
foreach ( $docs['class']['properties'] as $name => $doc ) {
$markdown .= '### `$' . $name . '`' . "\n\n";
$markdown .= trim( $doc ) . "\n\n";
}
}
if ( ! empty( $docs['class']['methods'] ) ) {
$markdown .= '## Methods' . "\n\n";
foreach ( $docs['class']['methods'] as $name => $doc ) {
$markdown .= '### `' . $name . '`' . "\n\n";
$markdown .= trim( $doc ) . "\n\n";
}
}
}
// Ensure file ends with single newline and no trailing spaces
$markdown = rtrim( rtrim( $markdown ), "\n" ) . "\n";
return $markdown;
}
/**
* Format a title for markdown documentation.
*
* @param string $title The title to format.
* @return string Formatted title.
*/
private function format_title( $title ) {
// Convert "Api" or "api" to "API"
$title = preg_replace( '/\b[Aa]pi\b/', 'API', $title );
return '# ' . $title;
}
}
// Parse command line arguments
$options = getopt( '', array( 'output::' ) );
$output_dir = isset( $options['output'] ) ? $options['output'] : __DIR__ . '/../code-reference';
$generator = new DocGenerator( $output_dir );
$generator->generate();