Completed
Push — master ( 32cb15...ce22ce )
by Alexander
05:39 queued 02:43
created

LazyCalls   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 8
c 2
b 1
f 0
lcom 1
cbo 2
dl 0
loc 73
ccs 28
cts 28
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A invokeLazyCalls() 0 11 2
A instance() 0 14 3
A __call() 0 8 2
A addCall() 0 7 1
1
<?php
2
/**
3
 * Save some calls of driver for future real query invocation
4
 *
5
 * @file      LazyCalls.php
6
 *
7
 * PHP version 5.4+
8
 *
9
 * @author    Yancharuk Alexander <alex at itvault dot info>
10
 * @copyright © 2012-2015 Alexander Yancharuk <alex at itvault at info>
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 Traits;
17
18
use Exception;
19
use Veles\Traits\SingletonInstance;
20
21
trait LazyCalls
22
{
23
	/** @var  array */
24
	protected static $calls = [];
25
26
	use Driver;
27
	use SingletonInstance;
28
29
	/**
30
	 * Lazy calls invocation
31
	 */
32 2
	protected static function invokeLazyCalls()
33
	{
34 2
		list($calls, static::$calls) = [static::$calls, []];
35
36 2
		foreach ($calls as $call) {
37 2
			call_user_func_array(
38 2
				[static::instance()->getDriver(), $call['method']],
39 2
				$call['arguments']
40 2
			);
41 2
		}
42 2
	}
43
44
	/**
45
	 * @return $this
46
	 */
47 2
	public static function instance()
48
	{
49 2
		if (null === static::$instance) {
50 2
			$class = get_called_class();
51
52 2
			static::$instance = new $class;
53 2
		}
54
55 2
		if ([] !== static::$calls) {
56 2
			static::invokeLazyCalls();
57 2
		}
58
59 2
		return static::$instance;
60
	}
61
62
	/**
63
	 * Collect calls which will be invoked during first real query
64
	 *
65
	 * @param $method
66
	 * @param $arguments
67
	 *
68
	 * @return mixed
69
	 * @throws Exception
70
	 */
71 2
	public function __call($method, $arguments)
72
	{
73 2
		if (!method_exists($this->getDriver(), $method)) {
74 1
			throw new Exception('Calling non existent method!');
75
		}
76
77 1
		static::addCall($method, $arguments);
78 1
	}
79
80
	/**
81
	 * Save calls for future invocation
82
	 *
83
	 * @param string $method Method name that should be called
84
	 * @param array $arguments Method arguments
85
	 */
86 2
	public static function addCall($method, array $arguments = [])
87
	{
88 2
		static::$calls[] = [
89 2
			'method'    => $method,
90
			'arguments' => $arguments
91 2
		];
92 2
	}
93
}
94