-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathclass-observers-registry.php
More file actions
65 lines (56 loc) · 1.87 KB
/
class-observers-registry.php
File metadata and controls
65 lines (56 loc) · 1.87 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
<?php
namespace DotOrg\TryWordPress;
use Exception;
use InvalidArgumentException;
class Observers_Registry {
private static array $observers = array();
/**
* Add a observer for a specific subject type
*
* @param SubjectType $type The subject type for which observer should be registered.
* @param array $identifier Array containing unique slug and description.
* @param callable $observer The observer function.
* @return void
* @throws InvalidArgumentException If observer is not callable.
*/
public static function add( SubjectType $type, array $identifier, callable $observer ): void {
if ( ! is_callable( $observer ) ) {
throw new InvalidArgumentException( 'observer must be callable' );
}
if ( ! isset( $identifier['slug'] ) ) {
throw new InvalidArgumentException( 'Identifier slug must be defined' );
}
if ( ! isset( self::$observers[ $type->value ] ) ) {
self::$observers[ $type->value ] = array();
}
self::$observers[ $type->value ][ $identifier['slug'] ] = array(
'slug' => $identifier['slug'],
'description' => $identifier['description'],
'observer' => $observer,
);
}
/**
* Check if observers exist for a type
*
* @param SubjectType $type The subject type to check for.
* @return bool True if observers exist
*/
public static function has( SubjectType $type ): bool {
return isset( self::$observers[ $type->value ] ) && ! empty( self::$observers[ $type->value ] );
}
/**
* Execute all observers for a type
*
* @param SubjectType $type The subject type to handle.
* @param Subject $subject Data to pass to observers.
* @return void
*/
public static function observe( SubjectType $type, Subject $subject ): void {
if ( ! self::has( $type ) ) {
return;
}
foreach ( self::$observers[ $type->value ] as $registered_observer ) {
$registered_observer['observer']( $subject );
}
}
}