LazyCalls   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 21
dl 0
loc 69
ccs 22
cts 22
cp 1
rs 10
c 1
b 1
f 0
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A invokeLazyCalls() 0 8 2
A addCall() 0 5 1
A instance() 0 13 3
A __call() 0 7 2
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