Passed
Push — master ( f13993...11c67b )
by Atanas
01:50
created

Handler::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace WPEmerge\Helpers;
4
5
use Closure;
6
use Exception;
7
use WPEmerge;
8
9
/**
10
 * Represent a generic handler - a Closure or a class method to be resolved from the service container
11
 */
12
class Handler {
13
	/**
14
	 * Parsed handler
15
	 *
16
	 * @var array|Closure|null
17
	 */
18
	protected $handler = null;
19
20
	/**
21
	 * Constructor
22
	 *
23
	 * @throws Exception
24
	 * @param  string|Closure $raw_handler
25
	 */
26 6
	public function __construct( $raw_handler ) {
27 6
		$handler = $this->parse( $raw_handler );
28
29 6
		if ( $handler === null ) {
30 2
			throw new Exception( 'No or invalid handler provided.' );
31
		}
32
33 4
		$this->handler = $handler;
34 4
	}
35
36
	/**
37
	 * Parse a raw handler to a Closure or a [class, method] array
38
	 *
39
	 * @param  string|Closure     $raw_handler
40
	 * @return array|Closure|null
41
	 */
42 5
	protected function parse( $raw_handler ) {
43 5
		if ( $raw_handler instanceof Closure ) {
44 1
			return $raw_handler;
45
		}
46
47 4
		if ( is_string( $raw_handler ) )  {
48 3
			return $this->parseFromString( $raw_handler );
49
		}
50
51 1
		return null;
52
	}
53
54
	/**
55
	 * Parse a raw string handler to a [class, method] array
56
	 *
57
	 * @param  string     $raw_handler
58
	 * @return array|null
59
	 */
60 3
	protected function parseFromString( $raw_handler ) {
61 3
		$handlerPieces = preg_split( '/@|::/', $raw_handler, 2 );
62
63 3
		if ( count( $handlerPieces ) === 2 ) {
64
			return array(
65 2
				'class' => $handlerPieces[0],
66 2
				'method' => $handlerPieces[1],
67 2
			);
68
		}
69
70 1
		return null;
71
	}
72
73
	/**
74
	 * Get the parsed handler
75
	 *
76
	 * @return array|Closure|null
77
	 */
78 1
	public function get() {
79 1
		return $this->handler;
80
	}
81
82
	/**
83
	 * Execute the parsed handler with any provided arguments and return the result
84
	 *
85
	 * @param  mixed $arguments,...
86
	 * @return mixed
87
	 */
88 3
	public function execute() {
89 3
		$arguments = func_get_args();
90 3
		if ( is_a( $this->handler, Closure::class ) ) {
91 2
			return call_user_func_array( $this->handler, $arguments );
92
		}
93
94 1
		$class = $this->handler['class'];
95 1
		$method = $this->handler['method'];
96
97 1
		$instance = WPEmerge::instantiate( $class );
98 1
		return call_user_func_array( [$instance, $method], $arguments );
99
	}
100
}
101