Completed
Push — master ( 228e92...6a576a )
by David
02:49
created

Wordlift_Property_Getter::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * The property service provides access to entities properties values. Each entity
5
 * type has a list of custom fields which map to WP's meta. The property service
6
 * maps meta keys to property services.
7
 *
8
 * @since 3.8.0
9
 */
10
class Wordlift_Property_Getter {
11
12
	/**
13
	 * An array of {@link Wordlift_Simple_Property_Service}s which can access a
14
	 * property.
15
	 *
16
	 * @since 3.8.0
17
	 * @access private
18
	 * @var Wordlift_Simple_Property_Service[] $services An array of {@link Wordlift_Simple_Property_Service}s.
19
	 */
20
	private $services = array();
21
22
	/**
23
	 * The default {@link Wordlift_Simple_Property_Service} which is used to access
24
	 * a property when no specific {@link Wordlift_Simple_Property_Service} is found
25
	 * in the {@see $services} array.
26
	 * @var Wordlift_Simple_Property_Service
27
	 */
28
	private $default;
29
30
	/**
31
	 * Create a property service with the provided {@link Wordlift_Simple_Property_Service}
32
	 * as default.
33
	 *
34
	 * @since 3.8.0
35
	 *
36
	 * @param $default
37
	 */
38
	public function __construct( $default ) {
39
40
		$this->default = $default;
41
42
	}
43
44
	/**
45
	 * Register a {@link Wordlift_Simple_Property_Service} for the specified meta keys.
46
	 *
47
	 * @since 3.8.0
48
	 *
49
	 * @param \Wordlift_Simple_Property_Service $property_service A {@link Wordlift_Simple_Property_Service} instance.
50
	 * @param array $meta_keys An array of meta keys that the provided {@link Wordlift_Simple_Property_Service} will handle.
51
	 */
52
	public function register( $property_service, $meta_keys ) {
53
54
		// Register the specified property service for each meta key.
55
		foreach ( $meta_keys as $meta_key ) {
56
			$this->services[ $meta_key ] = $property_service;
57
		}
58
59
	}
60
61
	/**
62
	 * Get the value for the specified entity post id and WP's meta key.
63
	 *
64
	 * @since 3.8.0
65
	 *
66
	 * @param int $post_id The post id.
67
	 * @param string $meta_key The meta key.
68
	 *
69
	 * @return mixed|null The property value or null.
70
	 */
71
	public function get( $post_id, $meta_key ) {
72
73
		return isset( $this->services[ $meta_key ] )
74
			// Use a specific property service.
75
			? $this->services[ $meta_key ]->get( $post_id, $meta_key )
76
			// Use the default property service.
77
			: $this->default->get( $post_id, $meta_key );
78
	}
79
80
}
81