LazyCalls::instance()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 0
crap 3
1
<?php
2
/**
3
 * Save some calls of driver for future real query invocation
4
 *
5
 * @file      LazyCalls.php
6
 *
7
 * PHP version 8.0+
8
 *
9
 * @author    Yancharuk Alexander <alex at itvault dot info>
10
 * @copyright © 2012-2021 Alexander Yancharuk
11
 * @date      2015-12-26 13:38
12
 * @license   The BSD 3-Clause License
13
 *            <http://opensource.org/licenses/BSD-3-Clause>
14
 */
15
16
namespace Veles\Traits;
17
18
use Exception;
19
20
trait LazyCalls
21
{
22
	/** @var  array */
23
	protected static $calls = [];
24
25
	use Driver;
26
	use SingletonInstance;
27
28
	/**
29
	 * Lazy calls invocation
30
	 */
31 2
	protected static function invokeLazyCalls()
32
	{
33 2
		[$calls, static::$calls] = [static::$calls, []];
34
35 2
		foreach ($calls as $call) {
36 2
			call_user_func_array(
37 2
				[static::instance()->getDriver(), $call['method']],
0 ignored issues
show
Bug introduced by
It seems like getDriver() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
				[static::instance()->/** @scrutinizer ignore-call */ getDriver(), $call['method']],
Loading history...
38 2
				$call['arguments']
39 2
			);
40
		}
41
	}
42
43
	/**
44
	 * @return $this
45
	 */
46 21
	public static function instance()
47
	{
48 21
		if (null === static::$instance) {
49 5
			$class = static::class;
50
51 5
			static::$instance = new $class;
52
		}
53
54 21
		if ([] !== static::$calls) {
55 2
			static::invokeLazyCalls();
56
		}
57
58 21
		return static::$instance;
59
	}
60
61
	/**
62
	 * Collect calls which will be invoked during first real query
63
	 *
64
	 * @param $method
65
	 * @param $arguments
66
	 *
67
	 * @throws Exception
68
	 */
69 2
	public function __call($method, $arguments)
70
	{
71 2
		if (!method_exists($this->getDriver(), $method)) {
72 1
			throw new Exception('Calling non existent method!');
73
		}
74
75 1
		static::addCall($method, $arguments);
76
	}
77
78
	/**
79
	 * Save calls for future invocation
80
	 *
81
	 * @param string $method Method name that should be called
82
	 * @param array $arguments Method arguments
83
	 */
84 2
	public static function addCall($method, array $arguments = [])
85
	{
86 2
		static::$calls[] = [
87 2
			'method'    => $method,
88 2
			'arguments' => $arguments
89 2
		];
90
	}
91
}
92