-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVariationFactory.php
More file actions
82 lines (69 loc) · 2.12 KB
/
VariationFactory.php
File metadata and controls
82 lines (69 loc) · 2.12 KB
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
<?php
declare (strict_types=1);
namespace Coshi\Variator;
use Coshi\Variator\Variation\AbstractVariation;
use Coshi\Variator\Variation\Type as VariationType;
class VariationFactory
{
protected $map = [
'int' => VariationType\IntVariation::class,
'enum' => VariationType\EnumVariation::class,
'callback' => VariationType\CallbackVariation::class,
];
/**
* @var ConfigResolver
*/
protected $configResolver;
/**
* @param string $name
* @param array $parameters
*
* @return AbstractVariation
*
* @throws \InvalidArgumentException
*/
public function createNew(string $name, array $parameters)
{
if (!$this->configResolver instanceof ConfigResolver) {
$this->configResolver = $this->getResolver();
}
if (!isset($this->map[$parameters['type']])) {
throw new \InvalidArgumentException(sprintf('Variation type %s is not valid', $parameters['type']));
}
$class = $this->map[$parameters['type']];
$class::validateParameters($parameters);
return new $class($name, $parameters, $this->configResolver);
}
/**
* @param string $type
* @param $value
*
* @throws \InvalidArgumentException
*/
public function validateValue(string $type, $value)
{
if (!isset($this->map[$type])) {
throw new \InvalidArgumentException(sprintf('Variation type %s is not valid', $type));
}
$class = $this->map[$type];
if (false === $class::validateValue($value)) {
$stringType = in_array(gettype($value), ['string', 'float'], true) ? $value : gettype($value);
throw new \InvalidArgumentException(sprintf('"%s" is not a valid value for type "%s"', $stringType, $type));
}
}
/**
* @param string $type
* @param string $className
*/
public function registerType(string $type, string $className)
{
$this->map[$type] = $className;
}
/**
* @return ConfigResolver
*/
protected function getResolver()
{
return new ConfigResolver();
}
}