Passed
Branch facadeless (50a555)
by Atanas
02:42
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
namespace WPEmerge\Application;
4
5
use Closure;
6
use BadMethodCallException;
7
8
/**
9
 * Add methods to classes at runtime.
10
 * Loosely based on spatie/macroable.
11
 *
12
 * @codeCoverageIgnore
13
 */
14
trait HasAliasesTrait {
15
	/**
16
	 * Aliases.
17
	 *
18
	 * @var array<string, string|Closure>
19
	 */
20
	protected $aliases = [];
21
22
	/**
23
	 * Register an alias.
24
	 *
25
	 * @param  string         $alias
26
	 * @param  string|Closure $target
27
	 * @return void
28
	 */
29
	public function alias( $alias, $target ) {
30
		$this->aliases[ $alias ] = $target;
31
	}
32
33
	/**
34
	 * Get whether an alias is registered.
35
	 *
36
	 * @param  string  $alias
37
	 * @return boolean
38
	 */
39
	public function hasAlias( $alias ) {
40
		return isset( $this->aliases[ $alias ] );
41
	}
42
43
	public function __call( $method, $parameters ) {
44
		if ( ! $this->hasAlias( $method ) ) {
45
			throw new BadMethodCallException( "Method {$method} does not exist." );
46
		}
47
48
		$target = $this->aliases[ $method ];
49
50
		if ( is_string( $target ) ) {
51
			return $this->resolve( $target );
52
		}
53
54
		/** @var $target Closure */
55
		return call_user_func_array( $target->bindTo( $this, static::class ), $parameters );
56
	}
57
58
	/**
59
	 * Resolve a dependency from the IoC container.
60
	 *
61
	 * @param  string     $key
62
	 * @return mixed|null
63
	 */
64
	abstract public function resolve( $key );
65
}
66