Completed
Pull Request — master (#917)
by Dmitry
08:52
created

Callback   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 16
c 2
b 1
f 0
lcom 1
cbo 1
dl 0
loc 61
ccs 0
cts 29
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setSerializer() 0 7 2
A setGroups() 0 8 3
A setVersion() 0 8 3
A setSerializeNull() 0 8 3
B serialize() 0 18 5
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
15
    public function setSerializer($serializer)
16
    {
17
        $this->serializer = $serializer;
18
        if (!method_exists($this->serializer, 'serialize')) {
19
            throw new \RuntimeException('The serializer must have a "serialize" method.');
20
        }
21
    }
22
23
    public function setGroups(array $groups)
24
    {
25
        $this->groups = $groups;
26
27
        if (!empty($this->groups) && !$this->serializer instanceof SerializerInterface) {
28
            throw new \RuntimeException('Setting serialization groups requires using "JMS\Serializer\Serializer".');
29
        }
30
    }
31
32
    public function setVersion($version)
33
    {
34
        $this->version = $version;
35
36
        if ($this->version && !$this->serializer instanceof SerializerInterface) {
37
            throw new \RuntimeException('Setting serialization version requires using "JMS\Serializer\Serializer".');
38
        }
39
    }
40
41
    public function setSerializeNull($serializeNull)
42
    {
43
        $this->serializeNull = $serializeNull;
44
45
        if (true === $this->serializeNull && !$this->serializer instanceof SerializerInterface) {
46
            throw new \RuntimeException('Setting null value serialization option requires using "JMS\Serializer\Serializer".');
47
        }
48
    }
49
50
    public function serialize($object)
51
    {
52
        $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
        if (!is_array($context)) {
63
          $context->setSerializeNull($this->serializeNull);
64
        }
65
66
        return $this->serializer->serialize($object, 'json', $context);
67
    }
68
}
69