This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
/
Params.php
130 lines (110 loc) · 3.09 KB
/
Params.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
<?php
namespace Model\Ontology;
class Params implements \Countable
{
use \Nette\SmartObject;
/** @var Combinations @see enumerateCombinations() */
private $combinations;
/** @var bool Combination may be repeated in multiple questions */
private $repeatAllowed = FALSE;
/** @var array Used up combination keys when combinations may not be repeated */
private $usedCombinationKeys = array();
/**
* @param array
*/
public function __construct($data)
{
$this->enumerateCombinations($data);
}
public function allowRepeat()
{
$this->repeatAllowed = TRUE;
}
/**
* Enumerates all possible combinations of used variables
* @param array
*/
private function enumerateCombinations($data)
{
$combinations = array(array());
foreach ($data as $key => $var) {
$combination = array();
foreach ($combinations as $values) {
foreach ($var as $val) {
$combination[] = array_merge($values, array($key => $val));
}
}
$combinations = $combination;
}
$this->combinations = $combinations;
}
/**
* @return int Returns a random combination key.
*/
public function assemble()
{
$keys = array_keys($this->combinations);
$availableKeys = array_diff($keys, $this->usedCombinationKeys);
$key = $availableKeys[array_rand($availableKeys)];
if (!$this->repeatAllowed) {
$this->usedCombinationKeys[] = $key;
}
return $key;
}
/**
* Returns a set of replacements for use in
* a strtr() function: walks over leaf nodes only
* and wraps the keys in %'s.
* @param int
* @return array
*/
public function produce($key)
{
$replacements = array();
array_walk_recursive(
$this->combinations[$key],
function($item, $key) use (&$replacements) {
$replacements['%' . $key . '%'] = $item;
}
);
return $replacements;
}
/**
* Returns all combinations' keys.
* @return array
*/
public function getKeys()
{
return array_keys($this->combinations);
}
/**
* Returns all possible values of a specific variable.
* @param string
* @return array
*/
public function getValues($var)
{
$values = array();
foreach ($this->combinations as $combination) {
$flat = array();
array_walk_recursive(
$combination,
function($item, $key) use (&$flat) {
$flat[$key] = $item;
}
);
if (!in_array($flat[$var], $values)) {
$values[] = $flat[$var];
}
}
return $values;
}
/**
* Get combinations' count
* @return int
*/
public function count()
{
return count($this->combinations);
}
}