Completed
Push — 4.0 ( 54735f...16e8d7 )
by Olivier
01:58
created

ModelProvider::provide()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\ActiveRecord;
13
14
/**
15
 * Provides a {@link Model} instance.
16
 */
17
class ModelProvider
18
{
19
	/**
20
	 * @var callable {@link Model} provider
21
	 */
22
	static private $provider;
23
24
	/**
25
	 * Defines the {@link Model} provider.
26
	 *
27
	 * @param callable $provider
28
	 *
29
	 * @return callable The previous provider, or `null` if none was defined.
30
	 */
31
	static public function define(callable $provider)
32
	{
33
		$previous = self::$provider;
34
35
		self::$provider = $provider;
36
37
		return $previous;
38
	}
39
40
	/**
41
	 * Returns the current provider.
42
	 *
43
	 * @return callable|null
44
	 */
45
	static public function defined()
46
	{
47
		return self::$provider;
48
	}
49
50
	/**
51
	 * Undefine the provider.
52
	 */
53
	static public function undefine()
54
	{
55
		self::$provider = null;
56
	}
57
58
	/**
59
	 * Returns a {@link Model} instance using the provider.
60
	 *
61
	 * @param string $id Model identifier.
62
	 *
63
	 * @return Model
64
	 *
65
	 * @throws ModelNotDefined if the model cannot be provided.
66
	 */
67
	static public function provide($id)
68
	{
69
		$provider = self::$provider;
70
71
		if (!$provider)
72
		{
73
			throw new \LogicException("No provider is defined yet. Please define one with `ModelProvider::define(\$provider)`.");
74
		}
75
76
		$model = $provider($id);
77
78
		if (!$model)
79
		{
80
			throw new ModelNotDefined($id);
81
		}
82
83
		return $model;
84
	}
85
}
86