|
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
|
|
|
|