Completed
Push — master ( b6760c...d0c54a )
by J.D.
03:04
created

WordPoints_Hook_Arg_Dynamic::get_value()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 12
rs 9.4286
cc 3
eloc 5
nc 2
nop 0
1
<?php
2
3
/**
4
 * Dynamic hook arg class.
5
 *
6
 * @package wordpoints-hooks-api
7
 * @since   1.0.0
8
 */
9
10
/**
11
 * Represents a hook arg for dynamic entities.
12
 *
13
 * Some hook events are tied to entities which are "dynamic": for example, an entity
14
 * is registered for each post type with a slug of the format "post-{$slug}". The
15
 * $slug portion is dynamic, so we call these entities dynamic entities.
16
 *
17
 * Hook events have to be registered for specific entities, so events registered for
18
 * dynamic entities also need to be dynamic. However, hook actions don't have to be
19
 * tied to specific entities. They can supply generic args that are used by multiple
20
 * different entities (for example, "post"). This fact allows us to register a single
21
 * generic action for each group of dynamic entities, using this class when
22
 * registering the event args for the dynamic entities.
23
 *
24
 * @since 1.0.0
25
 */
26
class WordPoints_Hook_Arg_Dynamic extends WordPoints_Hook_Arg {
27
28
	/**
29
	 * The slug of the arg to retrieve from the action.
30
	 *
31
	 * @since 1.0.0
32
	 *
33
	 * @var string
34
	 */
35
	protected $arg_slug;
36
37
	/**
38
	 * @since 1.0.0
39
	 */
40
	public function __construct( $slug, WordPoints_Hook_ActionI $action = null ) {
41
42
		parent::__construct( $slug, $action );
43
44
		$parts = explode( '\\', $this->slug, 2 );
45
46
		if ( isset( $parts[1] ) ) {
47
			$this->arg_slug = $parts[0];
48
		} else {
49
			$this->arg_slug = $this->slug;
50
		}
51
	}
52
53
	/**
54
	 * @since 1.0.0
55
	 */
56
	public function get_value() {
57
58
		// We first check if there is an action arg with the full, dynamic name.
59
		$value = parent::get_value();
60
61
		// If not, then we check for an arg with the generic name.
62
		if ( null === $value && $this->action instanceof WordPoints_Hook_ActionI ) {
63
			$value = $this->action->get_arg_value( $this->arg_slug );
64
		}
65
66
		return $value;
67
	}
68
}
69
70
// EOF
71