Skip to content

Commit ee855c9

Browse files
committed
introduce TransformersRegistry class to use in registration of transformers
1 parent 58e893e commit ee855c9

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<?php
2+
3+
namespace DotOrg\TryWordPress;
4+
5+
use InvalidArgumentException;
6+
7+
class TransformersRegistry {
8+
private static array $handlers = array();
9+
10+
/**
11+
* Add a handler for a specific subject type
12+
*
13+
* @param string $type The subject type to handle.
14+
* @param array $identifier Array containing unique slug and description.
15+
* @param callable $handler The handler function.
16+
* @return void
17+
* @throws InvalidArgumentException If handler is not callable.
18+
*/
19+
public static function add( string $type, array $identifier, callable $handler ): void {
20+
if ( ! is_callable( $handler ) ) {
21+
throw new InvalidArgumentException( 'Handler must be callable' );
22+
}
23+
24+
if ( ! isset( $identifier['slug'] ) ) {
25+
throw new InvalidArgumentException( 'Identifier slug must be defined' );
26+
}
27+
28+
if ( ! isset( self::$handlers[ $type ] ) ) {
29+
self::$handlers[ $type ] = array();
30+
}
31+
32+
self::$handlers[ $type ][] = $handler;
33+
}
34+
35+
/**
36+
* Check if handlers exist for a type
37+
*
38+
* @param string $type The type to check.
39+
* @return bool True if handlers exist
40+
*/
41+
public static function has( string $type ): bool {
42+
return isset( self::$handlers[ $type ] ) && ! empty( self::$handlers[ $type ] );
43+
}
44+
45+
/**
46+
* Execute all handlers for a type
47+
*
48+
* @TODO: Invoke this function at the right place in code
49+
*
50+
* @param string $type The type to handle.
51+
* @param mixed|null $data Data to pass to handlers.
52+
* @return array Results from all handlers
53+
*/
54+
public static function handle( string $type, mixed $data = null ): array {
55+
if ( ! self::has( $type ) ) {
56+
return array();
57+
}
58+
59+
$results = array();
60+
foreach ( self::$handlers[ $type ] as $handler ) {
61+
$results[] = $handler( $data );
62+
}
63+
64+
return $results;
65+
}
66+
67+
/**
68+
* Remove all handlers for a type
69+
*
70+
* @param string $type The type to clear handlers for.
71+
* @return void
72+
*/
73+
public static function clear( string $type ): void {
74+
if ( isset( self::$handlers[ $type ] ) ) {
75+
unset( self::$handlers[ $type ] );
76+
}
77+
}
78+
}

0 commit comments

Comments
 (0)