-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMacroable.hh
More file actions
78 lines (66 loc) · 2.01 KB
/
Copy pathMacroable.hh
File metadata and controls
78 lines (66 loc) · 2.01 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
<?hh // strict
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
namespace Titon\Common;
use Titon\Common\Exception\MissingMacroException;
/**
* Provides a mechanism at runtime for defining static methods that can be triggered during __callStatic().
*
* @package Titon\Common
*/
trait Macroable {
/**
* Custom methods to magically call through the static context.
*
* @var \Titon\Common\MacroContainer
*/
protected static MacroContainer $macros = Map {};
/**
* Execute a macro if it has been called statically.
*
* @param string $key
* @param array $args
* @return mixed
* @throws \Titon\Utility\Exception\UnsupportedMethodException
*/
public static function __callStatic(string $key, array<mixed> $args): mixed {
if (static::hasMacro($key)) {
return call_user_func_array(static::getMacros()->get($key), $args);
}
throw new MissingMacroException(sprintf('Macro %s has not been defined for %s', $key, static::class));
}
/**
* Return all defined macros for a class.
*
* @return \Titon\Common\MacroMap
*/
public static function getMacros(): MacroMap {
$macros = static::$macros;
$class = static::class;
if (!$macros->contains($class)) {
$macros[$class] = Map {};
}
return $macros[$class];
}
/**
* Return true if a macro is defined by name.
*
* @param string $key
* @return bool
*/
public static function hasMacro(string $key): bool {
return static::getMacros()->contains($key);
}
/**
* Define a custom macro, that will be triggered when a magic static method is called.
*
* @param string $key
* @param \Titon\Common\MacroCallback $callback
*/
public static function macro(string $key, MacroCallback $callback): void {
static::getMacros()->set($key, $callback);
}
}