Completed
Push — master ( cd4d3e...4fea37 )
by Karel
06:37
created

Callback::setSerializeNull()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 3
1
<?php
2
3
namespace FOS\ElasticaBundle\Serializer;
4
5
use JMS\Serializer\SerializationContext;
6
use JMS\Serializer\SerializerInterface;
7
8
class Callback
9
{
10
    protected $serializer;
11
    protected $groups = array();
12
    protected $version;
13
    protected $serializeNull;
14 1
15
    public function setSerializer($serializer)
16 1
    {
17 1
        $this->serializer = $serializer;
18
        if (!method_exists($this->serializer, 'serialize')) {
19
            throw new \RuntimeException('The serializer must have a "serialize" method.');
20 1
        }
21
    }
22 1
23
    public function setGroups(array $groups)
24 1
    {
25
        $this->groups = $groups;
26 1
27
        if (!empty($this->groups) && !$this->serializer instanceof SerializerInterface) {
28
            throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
29 1
        }
30
    }
31 1
32
    public function setVersion($version)
33 1
    {
34
        $this->version = $version;
35 1
36
        if ($this->version && !$this->serializer instanceof SerializerInterface) {
37
            throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
38 1
        }
39
    }
40 1
41
    public function setSerializeNull($serializeNull)
42 1
    {
43
        $this->serializeNull = $serializeNull;
44 1
45 1
        if (true === $this->serializeNull && !$this->serializer instanceof SerializerInterface) {
46
            throw new \RuntimeException('Setting null value serialization option requires using "JMS\Serializer\Serializer".');
47
        }
48 1
    }
49 1
50
    public function serialize($object)
51
    {
52 1
        $context = $this->serializer instanceof SerializerInterface ? SerializationContext::create()->enableMaxDepthChecks() : array();
53
54
        if (!empty($this->groups)) {
55
            $context->setGroups($this->groups);
56
        }
57
58
        if ($this->version) {
59
            $context->setVersion($this->version);
60
        }
61
62
        $context->setSerializeNull($this->serializeNull);
63
64
        return $this->serializer->serialize($object, 'json', $context);
65
    }
66
}
67