/
GroupsExclusionStrategy.php
115 lines (93 loc) · 2.86 KB
/
GroupsExclusionStrategy.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
declare(strict_types=1);
namespace JMS\Serializer\Exclusion;
use JMS\Serializer\Context;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
final class GroupsExclusionStrategy implements ExclusionStrategyInterface
{
public const DEFAULT_GROUP = 'Default';
/**
* @var array
*/
private $groups = [];
/**
* @var bool
*/
private $nestedGroups = false;
public function __construct(array $groups)
{
if (empty($groups)) {
$groups = [self::DEFAULT_GROUP];
}
foreach ($groups as $group) {
if (is_array($group)) {
$this->nestedGroups = true;
break;
}
}
if ($this->nestedGroups) {
$this->groups = $groups;
} else {
foreach ($groups as $group) {
$this->groups[$group] = true;
}
}
}
public function shouldSkipClass(ClassMetadata $metadata, Context $navigatorContext): bool
{
return false;
}
public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext): bool
{
if ($this->nestedGroups) {
$groups = $this->getGroupsFor($navigatorContext);
if (!$property->groups) {
return !in_array(self::DEFAULT_GROUP, $groups);
}
return $this->shouldSkipUsingGroups($property, $groups);
} else {
if (!$property->groups) {
return !isset($this->groups[self::DEFAULT_GROUP]);
}
foreach ($property->groups as $group) {
if (is_scalar($group) && isset($this->groups[$group])) {
return false;
}
}
return true;
}
}
private function shouldSkipUsingGroups(PropertyMetadata $property, array $groups): bool
{
foreach ($property->groups as $group) {
if (in_array($group, $groups)) {
return false;
}
}
return true;
}
public function getGroupsFor(Context $navigatorContext): array
{
if (!$this->nestedGroups) {
return array_keys($this->groups);
}
$paths = $navigatorContext->getCurrentPath();
$groups = $this->groups;
foreach ($paths as $index => $path) {
if (!array_key_exists($path, $groups)) {
if ($index > 0) {
$groups = [self::DEFAULT_GROUP];
} else {
$groups = array_filter($groups, 'is_string') ?: [self::DEFAULT_GROUP];
}
break;
}
$groups = $groups[$path];
if (!array_filter($groups, 'is_string')) {
$groups += [self::DEFAULT_GROUP];
}
}
return $groups;
}
}