-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHookAnnotation.php
104 lines (92 loc) · 2.65 KB
/
HookAnnotation.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
<?php
/**
* Annotation based hooking for class-like methods.
*
* @author Viktor Szépe <[email protected]>
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/szepeviktor/SentencePress
*/
declare(strict_types=1);
namespace SzepeViktor\SentencePress;
use ReflectionClass;
use ReflectionMethod;
use function add_filter;
/**
* Implement hooking in method annotation.
*
* Format: @hook tag 10
* @hook tag first
* @hook tag last
* @hook skip
*
* mindplay/annotations may be a better solution.
*
* @see https://github.com/szepeviktor/wordpress-website-lifecycle/blob/master/WordPress-hooks.md
*/
trait HookAnnotation
{
protected function hookMethods(int $defaultPriority = 10): void
{
$classReflection = new ReflectionClass(self::class);
// Look for hook tag in all public methods.
foreach ($classReflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
// Do not hook constructor, use HookConstructorTo.
if ($method->isConstructor()) {
continue;
}
$hookDetails = $this->getMetadata((string)$method->getDocComment(), $defaultPriority);
if ($hookDetails === null) {
continue;
}
add_filter(
$hookDetails['tag'],
[$this, $method->name],
$hookDetails['priority'],
$method->getNumberOfParameters()
);
}
}
/**
* Read hook tag from docblock.
*
* @return array{tag: string, priority: int}|null
*/
protected function getMetadata(string $docComment, int $defaultPriority): ?array
{
$matches = [];
if (
\preg_match(
// @hook ( tag ) ( priority )
'/^\s+\*\s+@hook\s+([\w\/._=-]+)(?:\s+(\d+|first|last))?\s*$/m',
$docComment,
$matches
) !== 1
) {
return null;
}
if ($matches[1] === 'skip') {
return null;
}
if (! isset($matches[2])) {
return [
'tag' => $matches[1],
'priority' => $defaultPriority,
];
}
switch ($matches[2]) {
case 'first':
$priority = PHP_INT_MIN;
break;
case 'last':
$priority = PHP_INT_MAX;
break;
default:
$priority = (int)$matches[2];
break;
}
return [
'tag' => $matches[1],
'priority' => $priority,
];
}
}