Completed
Push — master ( 81b69d...0d56ca )
by Eric
02:57
created

CircularReferenceExclusionStrategy::skipClass()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 6.7272
cc 7
eloc 16
nc 6
nop 2
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
17
/**
18
 * @author GeLo <[email protected]>
19
 */
20
class CircularReferenceExclusionStrategy extends ExclusionStrategy
21
{
22
    /**
23
     * @var int
24
     */
25
    private $limit;
26
27
    /**
28
     * @param int $limit
29
     */
30
    public function __construct($limit = 1)
31
    {
32
        $this->limit = $limit;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function skipClass(ClassMetadataInterface $class, ContextInterface $context)
39
    {
40
        $references = [];
41
        $dataStack = $context->getDataStack();
42
        $metadataStack = $context->getMetadataStack();
43
44
        for ($i = $metadataStack->count() - 1; $i > 0; --$i) {
45
            $data = $dataStack[$i];
46
            $metadata = $metadataStack[$i];
47
48
            if (!$metadata instanceof ClassMetadataInterface || !is_object($data)) {
49
                continue;
50
            }
51
52
            $hash = spl_object_hash($data);
53
54
            if (!isset($references[$hash])) {
55
                $references[$hash] = 0;
56
            }
57
58
            foreach ($references as &$reference) {
59
                if (++$reference >= $this->limit) {
60
                    return true;
61
                }
62
            }
63
        }
64
65
        return false;
66
    }
67
}
68