-
Notifications
You must be signed in to change notification settings - Fork 17
/
ContextDependingRequest.php
67 lines (60 loc) · 2.17 KB
/
ContextDependingRequest.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
<?php
namespace Fesor\RequestObject\Examples\Request;
use Fesor\RequestObject\RequestObject;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class ContextDependingRequest
* @package Fesor\RequestObject\Examples\Request
*
* Please note that this example is more a hack
* than real solution due limitations of `Collection`
* validator... Please consider to use CallbackValidator
* for cases like this. Or you can make some helper-function.
*/
class ContextDependingRequest extends RequestObject
{
public function rules()
{
return [
// Add required fileds
$this->collection([
'buz' => new Assert\Type('string'),
'context' => new Assert\Optional(
new Assert\Choice(['first', 'second'])
),
// to be sure that no extra fields allowed by default
'foo' => new Assert\Optional(),
'bar' => new Assert\Optional(),
]),
// add fields required within "first" validation groups
$this->collection([
'foo' => new Assert\Type('string'),
], ['groups' => ['first'], 'allowExtraFields' => true]),
// add fields required within "second" validation groups
$this->collection([
'bar' => new Assert\Type('string'),
], ['groups' => ['second'], 'allowExtraFields' => true]),
];
}
public function validationGroup(array $payload)
{
return isset($payload['context']) ?
['Default', $payload['context']] : null;
}
private function collection($fields, array $options = null)
{
if (!$options) {
$options = [];
}
$options['fields'] = array_map(function ($constraints) use ($options) {
if ($constraints instanceof Assert\Existence || !array_key_exists('groups', $options)) {
return $constraints;
}
return new Assert\Required([
'constraints' => $constraints,
'groups' => $options['groups'],
]);
}, $fields);
return new Assert\Collection($options);
}
}