Completed
Push — master ( 43d45a...5355f5 )
by Eric
02:45
created

MaxDepthExclusionStrategy::skip()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 18
nc 10
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Ivory Serializer package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\Serializer\Exclusion;
13
14
use Ivory\Serializer\Context\ContextInterface;
15
use Ivory\Serializer\Mapping\ClassMetadataInterface;
16
use Ivory\Serializer\Mapping\PropertyMetadataInterface;
17
use Ivory\Serializer\Mapping\TypeMetadataInterface;
18
19
/**
20
 * @author GeLo <[email protected]>
21
 */
22
class MaxDepthExclusionStrategy extends ExclusionStrategy
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function skipClass(ClassMetadataInterface $class, ContextInterface $context)
28
    {
29
        return $this->skip($context);
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function skipType(TypeMetadataInterface $type, ContextInterface $context)
36
    {
37
        return $this->skip($context);
38
    }
39
40
    /**
41
     * @param ContextInterface $context
42
     *
43
     * @return bool
44
     */
45
    private function skip(ContextInterface $context)
46
    {
47
        if (!$context->hasMaxDepthEnabled()) {
48
            return false;
49
        }
50
51
        $metadataStack = $context->getMetadataStack();
52
        $stackDepth = count($context->getDataStack());
53
        $depth = 0;
54
55
        for ($i = $metadataStack->count() - 1; $i > 0; --$i) {
56
            $metadata = $metadataStack[$i];
57
58
            if ($metadata instanceof TypeMetadataInterface) {
59
                ++$depth;
60
            }
61
62
            if (!$metadata instanceof PropertyMetadataInterface) {
63
                continue;
64
            }
65
66
            ++$depth;
67
68
            if (!$metadata->hasMaxDepth()) {
69
                continue;
70
            }
71
72
            if ($stackDepth - $depth > $metadata->getMaxDepth()) {
73
                return true;
74
            }
75
        }
76
77
        return false;
78
    }
79
}
80