1 <?php
2
3 /**
4 * Instance List Pool Trait.
5 *
6 * @author gharlan
7 *
8 * @package redaxo\core
9 */
10 trait rex_instance_list_pool_trait
11 {
12 /**
13 * @var mixed[]
14 */
15 private static $instanceLists = [];
16
17 /**
18 * Adds an instance list.
19 *
20 * @param mixed $key Key
21 * @param array $instanceKeyList Array of instance keys
22 */
23 protected static function addInstanceList($key, array $instanceKeyList)
24 {
25 $key = self::getInstanceListPoolKey($key);
26 self::$instanceLists[$key] = $instanceKeyList;
27 }
28
29 /**
30 * Checks whether an instance list exists for the given key.
31 *
32 * @param mixed $key Key
33 *
34 * @return bool
35 */
36 protected static function hasInstanceList($key)
37 {
38 $key = self::getInstanceListPoolKey($key);
39 return isset(self::$instanceLists[$key]);
40 }
41
42 /**
43 * Returns the instance list for the given key.
44 *
45 * If the instance list does not exist it will be created by calling the $createListCallback
46 *
47 * @param mixed $key Key
48 * @param callable $getInstanceCallback Callback, will be called for every list item to get the instance
49 * @param callable $createListCallback Callback, will be called to create the list of instance keys
50 *
51 * @return array
52 */
53 protected static function getInstanceList($key, callable $getInstanceCallback, callable $createListCallback = null)
54 {
55 $args = (array) $key;
56 $key = self::getInstanceListPoolKey($args);
57 if (!isset(self::$instanceLists[$key]) && $createListCallback) {
58 $list = call_user_func_array($createListCallback, $args);
59 self::$instanceLists[$key] = is_array($list) ? $list : [];
60 }
61 if (!isset(self::$instanceLists[$key])) {
62 return [];
63 }
64 $list = [];
65 foreach (self::$instanceLists[$key] as $instanceKey) {
66 $instance = call_user_func_array($getInstanceCallback, (array) $instanceKey);
67 if ($instance) {
68 $list[] = $instance;
69 }
70 }
71 return $list;
72 }
73
74 /**
75 * Clears the instance list of the given key.
76 *
77 * @param mixed $key Key
78 */
79 public static function clearInstanceList($key)
80 {
81 $key = self::getInstanceListPoolKey($key);
82 unset(self::$instanceLists[$key]);
83 }
84
85 /**
86 * Clears the instance list pool.
87 */
88 public static function clearInstanceListPool()
89 {
90 self::$instanceLists = [];
91 }
92
93 /**
94 * Returns a string representation for the key.
95 *
96 * The original key can be a scalar value or an array of scalar values
97 *
98 * @param mixed $key Key
99 *
100 * @return string
101 */
102 private static function getInstanceListPoolKey($key)
103 {
104 return implode('###', (array) $key);
105 }
106 }
107