-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathPlugin.php
1656 lines (1413 loc) · 58 KB
/
Plugin.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
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 PsalmWordPress;
use BadMethodCallException;
use Exception;
use InvalidArgumentException;
use phpDocumentor;
use PhpParser;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Echo_;
use PhpParser\Node\Stmt\GroupUse;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\UseItem;
use Psalm;
use Psalm\CodeLocation;
use Psalm\Config;
use Psalm\Context;
use Psalm\Exception\TypeParseTreeException;
use Psalm\Internal\Analyzer\Statements\Expression\ExpressionIdentifier;
use Psalm\Internal\Analyzer\Statements\Expression\Fetch\ConstFetchAnalyzer;
use Psalm\Internal\Analyzer\Statements\Expression\SimpleTypeInferer;
use Psalm\Internal\Provider\ReturnTypeProvider\ParseUrlReturnTypeProvider;
use Psalm\IssueBuffer;
use Psalm\Issue\InvalidDocblock;
use Psalm\Issue\PluginIssue;
use Psalm\Plugin\EventHandler\AfterEveryFunctionCallAnalysisInterface;
use Psalm\Plugin\EventHandler\BeforeFileAnalysisInterface;
use Psalm\Plugin\EventHandler\Event\AfterEveryFunctionCallAnalysisEvent;
use Psalm\Plugin\EventHandler\Event\BeforeFileAnalysisEvent;
use Psalm\Plugin\EventHandler\Event\FunctionParamsProviderEvent;
use Psalm\Plugin\EventHandler\Event\FunctionReturnTypeProviderEvent;
use Psalm\Plugin\EventHandler\FunctionParamsProviderInterface;
use Psalm\Plugin\EventHandler\FunctionReturnTypeProviderInterface;
use Psalm\Plugin\PluginEntryPointInterface;
use Psalm\Plugin\RegistrationInterface;
use Psalm\StatementsSource;
use Psalm\Storage\FunctionLikeParameter;
use Psalm\Type;
use Psalm\Type\Atomic;
use Psalm\Type\Atomic\TCallable;
use Psalm\Type\Atomic\TIntRange;
use Psalm\Type\Union;
use RuntimeException;
use SimpleXMLElement;
use UnexpectedValueException;
/**
* @psalm-type Hook = array{hook_type: string, types: list<Union>, deprecated: bool, minimum_invoke_args: int<0, max>}
*/
class Plugin implements
AfterEveryFunctionCallAnalysisInterface,
BeforeFileAnalysisInterface,
FunctionParamsProviderInterface,
FunctionReturnTypeProviderInterface,
PluginEntryPointInterface {
/**
* @var bool
*/
public static $requireAllParams = false;
/**
* @var array{useDefaultHooks: bool, hooks: list<string>}
*/
public static $configHooks = [
'useDefaultHooks' => false,
'hooks' => [],
];
/**
* @var array<string, Hook>
*/
public static $hooks = [];
/**
* @var string[]
*/
public static $parseErrors = [];
public function __invoke( RegistrationInterface $registration, ?SimpleXMLElement $config = null ) : void {
$registration->registerHooksFromClass( static::class );
// if all possible params of an apply_filters should be required
if ( isset( $config->requireAllParams['value'] ) && (string) $config->requireAllParams['value'] === 'true' ) {
static::$requireAllParams = true;
}
// if useDefaultStubs is not set or set to anything except false, we want to load the stubs included in this plugin
if ( ! isset( $config->useDefaultStubs['value'] ) || (string) $config->useDefaultStubs['value'] !== 'false' ) {
array_map( [ $registration, 'addStubFile' ], $this->getStubFiles() );
}
// if useDefaultHooks is not set or set to anything except false, we want to load the hooks included in this plugin
if ( ! isset( $config->useDefaultHooks['value'] ) || (string) $config->useDefaultHooks['value'] !== 'false' ) {
static::$configHooks['useDefaultHooks'] = true;
}
if ( ! empty( $config->hooks ) ) {
$hooks = [];
$psalm_config = Config::getInstance();
if ( $psalm_config->resolve_from_config_file ) {
$base_dir = $psalm_config->base_dir;
} else {
$base_dir = getcwd();
}
foreach ( $config->hooks as $hook_data ) {
foreach ( $hook_data as $type => $data ) {
if ( $type === 'file' ) {
// this is a SimpleXmlElement, therefore we need to cast it to string!
$file = (string) $data['name'];
if ( $file[0] !== '/' ) {
$file = $base_dir . '/' . $file;
}
if ( ! is_file( $file ) ) {
throw new BadMethodCallException(
sprintf( 'Hook file "%s" does not exist', $file )
);
}
// File as key, to avoid loading the same hooks multiple times.
$hooks[ $file ] = $file;
} elseif ( $type === 'directory' ) {
$directory = rtrim( (string) $data['name'], '/' );
if ( $directory[0] !== '/' ) {
$directory = $base_dir . '/' . $directory;
}
if ( ! is_dir( $directory ) ) {
throw new BadMethodCallException(
sprintf( 'Hook directory "%s" does not exist', $directory )
);
}
if ( isset( $data['recursive'] ) && (string) $data['recursive'] === 'true' ) {
$directories = glob( $directory . '/*', GLOB_ONLYDIR );
}
if ( empty( $directories ) ) {
$directories = [ $directory ];
} else {
/** @var string[] $directories */
$directories[] = $directory;
// Might have duplicates if the directory is explicitly
// specified and also passed in recursive directory.
$directories = array_unique( $directories );
}
foreach ( $directories as $directory ) {
foreach ( [ 'actions', 'filters', 'hooks' ] as $file_name ) {
$file_path = $directory . '/' . $file_name . '.json';
if ( is_file( $file_path ) ) {
$hooks[ $file_path ] = $file_path;
}
}
}
}
}
}
// Don't need the keys anymore and ensures array_merge runs smoothly later on.
static::$configHooks['hooks'] = array_values( $hooks );
}
static::loadStubbedHooks();
}
/**
* Resolves a vendor-relative directory path to the absolute package directory.
*
* The plugin must run both from the source file in the repository (current working directory)
* as well as when required as a composer package when the current working directory may not
* have a vendor/ folder and the package directory is detected relative to this file.
*
* @param string $path Path of a folder, relative, inside `vendor/` (Composer).
* Must start with `vendor/` marker.
*/
private static function getVendorDir( string $path ) : string {
$vendor = 'vendor/';
$self = 'humanmade/psalm-plugin-wordpress';
if ( 0 !== strpos( $path, $vendor ) ) {
throw new BadMethodCallException(
sprintf( '$path must start with "%s", "%s" given', $vendor, $path )
);
}
$cwd = getcwd();
// Prefer path relative to current working directory (original default).
$cwd_path = $cwd . '/' . $path;
if ( is_dir( $cwd_path ) ) {
return $cwd_path;
}
// Check running as composer package inside a vendor folder.
$pkg_self_dir = __DIR__;
$vendor_dir = dirname( $pkg_self_dir, 2 );
if ( $pkg_self_dir === $vendor_dir . '/' . $self ) {
// Likely plugin is running as composer package, let's try for the path.
$pkg_path = substr( $path, strlen( $vendor ) );
$vendor_path = $vendor_dir . '/' . $pkg_path;
if ( is_dir( $vendor_path ) ) {
return $vendor_path;
}
}
// Original default behaviour.
return $cwd_path;
}
/**
* @return string[]
*/
private function getStubFiles() : array {
return [
self::getVendorDir( 'vendor/php-stubs/wordpress-stubs' ) . '/wordpress-stubs.php',
self::getVendorDir( 'vendor/php-stubs/wordpress-globals' ) . '/wordpress-globals.php',
self::getVendorDir( 'vendor/php-stubs/wp-cli-stubs' ) . '/wp-cli-stubs.php',
self::getVendorDir( 'vendor/php-stubs/wp-cli-stubs' ) . '/wp-cli-commands-stubs.php',
self::getVendorDir( 'vendor/php-stubs/wp-cli-stubs' ) . '/wp-cli-i18n-stubs.php',
__DIR__ . '/stubs/globals.php',
__DIR__ . '/stubs/overrides.php',
];
}
protected static function loadStubbedHooks() : void {
if ( static::$hooks ) {
return;
}
if ( static::$configHooks['useDefaultHooks'] !== false ) {
$wp_hooks_data_dir = self::getVendorDir( 'vendor/wp-hooks/wordpress-core/hooks' );
static::loadHooksFromFile( $wp_hooks_data_dir . '/actions.json' );
static::loadHooksFromFile( $wp_hooks_data_dir . '/filters.json' );
}
foreach ( static::$configHooks['hooks'] as $file ) {
static::loadHooksFromFile( $file );
}
}
protected static function loadHooksFromFile( string $filepath ) : void {
$data = json_decode( file_get_contents( $filepath ), true );
if ( ! isset( $data['hooks'] ) || ! is_array( $data['hooks'] ) ) {
static::$parseErrors[] = 'Invalid hook file ' . $filepath;
return;
}
/**
* @var list<array{
* args: int<0, max>,
* name: string,
* aliases?: list<string>,
* file: string,
* type: 'action'|'action_reference'|'action_deprecated'|'filter'|'filter_reference'|'filter_deprecated',
* doc: array{
* description: string,
* long_description: string,
* long_description_html: string,
* tags: list<array{ name: string, content: string, types?: list<string>}>
* }
* }>
*/
$hooks = $data['hooks'];
$plugin_slug = basename( dirname( $filepath ) );
foreach ( $hooks as $hook ) {
$params = array_filter( $hook['doc']['tags'], function ( $tag ) {
return $tag['name'] === 'param';
});
$params = array_map( function ( array $param ) : array {
if ( isset( $param['types'] ) && $param['types'] !== [ 'array' ] ) {
return $param;
}
if ( substr_count( $param['content'], '{' ) !== 1 ) {
// Unable to parse nested array style PHPDoc.
return $param;
}
// ? after variable name is kept, to mark it optional
// sometimes a hyphen is used in the "variable" here, e.g. "$update-supported"
$found = preg_match_all( '/@type\s+([^ ]+)\s+\$([\w-]+\??)/', $param['content'], $matches, PREG_SET_ORDER );
if ( ! $found ) {
return $param;
}
$array_properties = [];
foreach ( $matches as $match ) {
// use as property as key to avoid setting the same property twice in case it is incorrectly set twice
$array_properties[ $match[2] ] = $match[2] . ': ' . $match[1];
}
$array_string = 'array{ ' . implode( ', ', $array_properties ) . ' }';
$param['types'] = [ $array_string ];
return $param;
}, $params );
$types = array_column( $params, 'types' );
// remove empty elements which can happen with invalid phpdoc - must be done before parseString to avoid notice there
$types = array_filter( $types );
$types = array_map( function ( $type ) : string {
natcasesort( $type );
return implode( '|', $type );
}, $types );
// not all types are documented, assume "mixed" for undocumented
if ( count( $types ) < $hook['args'] ) {
$fill_types = array_fill( 0, $hook['args'], 'mixed' );
$types = $types + $fill_types;
ksort( $types );
}
// skip invalid ones
try {
$parsed_types = array_map( [ Type::class, 'parseString' ], $types );
} catch ( TypeParseTreeException $e ) {
static::$parseErrors[] = $e->getMessage() . ' for hook ' . $hook['name'] . ' of hook file ' . $filepath . ' in ' . $plugin_slug . '/' . $hook['file'];
continue;
}
if ( $hook['type'] === 'filter_deprecated' ) {
$is_deprecated = true;
$hook['type'] = 'filter';
} elseif ( $hook['type'] === 'action_deprecated' ) {
$is_deprecated = true;
$hook['type'] = 'action';
} else {
$deprecated_tags = array_filter( $hook['doc']['tags'], function ( $tag ) {
return $tag['name'] === 'deprecated';
});
$is_deprecated = $deprecated_tags === [] ? false : true;
}
static::registerHook( $hook['name'], $parsed_types, $hook['type'], $is_deprecated );
if ( isset( $hook['aliases'] ) ) {
foreach ( $hook['aliases'] as $alias_name ) {
static::registerHook( $alias_name, $parsed_types, $hook['type'], $is_deprecated );
}
}
}
}
public static function beforeAnalyzeFile( BeforeFileAnalysisEvent $event ) : void {
$file_path = $event->getStatementsSource()->getFilePath();
$statements = $event->getCodebase()->getStatementsForFile( $file_path );
$traverser = new PhpParser\NodeTraverser;
$hook_visitor = new HookNodeVisitor();
$traverser->addVisitor( $hook_visitor );
try {
$traverser->traverse( $statements );
} catch ( Exception $e ) {
}
foreach ( $hook_visitor->hooks as $hook ) {
static::registerHook( $hook['name'], $hook['types'], $hook['hook_type'], $hook['deprecated'] );
}
}
public static function getDynamicHookName( object $arg ) : ?string {
// variable or 'foo' . $bar variable hook name
// "foo_{$my_var}_bar" is the wp-hooks-generator style, we need to mimic
if ( $arg instanceof Variable ) {
return '{$' . $arg->name . '}';
}
if ( $arg instanceof PhpParser\Node\Scalar\Encapsed || $arg instanceof PhpParser\Node\Scalar\InterpolatedString ) {
$hook_name = '';
foreach ( $arg->parts as $part ) {
$resolved_part = static::getDynamicHookName( $part );
if ( $resolved_part === null ) {
return null;
}
$hook_name .= $resolved_part;
}
return $hook_name;
}
if ( $arg instanceof PhpParser\Node\Expr\BinaryOp\Concat ) {
$hook_name = static::getDynamicHookName( $arg->left );
if ( is_null( $hook_name ) ) {
return null;
}
$temp = static::getDynamicHookName( $arg->right );
if ( is_null( $temp ) ) {
return null;
}
$hook_name .= $temp;
return $hook_name;
}
if ( $arg instanceof String_ || $arg instanceof PhpParser\Node\Scalar\EncapsedStringPart || $arg instanceof PhpParser\Node\InterpolatedStringPart || $arg instanceof PhpParser\Node\Scalar\LNumber || $arg instanceof PhpParser\Node\Scalar\Int_ ) {
return $arg->value;
}
if ( $arg instanceof PhpParser\Node\Expr\StaticPropertyFetch ) {
// @todo the WP hooks generator doesn't support that yet and handling needs to be added for it there first
// e.g. self::$foo
return null;
}
if ( $arg instanceof PhpParser\Node\Expr\StaticCall ) {
if ( ! $arg->name instanceof PhpParser\Node\Identifier ) {
throw new UnexpectedValueException( 'Unsupported dynamic hook name with name type ' . get_class( $arg->name ) . ' on line ' . $arg->getStartLine(), 0 );
}
// hook name with Foo:bar()
if ( $arg->class instanceof Name ) {
// @todo this can be handled here, however the WP hooks generator creates output that does not match the other format at all and needs to be fixed first
return null;
}
// need to check recursively
$temp = static::getDynamicHookName( $arg->class );
if ( is_null( $temp ) ) {
throw new UnexpectedValueException( 'Unsupported dynamic hook name with class type ' . get_class( $arg->class ) . ' on line ' . $arg->getStartLine(), 0 );
}
$append_method_call = '()';
return rtrim( $temp, '}' ) . '::' . $arg->name->toString() . $append_method_call . '}';
}
if ( $arg instanceof PhpParser\Node\Expr\PropertyFetch || $arg instanceof PhpParser\Node\Expr\MethodCall ) {
if ( ! $arg->name instanceof PhpParser\Node\Identifier ) {
throw new UnexpectedValueException( 'Unsupported dynamic hook name with name type ' . get_class( $arg->name ) . ' on line ' . $arg->getStartLine(), 0 );
}
// need to check recursively
$temp = static::getDynamicHookName( $arg->var );
if ( is_null( $temp ) ) {
throw new UnexpectedValueException( 'Unsupported dynamic hook name with var type ' . get_class( $arg->var ) . ' on line ' . $arg->getStartLine(), 0 );
}
$append_method_call = $arg instanceof PhpParser\Node\Expr\MethodCall ? '()' : '';
return rtrim( $temp, '}' ) . '->' . $arg->name->toString() . $append_method_call . '}';
}
if ( $arg instanceof FuncCall ) {
// mostly relevant for add_action - can just assume any variable name without using the function name, since it's useless (e.g. basename, dirname,... are common ones)
return '{$variable}';
}
if ( $arg instanceof PhpParser\Node\Expr\ArrayDimFetch ) {
$key_hook_name = static::getDynamicHookName( $arg->dim );
if ( is_null( $key_hook_name ) ) {
throw new UnexpectedValueException( 'Unsupported dynamic hook name with key type ' . get_class( $arg->dim ) . ' on line ' . $arg->getStartLine(), 0 );
}
// need to check recursively
$temp = static::getDynamicHookName( $arg->var );
if ( is_null( $temp ) ) {
throw new UnexpectedValueException( 'Unsupported dynamic hook name with var type ' . get_class( $arg->var ) . ' on line ' . $arg->getStartLine(), 0 );
}
if ( $key_hook_name[0] === '{' ) {
$key = trim( $key_hook_name, '{}' );
} elseif ( is_numeric( $key_hook_name ) ) {
$key = $key_hook_name;
} else {
$key = "'" . $key_hook_name . "'";
}
return rtrim( $temp, '}' ) . '[' . $key . ']}';
}
// isn't actually supported by the wp-hooks-generator yet and will be handled as regular string there
// just handle it generically here for the time being
if ( $arg instanceof PhpParser\Node\Expr\ConstFetch || $arg instanceof PhpParser\Node\Expr\ClassConstFetch ) {
return '{$variable}';
}
// other types not supported yet
// add handling if encountered @todo
throw new UnexpectedValueException( 'Unsupported dynamic hook name with type ' . get_class( $arg ) . ' on line ' . $arg->getStartLine(), 0 );
}
/**
* @return Hook|null
*/
public static function getDynamicHookData( string $hook_name, bool $is_action_not_filter = false ) : ?array {
// fully dynamic hooks like {$tag} cannot be used here, as they would match many hooks
// same for {$tag}_{$hello}
$normalized_hook_name = preg_replace( '/{(?:[^{}]+|(?R))*+}/', '{$abc}', $hook_name );
$hook_dynamic_removed = ltrim( $normalized_hook_name, '_' );
if ( empty( $hook_dynamic_removed ) ) {
return null;
}
// register dynamic actions - here we can use the static name from the add_action to register it
// this ensures that add_action for those will give correct error (e.g. if the 4th argument is not 0 for ajax) and we don't need to ignore these
$all_hook_names = array_keys( static::$hooks );
// dynamic hooks exist as some_{$variable}_text
$dynamic_hook_names = preg_grep( '/{\$/', $all_hook_names );
// normalize variable name length, to ensure longer variable names don't cause wrong sorting leading to incorrect replacements later on
$normalized_dynamic_hook_names = preg_replace( '/{(?:[^{}]+|(?R))*+}/', '{$abc}', $dynamic_hook_names );
$dynamic_hook_names = array_combine( $dynamic_hook_names, $normalized_dynamic_hook_names );
// sort descending from longest to shortest, to avoid shorter dynamic hooks accidentally matching
uasort( $dynamic_hook_names, function( string $a, string $b ) {
return strlen( $b ) - strlen( $a );
});
// the hook name has a variable, so we first check it against hooks that use a variable too only, to see if we get a match here already
$dynamic_hook_name_key = array_search( $normalized_hook_name, $dynamic_hook_names, true );
if ( $dynamic_hook_name_key !== false && $is_action_not_filter && static::$hooks[ $dynamic_hook_name_key ]['hook_type'] !== 'action' ) {
// action used as filter
return null;
} elseif ( $dynamic_hook_name_key !== false && ! $is_action_not_filter && static::$hooks[ $dynamic_hook_name_key ]['hook_type'] !== 'filter' ) {
// filter used as action
return null;
} elseif ( $dynamic_hook_name_key !== false ) {
$dynamic_hook = static::$hooks[ $dynamic_hook_name_key ];
// it's already in the correct format, so we just need to assign it to the non-dynamic name
static::$hooks[ $hook_name ] = [
'hook_type' => $dynamic_hook['hook_type'],
'types' => $dynamic_hook['types'],
'deprecated' => $dynamic_hook['deprecated'],
'minimum_invoke_args' => $dynamic_hook['minimum_invoke_args'],
];
return static::$hooks[ $hook_name ];
}
foreach ( $dynamic_hook_names as $dynamic_hook_name => $normalized_dynamic_hook_name ) {
if ( $is_action_not_filter && ! in_array( static::$hooks[ $dynamic_hook_name ]['hook_type'], [ 'action', 'action_reference', 'action_deprecated' ], true ) ) {
// don't match actions with filters here, so we will get an error later on
continue;
}
if ( ! $is_action_not_filter && ! in_array( static::$hooks[ $dynamic_hook_name ]['hook_type'], [ 'filter', 'filter_reference', 'filter_deprecated' ], true ) ) {
continue;
}
// fully dynamic hooks like {$tag} cannot be used here, as they would match all hooks
// same for {$tag}_{$hello}
$dynamic_removed = ltrim( str_replace( '{$abc}', '', $normalized_dynamic_hook_name ), '_' );
if ( empty( $dynamic_removed ) ) {
continue;
}
// need to escape it beforehand, since we insert regex into it
$preg_hook_name = preg_quote( $normalized_dynamic_hook_name, '/' );
// dot for dynamic hook names, e.g. load-edit.php
// may contain a variable if the hook name is dynamic too
$preg_hook_name = str_replace( '\{\$abc\}', '({\$)?[\w:>.[\]\'$\/-]+}?', $preg_hook_name );
if ( preg_match( '/^' . $preg_hook_name . '$/', $hook_name ) === 1 ) {
$dynamic_hook = static::$hooks[ $dynamic_hook_name ];
// it's already in the correct format, so we just need to assign it to the non-dynamic name
static::$hooks[ $hook_name ] = [
'hook_type' => $dynamic_hook['hook_type'],
'types' => $dynamic_hook['types'],
'deprecated' => $dynamic_hook['deprecated'],
'minimum_invoke_args' => $dynamic_hook['minimum_invoke_args'],
];
return static::$hooks[ $hook_name ];
}
}
return null;
}
public static function afterEveryFunctionCallAnalysis( AfterEveryFunctionCallAnalysisEvent $event ) : void {
$apply_filter_functions = [
'apply_filters',
'apply_filters_ref_array',
'apply_filters_deprecated',
];
$do_action_functions = [
'do_action',
'do_action_ref_array',
'do_action_deprecated',
];
$function_id = $event->getFunctionId();
if ( in_array( $function_id, $apply_filter_functions, true ) ) {
$hook_type = 'filter';
} elseif ( in_array( $function_id, $do_action_functions, true ) ) {
$hook_type = 'action';
} elseif ( preg_match( '/_deprecated_hook$/', $function_id ) !== 1 ) {
// there are custom implementations of "deprecated_hook", e.g. for "wcs", so we need to preg match it
return;
}
$call_args = $event->getExpr()->getArgs();
if ( ! isset( $call_args[0] ) ) {
return;
}
if ( ! $call_args[0]->value instanceof String_ ) {
$statements_source = $event->getStatementsSource();
try {
$union = $statements_source->getNodeTypeProvider()->getType( $call_args[0]->value );
} catch (UnexpectedValueException $e) {
$union = null;
}
if ( ! $union ) {
$union = static::getTypeFromArg( $call_args[0]->value, $event->getContext(), $statements_source );
}
$potential_hook_name = false;
if ( $union && $union->isSingleStringLiteral() ) {
$potential_hook_name = $union->getSingleStringLiteral()->value;
}
if ( $potential_hook_name && isset( static::$hooks[ $potential_hook_name ] ) ) {
$hook_name = $potential_hook_name;
} else {
$hook_name = static::getDynamicHookName( $call_args[0]->value );
if ( is_null( $hook_name ) && ! $potential_hook_name ) {
return;
}
if ( $potential_hook_name ) {
if ( is_null( $hook_name ) || ! isset( static::$hooks[ $hook_name ] ) ) {
// if it's not registered yet, use the resolved hook name
$hook_name = $potential_hook_name;
} elseif ( isset( static::$hooks[ $hook_name ] ) ) {
// if it's registered already, store the resolved name hook too
static::$hooks[ $potential_hook_name ] = static::$hooks[ $hook_name ];
}
}
}
} else {
$hook_name = $call_args[0]->value->value;
}
if ( preg_match( '/_deprecated_hook$/', $function_id ) === 1 ) {
// hook type is irrelevant and won't be used when overriding
// in case the hook is not registered yet, it will eventually be registered and the hook type and types will be set
static::registerHook( $hook_name, [], '', true );
return;
}
// Check if this hook is already documented.
if ( isset( static::$hooks[ $hook_name ] ) ) {
if (
! in_array( $function_id, ['apply_filters_deprecated', 'do_action_deprecated'], true ) &&
static::$hooks[ $hook_name ]['deprecated'] === true
) {
$statements_source = $event->getStatementsSource();
$code_location = new CodeLocation( $event->getStatementsSource(), $event->getExpr() );
$suggestion = $hook_type === 'filter' ? 'apply_filters_deprecated' : 'do_action_deprecated';
IssueBuffer::accepts(
new DeprecatedHook(
'Hook "' . $hook_name . '" is deprecated. If you still need this, check if there is a replacement for it. Otherwise, if this is a 3rd party ' . $hook_type . ', you can remove it. If it is your own/custom, please use "' . $suggestion . '" here instead and add an "@deprecated new" comment in the phpdoc',
$code_location
),
$statements_source->getSuppressedIssues()
);
}
return;
}
$statements_source = $event->getStatementsSource();
$types = array_map( function ( Arg $arg ) use ( $statements_source ) {
try {
$type = $statements_source->getNodeTypeProvider()->getType( $arg->value );
} catch ( UnexpectedValueException $e ) {
$type = null;
}
if ( ! $type ) {
$type = Type::getMixed();
} else {
$sub_types = array_values( $type->getAtomicTypes() );
$sub_types = array_map( function ( Atomic $type ) : Atomic {
if ( $type instanceof Atomic\TTrue || $type instanceof Atomic\TFalse ) {
return new Atomic\TBool;
} elseif ( $type instanceof Atomic\TLiteralString ) {
return new Atomic\TString;
} elseif ( $type instanceof Atomic\TLiteralInt ) {
return new Atomic\TInt;
} elseif ( $type instanceof Atomic\TLiteralFloat ) {
return new Atomic\TFloat;
}
return $type;
}, $sub_types );
$type = new Union( $sub_types );
}
return $type;
}, array_slice( $call_args, 1 ) );
$is_deprecated = false;
if ( in_array( $function_id, ['apply_filters_deprecated', 'do_action_deprecated'], true ) ) {
$is_deprecated = true;
}
static::registerHook( $hook_name, $types, $hook_type, $is_deprecated );
}
/**
* @return non-empty-list<lowercase-string>
*/
public static function getFunctionIds() : array {
return [
'add_action',
'add_filter',
'do_action',
'do_action_ref_array',
'do_action_deprecated',
'apply_filters',
'apply_filters_ref_array',
'apply_filters_deprecated',
'did_action',
'did_filter',
'doing_action',
'doing_filter',
'has_action',
'has_filter',
'remove_action',
'remove_filter',
'remove_all_actions',
'remove_all_filters',
'wp_parse_url',
];
}
/**
* @return ?array<int, Psalm\Storage\FunctionLikeParameter>
*/
public static function getFunctionParams( FunctionParamsProviderEvent $event ) : ?array {
$function_id = $event->getFunctionId();
if ( ! in_array( $function_id, static::getFunctionIds(), true ) ) {
return null;
}
if ( $function_id === 'wp_parse_url' ) {
return null;
}
// @todo not supported yet below
if ( in_array( $function_id, ['do_action_ref_array', 'do_action_deprecated', 'apply_filters_ref_array', 'apply_filters_deprecated'], true ) ) {
return null;
}
static::loadStubbedHooks();
$statements_source = $event->getStatementsSource();
$code_location = $event->getCodeLocation();
// output any parse errors
foreach ( static::$parseErrors as $error_message ) {
// do not allow suppressing this
IssueBuffer::accepts(
new InvalidDocblock(
$error_message,
$code_location // this can be completely wrong (even completely wrong file), since the parse error might be taken from the hooks file, so ideally we would create the correct code location before adding to $parseErrors
)
);
}
static::$parseErrors = [];
$is_action = $function_id === 'add_action';
$is_do_action = $function_id === 'do_action';
$is_action_not_filter = $is_action || $is_do_action;
$is_invoke = $is_do_action || $function_id === 'apply_filters';
$is_utility = false;
if (
in_array(
$function_id,
array(
'did_action',
'doing_action',
'has_action',
'remove_action',
'remove_all_actions',
),
true
)
) {
$is_utility = true;
$is_action_not_filter = true;
} elseif (
in_array( $function_id,
array(
'did_filter',
'doing_filter',
'has_filter',
'remove_filter',
'remove_all_filters',
),
true
)
) {
$is_utility = true;
}
$call_args = $event->getCallArgs();
if ( ! isset( $call_args[0] ) ) {
return null;
}
if ( ! $call_args[0]->value instanceof String_ ) {
try {
$union = $statements_source->getNodeTypeProvider()->getType( $call_args[0]->value );
} catch (UnexpectedValueException $e) {
$union = null;
}
if ( ! $union ) {
$union = static::getTypeFromArg( $call_args[0]->value, $event->getContext(), $statements_source );
}
$potential_hook_name = false;
if ( $union && $union->isSingleStringLiteral() ) {
$potential_hook_name = $union->getSingleStringLiteral()->value;
}
if ( $potential_hook_name && isset( static::$hooks[ $potential_hook_name ] ) ) {
$hook_name = $potential_hook_name;
} else {
$hook_name = static::getDynamicHookName( $call_args[0]->value );
if ( is_null( $hook_name ) && ! $potential_hook_name ) {
return null;
}
if ( $potential_hook_name ) {
if ( is_null( $hook_name ) || ! isset( static::$hooks[ $hook_name ] ) ) {
$hook_name = $potential_hook_name;
}
}
}
} else {
$hook_name = $call_args[0]->value->value;
}
$hook = static::$hooks[ $hook_name ] ?? null;
if ( is_null( $hook ) ) {
$hook = static::getDynamicHookData( $hook_name, $is_action_not_filter );
}
// if we declare/invoke the hook, the hook obviously exists
if ( ! $is_invoke && ! $hook ) {
if ( $code_location ) {
IssueBuffer::accepts(
new HookNotFound(
'Hook "' . $hook_name . '" not found',
$code_location
),
$statements_source->getSuppressedIssues()
);
}
return [];
}
// if it were an add_filter/add_action, we would have returned above if the $hook is not set
// if the $hook is still not set, it means we have a do_action/apply_filters here
// it may be empty if it's missing in the actions/filters.json
// or if it's not documented in the file. e.g. a do_action without a phpdoc, an action that is only declared in a wp_schedule_event,... and thus not picked up by beforeAnalyzeFile
// since we have no details on it, we skip it
if ( ! $hook ) {
// like this, it will give error that the do_action does not expect any arguments, thus prompting the dev to add phpdoc or remove args
// if this should be ignored return []; instead
// return [
// new FunctionLikeParameter( 'hook_name', false, Type::getNonEmptyString(), null, null, null, false ),
// ];
return [];
}
$hook_type = $hook['hook_type'] ?? '';
// action_reference for do_action_ref_array
if ( $is_action_not_filter && ! in_array( $hook_type, [ 'action', 'action_reference', 'action_deprecated' ], true ) ) {
if ( $code_location ) {
IssueBuffer::accepts(
new HookNotFound(
'Hook "' . $hook_name . '" is a filter not an action',
$code_location
),
$statements_source->getSuppressedIssues()
);
}
return [];
}
// filter_reference for apply_filters_ref_array
if ( ! $is_action_not_filter && ! in_array( $hook_type, [ 'filter', 'filter_reference', 'filter_deprecated' ], true ) ) {
if ( $code_location ) {
IssueBuffer::accepts(
new HookNotFound(
'Hook "' . $hook_name . '" is an action not a filter',
$code_location
),
$statements_source->getSuppressedIssues()
);
}
return [];
}
if ( ! $is_invoke && $hook['deprecated'] === true && $code_location ) {
IssueBuffer::accepts(
new DeprecatedHook(
'Hook "' . $hook_name . '" is deprecated',
$code_location
),
$statements_source->getSuppressedIssues()
);
}
// don't modify the param types for utility types, since the stubbed ones are fine
if ( $is_utility ) {
return null;
}
// Check how many args the filter is registered with.
$accepted_args_provided = false;
if ( $is_invoke ) {
// need to deduct 1, since the first argument (string) is the hardcoded hook name, which is added manually later on, since it's not in the PHPDoc
$num_args = count( $call_args ) - 1;
} else {
$num_args = 1;
if ( isset( $call_args[ 3 ]->value->value ) && !isset( $call_args[ 3 ]->name ) ) {
$num_args = max( 0, (int) $call_args[ 3 ]->value->value );
$accepted_args_provided = true;
}
// named arguments
foreach ( $call_args as $call_arg ) {
if ( isset( $call_arg->name ) && $call_arg->name instanceof PhpParser\Node\Identifier && $call_arg->name->name === 'accepted_args' ) {
$num_args = max( 0, (int) $call_arg->value->value );
$accepted_args_provided = true;
break;
}
}
}
// if the PHPDoc is missing from the do_action/apply_filters, the types can be empty - we assign "mixed" when loading stubs in that case though to avoid this
// this means these hooks really do not accept any args and the arg
// this will cause "InvalidArgument" error for add_action/add_filter and TooManyArguments error for do_action/apply_filters
// except where it actually has 0 args
if ( empty( $hook['types'] ) && $num_args !== 0 ) {
if ( $is_invoke ) {
// impossible, as it would have been populated with "mixed" already
// kept for completeness sake
$hook_types = array_fill( 0, $num_args, Type::getMixed() );
} else {
// add_action default has 1 arg, but this hook does not accept any args
if ( $is_action ) {
// if accepted args are not provided, it will use the default value, so we need to give an error
// if it's provided psalm will report an InvalidArgument error by default already
if ( $code_location && $accepted_args_provided === false ) {
IssueBuffer::accepts(
new HookInvalidArgs(
'Hook "' . $hook_name . '" does not accept any args, but the default number of args of add_action is 1. Please pass 0 as 4th argument',
$code_location
),
$statements_source->getSuppressedIssues()
);
}
$hook_types = [];
} else {
// should never happen, since we always assume "mixed" as default already and apply_filters must have at least 1 arg which is the value that is filtered
// this might be worth to debug, if anybody ever encounters this
throw new UnexpectedValueException( 'You found a bug for hook "' . $hook_name . '". Please open an issue with a code sample on https://github.com/psalm/psalm-plugin-wordpress', 0 );
// alternatively handle it with mixed for add_filter
// $hook_types = [ Type::getMixed() ];
}
}
} else {
$hook_types = $hook['types'];
}
$max_params = count( $hook_types );