1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Fesor\RequestObject\Examples\Request; |
4
|
|
|
|
5
|
|
|
use Fesor\RequestObject\RequestObject; |
6
|
|
|
use Symfony\Component\Validator\Constraints as Assert; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class ContextDependingRequest |
10
|
|
|
* @package Fesor\RequestObject\Examples\Request |
11
|
|
|
* |
12
|
|
|
* Please note that this example is more a hack |
13
|
|
|
* than real solution due limitations of `Collection` |
14
|
|
|
* validator... Please consider to use CallbackValidator |
15
|
|
|
* for cases like this. Or you can make some helper-function. |
16
|
|
|
*/ |
17
|
|
|
class ContextDependingRequest extends RequestObject |
18
|
|
|
{ |
19
|
|
|
public function rules() |
20
|
|
|
{ |
21
|
|
|
return [ |
22
|
|
|
// Add required fileds |
23
|
|
|
$this->collection([ |
24
|
|
|
'buz' => new Assert\Type('string'), |
25
|
|
|
'context' => new Assert\Optional( |
26
|
|
|
new Assert\Choice(['first', 'second']) |
27
|
|
|
), |
28
|
|
|
// to be sure that no extra fields allowed by default |
29
|
|
|
'foo' => new Assert\Optional(), |
30
|
|
|
'bar' => new Assert\Optional() |
31
|
|
|
]), |
32
|
|
|
// add fields required within "first" validation groups |
33
|
|
|
$this->collection([ |
34
|
|
|
'foo' => new Assert\Type('string'), |
35
|
|
|
], ['groups' => ['first'], 'allowExtraFields' => true]), |
36
|
|
|
// add fields required within "second" validation groups |
37
|
|
|
$this->collection([ |
38
|
|
|
'bar' => new Assert\Type('string'), |
39
|
|
|
], ['groups' => ['second'], 'allowExtraFields' => true]), |
40
|
|
|
]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function validationGroup(array $payload) |
44
|
|
|
{ |
45
|
|
|
return isset($payload['context']) ? |
46
|
|
|
['Default', $payload['context']] : null; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function collection($fields, array $options = null) |
50
|
|
|
{ |
51
|
|
|
if (!$options) { |
52
|
|
|
$options = []; |
53
|
|
|
} |
54
|
|
|
$options['fields'] = array_map(function ($constraints) use ($options) { |
55
|
|
|
if ($constraints instanceof Assert\Existence || !array_key_exists('groups', $options)) { |
56
|
|
|
return $constraints; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return new Assert\Required([ |
60
|
|
|
'constraints' => $constraints, |
61
|
|
|
'groups' => $options['groups'] |
62
|
|
|
]); |
63
|
|
|
}, $fields); |
64
|
|
|
|
65
|
|
|
return new Assert\Collection($options); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|