-
-
Notifications
You must be signed in to change notification settings - Fork 588
Expand file tree
/
Copy pathDepthExclusionStrategy.php
More file actions
104 lines (79 loc) · 2.74 KB
/
DepthExclusionStrategy.php
File metadata and controls
104 lines (79 loc) · 2.74 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
namespace JMS\Serializer\Exclusion;
use JMS\Serializer\Context;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*/
final class DepthExclusionStrategy implements ExclusionStrategyInterface
{
private bool $cachedResult = false;
private int $cachedStackCount = -1;
private bool $hasMaxDepthOnStack = false;
public function shouldSkipClass(ClassMetadata $metadata, Context $context): bool
{
return $this->isTooDeep($context);
}
public function shouldSkipProperty(PropertyMetadata $property, Context $context): bool
{
return $this->isTooDeep($context);
}
private function isTooDeep(Context $context): bool
{
$currentCount = $context->getMetadataStackSize();
if ($currentCount === $this->cachedStackCount) {
return $this->cachedResult;
}
if ($currentCount < $this->cachedStackCount && !$this->cachedResult) {
$this->cachedStackCount = $currentCount;
return false;
}
$stack = $context->getMetadataStack();
if (!$this->hasMaxDepthOnStack && !$this->cachedResult && $currentCount > $this->cachedStackCount) {
$delta = $currentCount - $this->cachedStackCount;
$found = false;
$i = 0;
foreach ($stack as $metadata) {
if ($i >= $delta) {
break;
}
if ($metadata instanceof PropertyMetadata && null !== $metadata->maxDepth) {
$found = true;
break;
}
$i++;
}
if (!$found) {
$this->cachedStackCount = $currentCount;
return false;
}
}
// Full scan
$relativeDepth = 0;
$top = $currentCount > 0 ? $stack[0] : null;
$foundMaxDepth = false;
foreach ($stack as $metadata) {
if (!$metadata instanceof PropertyMetadata) {
continue;
}
$relativeDepth++;
if (null !== $metadata->maxDepth) {
$foundMaxDepth = true;
}
if (0 === $metadata->maxDepth && $top === $metadata) {
continue;
}
if (null !== $metadata->maxDepth && $relativeDepth > $metadata->maxDepth) {
$this->cachedResult = true;
$this->cachedStackCount = $currentCount;
return true;
}
}
$this->hasMaxDepthOnStack = $foundMaxDepth;
$this->cachedResult = false;
$this->cachedStackCount = $currentCount;
return false;
}
}