-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlexDataGen.php
84 lines (71 loc) · 2.95 KB
/
FlexDataGen.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
<?php
// ============================================================================
abstract class FlexDataGen {
/*
Base class for all random data generators. Each generator must implement
the generateValue() function that retrieves a new random value based on the
defined distribution function
*/
// ============================================================================
protected $options;
// ------------------------------------------------------------------------
public function __construct(
$options = []
) {
// ------------------------------------------------------------------------
$this->options = $options;
}
// ------------------------------------------------------------------------
public function isNull(
) {
// ------------------------------------------------------------------------
return isset($this->options['nulls']) && $nulls > 0 && $nulls <= 1
&& rand(0, 100) / 100. < $this->options['nulls'];
}
// ------------------------------------------------------------------------
public function isUnique(
) {
// ------------------------------------------------------------------------
return isset($this->options['unique'])
&& $this->options['unique'] === true;
}
// ------------------------------------------------------------------------
public function getData(
$count = 1
) {
// ------------------------------------------------------------------------
$data = [];
for($i = 1; $i <= $count; $i++) {
if($this->isNull()) {
$data[] = null;
continue;
}
while(true) {
$v = $this->generateValue($i);
if($this->isUnique() && $this->alreadyExists($v, $data))
continue;
$this->postProcess($v);
break;
}
$data[] = $v;
}
return $data;
}
// ------------------------------------------------------------------------
// can be overridden if in_array doesn't fit the generator
protected function alreadyExists(&$value, &$data) {
// ------------------------------------------------------------------------
return in_array($value, $data);
}
// ------------------------------------------------------------------------
// should be invoked last if overridden
protected function postProcess(&$value) {
// ------------------------------------------------------------------------
if(isset($this->options['postProcess']) && is_callable($this->options['postProcess']))
$this->options['postProcess']($value);
}
// ------------------------------------------------------------------------
// ABSTRACT FUNCTIONS
// ------------------------------------------------------------------------
protected abstract function generateValue($row_no);
}