1<?php
2
3declare(strict_types=1);
4
5namespace JMS\Serializer\Tests\Handler;
6
7use Doctrine\Common\Collections\ArrayCollection;
8use Doctrine\Common\Collections\Collection;
9use JMS\Serializer\Annotation as Serializer;
10use JMS\Serializer\Exclusion\DepthExclusionStrategy;
11use JMS\Serializer\SerializationContext;
12use JMS\Serializer\Serializer as JMSSerializer;
13use JMS\Serializer\SerializerBuilder;
14use PHPUnit\Framework\TestCase;
15
16class ArrayCollectionDepthTest extends TestCase
17{
18    /** @var JMSSerializer */
19    private $serializer;
20
21    public function setUp()
22    {
23        $this->serializer = SerializerBuilder::create()->build();
24    }
25
26    /**
27     * @param array|Collection $collection
28     *
29     * @dataProvider getCollections
30     */
31    public function testDepth($collection)
32    {
33        $context = SerializationContext::create()
34            ->addExclusionStrategy(new DepthExclusionStrategy());
35        $result = $this->serializer->serialize(new CollectionWrapper($collection), 'json', $context);
36        self::assertSame('{"collection":[{"name":"lvl1","next":{"name":"lvl2"}}]}', $result);
37    }
38
39    public static function getCollections()
40    {
41        $data = [new Node('lvl1', new Node('lvl2', new Node('lvl3')))];
42        return [
43            [$data],
44            [new ArrayCollection($data)],
45        ];
46    }
47}
48
49class CollectionWrapper
50{
51    /**
52     * @Serializer\MaxDepth(2)
53     */
54    public $collection;
55
56    public function __construct($collection)
57    {
58        $this->collection = $collection;
59    }
60}
61
62class Node
63{
64    public $name;
65
66    public $next;
67
68    public function __construct($name, $next = null)
69    {
70        $this->name = $name;
71        $this->next = $next;
72    }
73}
74