1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Konsulting\Laravel\RuleRepository; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
|
8
|
|
|
trait RuleRepositoryTrait |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* The repository holder instance. |
12
|
|
|
* |
13
|
|
|
* @var RepositoryManager |
14
|
|
|
*/ |
15
|
|
|
protected static $repositoryInstances; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var Collection |
19
|
|
|
*/ |
20
|
|
|
protected static $masterRepositoryList; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Return the array of validation rules. |
24
|
|
|
* |
25
|
|
|
* @param string $repositoryName |
26
|
|
|
* @param string $state |
27
|
|
|
* @return array |
28
|
|
|
*/ |
29
|
8 |
|
public static function getRules($repositoryName, $state = null) |
30
|
|
|
{ |
31
|
8 |
|
return static::getInstance($repositoryName)->getRules($state); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Get the instance of the specified rule repository. If the repository is not already instantiated, instantiate |
36
|
|
|
* and store it in the repository instances array. |
37
|
|
|
* |
38
|
|
|
* @param string $name |
39
|
|
|
* @return RepositoryManager |
40
|
|
|
* @throws Exception |
41
|
|
|
*/ |
42
|
8 |
|
protected static function getInstance($name) |
43
|
|
|
{ |
44
|
8 |
|
static::$masterRepositoryList = collect(); |
45
|
8 |
|
if (isset(static::$ruleRepositories)) { |
46
|
4 |
|
static::$masterRepositoryList = collect(static::$ruleRepositories); |
47
|
|
|
} |
48
|
|
|
|
49
|
8 |
|
static::extractRepositoriesFromProperties(); |
50
|
|
|
|
51
|
8 |
|
return static::$repositoryInstances[$name] |
52
|
8 |
|
?? (static::$repositoryInstances[$name] = new RepositoryManager(new static::$masterRepositoryList[$name])); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Check if $string ends in $search. If it does, extract and return the string minus the search string; if not |
57
|
|
|
* return null. |
58
|
|
|
* |
59
|
|
|
* @param string $string |
60
|
|
|
* @param string $search |
61
|
|
|
* @return string |
62
|
|
|
*/ |
63
|
8 |
|
private static function extractFromString($string, $search) |
64
|
|
|
{ |
65
|
8 |
|
return substr($string, 0 - strlen($search)) == $search |
66
|
5 |
|
? str_replace($search, '', $string) |
67
|
8 |
|
: null; |
68
|
|
|
} |
69
|
|
|
|
70
|
8 |
|
private static function extractRepositoriesFromProperties() |
71
|
|
|
{ |
72
|
8 |
|
foreach (get_class_vars(static::class) as $key => $value) { |
73
|
8 |
|
$repositoryName = static::extractFromString($key, |
74
|
8 |
|
config('rule_repository.property_suffix', 'Repository')); |
75
|
|
|
|
76
|
8 |
|
if ($repositoryName) { |
77
|
8 |
|
static::$masterRepositoryList->put($repositoryName, $value); |
78
|
|
|
} |
79
|
|
|
} |
80
|
8 |
|
} |
81
|
|
|
} |
82
|
|
|
|