1<?php
2
3declare(strict_types=1);
4
5namespace JMS\Serializer\Exclusion;
6
7use JMS\Serializer\Context;
8use JMS\Serializer\Metadata\ClassMetadata;
9use JMS\Serializer\Metadata\PropertyMetadata;
10
11/**
12 * @author Adrien Brault <adrien.brault@gmail.com>
13 */
14final class DepthExclusionStrategy implements ExclusionStrategyInterface
15{
16    /**
17     * {@inheritDoc}
18     */
19    public function shouldSkipClass(ClassMetadata $metadata, Context $context): bool
20    {
21        return $this->isTooDeep($context);
22    }
23
24    /**
25     * {@inheritDoc}
26     */
27    public function shouldSkipProperty(PropertyMetadata $property, Context $context): bool
28    {
29        return $this->isTooDeep($context);
30    }
31
32    private function isTooDeep(Context $context): bool
33    {
34        $depth = $context->getDepth();
35        $metadataStack = $context->getMetadataStack();
36
37        $nthProperty = 0;
38        // iterate from the first added items to the lasts
39        for ($i = $metadataStack->count() - 1; $i > 0; $i--) {
40            $metadata = $metadataStack[$i];
41            if ($metadata instanceof PropertyMetadata) {
42                $nthProperty++;
43                $relativeDepth = $depth - $nthProperty;
44
45                if (null !== $metadata->maxDepth && $relativeDepth > $metadata->maxDepth) {
46                    return true;
47                }
48            }
49        }
50
51        return false;
52    }
53}
54