LaravelSerializer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace Realshadow\RequestDeserializer\Serializers;
4
5
use Illuminate\Support\Collection;
6
use JMS\Serializer\Context;
7
use JMS\Serializer\GraphNavigator;
8
use JMS\Serializer\Handler\HandlerRegistry;
9
use JMS\Serializer\VisitorInterface;
10
11
12
/**
13
 * Extension of the base serializer which adds capabilities to work with Laravel's Collection
14
 *
15
 * @package Realshadow\RequestDeserializer\Serializers
16
 * @author Lukáš Homza <[email protected]>
17
 */
18
class LaravelSerializer extends AbstractSerializer
19
{
20
21
    /**
22
     * Adds the Collection handlers to handler stack
23
     *
24
     * @return \Closure
25
     */
26
    protected function addCollectionHandler()
27
    {
28
        return function (HandlerRegistry $registry) {
29
            $registry->registerHandler(
30
                GraphNavigator::DIRECTION_SERIALIZATION,
31
                Collection::class,
32
                'json',
33
                function (VisitorInterface $visitor, Collection $collection, array $type, Context $context) {
34
                    return $visitor->visitArray($collection->values(), $type, $context);
35
                }
36
            );
37
38
            $registry->registerHandler(
39
                GraphNavigator::DIRECTION_DESERIALIZATION,
40
                Collection::class,
41
                'json',
42
                function (VisitorInterface $visitor, array $data, array $type, Context $context) {
43
                    $data = $visitor->visitArray($data, $type, $context);
44
45
                    return new Collection($data);
46
                }
47
            );
48
        };
49
    }
50
51
    /**
52
     * LaravelSerializer constructor
53
     */
54
    public function __construct()
55
    {
56
        parent::__construct();
57
58
        $this->builder->configureHandlers($this->addCollectionHandler());
59
    }
60
61
}
62