coshi / variator
生成数据组合数组的工具
v0.0.2
2016-08-24 09:37 UTC
Requires
- php: 7.*
This package is not auto-updated.
Last update: 2024-09-26 03:30:28 UTC
README
用法
$factory = new VariationFactory();
$builder = new VariationsTreeBuilder($factory);
$config = [
'text' => [
'type' => 'enum',
'values' => ['first', 'second', 'third'],
],
];
$variations = $builder->build($config);
foreach ($variations as $values) {
foreach($values as $value) {
print($value); // displays first, second, third
}
}
更复杂的情况
$factory = new VariationFactory();
$builder = new VariationsTreeBuilder($factory);
$config = [
'text' => [
'type' => 'enum',
'values' => ['first', 'second', 'third'],
],
'number' => [
'type' => 'int',
'min' => 0,
'max' => 2
],
];
$variations = $builder->build($config);
foreach ($variations as $values) {
echo sprintf('text: %s, number: %d', $values['text'], $values['number']);
echo PHP_EOL;
}
输出将是
text: first, number: 0
text: second, number: 0
text: third, number: 0
text: first, number: 1
text: second, number: 1
text: third, number: 1
text: first, number: 2
text: second, number: 2
text: third, number: 2
它可以调用方法和函数来获取值
class DummyClass
{
public function someValues()
{
return [0, 1, 2];
}
}
$factory = new VariationFactory();
$builder = new VariationsTreeBuilder($factory);
$config = [
'text' => [
'type' => 'enum',
'values' => ['first', 'second', 'third'],
],
'number' => [
'type' => 'callback',
'callback' => [DummyClass::class, 'someValues']
],
];
$variations = $builder->build($config);
foreach ($variations as $values) {
echo sprintf('text: %s, number: %d', $values['text'], $values['number']);
echo PHP_EOL;
}
结果将完全与上一个相同。当回调定义为 '['range', [0, 2]]' 时,结果也将相同。
支持变体之间的交叉引用
class DummyClass
{
public function someValues($text)
{
$values = [
'first' => [0, 1],
'second' => [2, 3],
'third' => [4, 5],
];
return $values[$text];
}
}
$factory = new VariationFactory();
$builder = new VariationsTreeBuilder($factory);
$config = [
'text' => [
'type' => 'enum',
'values' => ['first', 'second', 'third'],
],
'number' => [
'type' => 'callback',
'callback' => [DummyClass::class, 'someValues', ['@text']],
'context_dependent' => true
],
];
$variations = $builder->build($config);
foreach ($variations as $values) {
echo sprintf('text: %s, number: %d', $values['text'], $values['number']);
echo PHP_EOL;
}
输出将是
text: first, number: 0
text: first, number: 1
text: second, number: 2
text: second, number: 3
text: third, number: 4
text: third, number: 5