-
Notifications
You must be signed in to change notification settings - Fork 1
/
Caster.php
77 lines (67 loc) · 1.88 KB
/
Caster.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
<?php
namespace Gl3n\HttpQueryStringFilterBundle;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Gl3n\HttpQueryStringFilterBundle\ParameterType\ParameterTypeChain;
/**
* Casts given or default query parameter
*/
class Caster
{
/**
* @var ParameterTypeChain
*/
private $parameterTypeChain;
/**
* Constructor
*
* @param ParameterTypeChain $parameterTypeChain
*/
public function __construct(ParameterTypeChain $parameterTypeChain)
{
$this->parameterTypeChain = $parameterTypeChain;
}
/**
* Casts a value
*
* @param array $options
* @param string|array $value
*
* @return mixed
*/
public function cast(array $options, $value)
{
$parameterType = $this->parameterTypeChain->getParameterType($options['type']);
if ($options['array']) {
foreach ($value as &$subValue) {
$subValue = $parameterType->castValue($subValue);
}
} else {
$value = $parameterType->castValue($value);
}
return $value;
}
/**
* Returns casted default value
*
* @param array $options
*
* @return mixed
*/
public function getDefaultValue(array $options)
{
$parameterType = $this->parameterTypeChain->getParameterType($options['type']);
if ($options['array']) {
$language = new ExpressionLanguage;
$defaultValue = $language->evaluate($options['default']);
if (is_array($defaultValue)) {
foreach ($defaultValue as &$subValue) {
$subValue = $parameterType->castValue($subValue);
}
}
return $defaultValue;
} else {
return $parameterType->castValue($options['default']);
}
}
}