Passed
Branch master (7c6870)
by Atanas
02:11
created

Portal::setApplication()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
dl 0
loc 5
rs 10
c 1
b 0
f 0
cc 2
nc 2
nop 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 BadMethodCallException;
13
use WPEmerge\Exceptions\ConfigurationException;
14
use WPEmerge\Support\Arr;
15
16
/**
17
 * Provides static access to an application instance.
18
 *
19
 * @codeCoverageIgnore
20
 */
21
class Portal {
22
	/**
23
	 * Array of registered instances.
24
	 *
25
	 * @var array<string, object>
26
	 */
27
	public static $instances = [];
28
29
	/**
30
	 * Make a new application instance and associate it with the current portal.
31
	 *
32
	 * @return Application
33
	 */
34
	public static function make() {
35
		$application = Application::make();
36
37
		static::setApplication( $application );
38
39
		return $application;
40
	}
41
42
	/**
43
	 * Get the portal application.
44
	 *
45
	 * @return object|null
46
	 */
47
	public static function getApplication() {
48
		return Arr::get( static::$instances, static::class, null );
49
	}
50
51
	/**
52
	 * Set the portal application.
53
	 *
54
	 * @param  object|null $application
55
	 * @return void
56
	 */
57
	public static function setApplication( $application ) {
58
		if ( $application !== null ) {
59
			static::$instances[ static::class ] = $application;
60
		} else {
61
			unset( static::$instances[ static::class ] );
62
		}
63
	}
64
65
	/**
66
	 * Invoke any matching instance alias for the static method used.
67
	 *
68
	 * @param  string $method
69
	 * @param  array  $parameters
70
	 * @return mixed
71
	 */
72
	public static function __callStatic( $method, $parameters ) {
73
		$application = static::getApplication();
74
		$callable = [$application, $method];
75
76
		if ( ! $application ) {
77
			throw new ConfigurationException(
78
				'Application instance not registered with portal: ' . static::class . '. ' .
79
				'Did you miss to call ' . static::class . '::make()->bootstrap()?'
80
			);
81
		}
82
83
		if ( ! is_callable( $callable ) ) {
84
			throw new BadMethodCallException( "Method {$method} does not exist." );
85
		}
86
87
		return call_user_func_array( $callable, $parameters );
88
	}
89
}
90