Passed
Push — master ( 576bdc...3d3460 )
by Atanas
02:09
created

HasAliasesTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 10
c 1
b 0
f 0
dl 0
loc 51
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A hasAlias() 0 2 1
A __call() 0 13 3
A alias() 0 2 1
1
<?php
2
/**
3
 * @package   WPEmerge
4
 * @author    Atanas Angelov <[email protected]>
5
 * @copyright 2017-2019 Atanas Angelov
6
 * @license   https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0
7
 * @link      https://wpemerge.com/
8
 */
9
10
namespace WPEmerge\Application;
11
12
use Closure;
13
use BadMethodCallException;
14
15
/**
16
 * Add methods to classes at runtime.
17
 * Loosely based on spatie/macroable.
18
 *
19
 * @codeCoverageIgnore
20
 */
21
trait HasAliasesTrait {
22
	/**
23
	 * Aliases.
24
	 *
25
	 * @var array<string, string|Closure>
26
	 */
27
	protected $aliases = [];
28
29
	/**
30
	 * Register an alias.
31
	 *
32
	 * @param  string         $alias
33
	 * @param  string|Closure $target
34
	 * @return void
35
	 */
36
	public function alias( $alias, $target ) {
37
		$this->aliases[ $alias ] = $target;
38
	}
39
40
	/**
41
	 * Get whether an alias is registered.
42
	 *
43
	 * @param  string  $alias
44
	 * @return boolean
45
	 */
46
	public function hasAlias( $alias ) {
47
		return isset( $this->aliases[ $alias ] );
48
	}
49
50
	public function __call( $method, $parameters ) {
51
		if ( ! $this->hasAlias( $method ) ) {
52
			throw new BadMethodCallException( "Method {$method} does not exist." );
53
		}
54
55
		$target = $this->aliases[ $method ];
56
57
		if ( is_string( $target ) ) {
58
			return $this->resolve( $target );
59
		}
60
61
		/** @var $target Closure */
62
		return call_user_func_array( $target->bindTo( $this, static::class ), $parameters );
63
	}
64
65
	/**
66
	 * Resolve a dependency from the IoC container.
67
	 *
68
	 * @param  string     $key
69
	 * @return mixed|null
70
	 */
71
	abstract public function resolve( $key );
72
}
73