/
DumpHooks.php
101 lines (82 loc) · 2.31 KB
/
DumpHooks.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
<?php
/**
* Dump all the Dochooks to an external file: /inc/hooks.php
*
* It's used when OPcache's `save_comments` is disabled.
*
* @usage: wp notification dump-hooks
*
* @package notification
*/
namespace BracketSpace\Notification\Cli;
use Notification;
use WP_CLI;
/**
* Dump all hooks as add_filter() calls.
*/
class DumpHooks {
/**
* Dump all the Dochooks.
*
* @param list<string> $args Arguments.
* @return void
*/
public function __invoke( $args ) {
$runtime = Notification::runtime();
$filesystem = $runtime->get_filesystem();
$hooks_file = 'compat/register-hooks.php';
// Build an array of searchable instances.
$objects = [];
foreach ( Notification::components() as $component_name => $instance ) {
if ( is_object( $instance ) ) {
$objects[ $component_name ] = get_class( $instance );
}
}
$hook_functions = [];
// Loop over each class registering hooks.
foreach ( $runtime->get_calls() as $class_name => $hooks ) {
$count = 0;
if ( 'BracketSpace\\Notification\\Runtime' === $class_name ) {
$callback_object_name = '$this';
} else {
$component_name = array_search( $class_name, $objects, true );
if ( ! $component_name ) {
WP_CLI::warning( str_replace( 'BracketSpace\\Notification\\', '', $class_name ) . ' skipped, no instance available' );
continue;
}
$callback_object_name = "\$this->component( '" . $component_name . "' )";
}
foreach ( $hooks as $hook ) {
$hook_functions[] = sprintf(
"add_%s( '%s', [ %s, '%s' ], %d, %d );",
$hook['type'],
$hook['name'],
$callback_object_name,
$hook['callback'],
$hook['priority'],
$hook['arg_count']
);
$count++;
}
WP_CLI::log( str_replace( 'BracketSpace\\Notification\\', '', $class_name ) . ' added ' . $count . ' hooks' );
}
// Clear the hooks file.
if ( $filesystem->exists( $hooks_file ) ) {
$filesystem->delete( $hooks_file );
}
$file_header = '<?php
/**
* Hooks compatibilty file.
*
* Automatically generated with `wp notification dump-hooks`.
*
* @package notification
*/
/** @var \BracketSpace\Notification\Runtime $this */
// phpcs:disable
';
// Save the content.
$filesystem->put_contents( $hooks_file, $file_header . implode( "\n", $hook_functions ) . "\n" );
WP_CLI::success( 'All hooks dumped!' );
}
}