Completed
Push — master ( ca959b...d3c999 )
by Tomasz
06:06
created

JmsSerializer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 51
ccs 13
cts 13
cp 1
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A serialize() 0 4 1
A unserialize() 0 12 4
1
<?php
2
3
namespace Gendoria\CommandQueueBundle\Serializer;
4
5
use Exception;
6
use Gendoria\CommandQueue\Command\CommandInterface;
7
use Gendoria\CommandQueue\Serializer\Exception\UnserializeErrorException;
8
use Gendoria\CommandQueue\Serializer\SerializedCommandData;
9
use Gendoria\CommandQueue\Serializer\SerializerInterface;
10
use JMS\Serializer\Serializer;
11
12
/**
13
 * Serializer using JMS serializer module
14
 *
15
 * @author Tomasz Struczyński <[email protected]>
16
 */
17
class JmsSerializer implements SerializerInterface
18
{
19
    /**
20
     *
21
     * @var Serializer
22
     */
23
    private $serializer;
24
    
25
    /**
26
     * Serialization format.
27
     * 
28
     * @var string
29
     */
30
    private $format;
31
    
32
    /**
33
     * Class constructor.
34
     * 
35
     * @param Serializer $serializer
36
     * @param string $format Serialization format.
37
     */
38 4
    public function __construct(Serializer $serializer, $format = "json")
39
    {
40 4
        $this->serializer = $serializer;
41 4
        $this->format = $format;
42 4
    }
43
    
44
    /**
45
     * {@inheritdoc}
46
     */
47 2
    public function serialize(CommandInterface $command)
48
    {
49 2
        return new SerializedCommandData($this->serializer->serialize($command, $this->format), get_class($command));
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 3
    public function unserialize(SerializedCommandData $serializedCommandData)
56
    {
57
        try {
58 3
            $command = $this->serializer->deserialize($serializedCommandData->getSerializedCommand(), $serializedCommandData->getCommandClass(), $this->format);
59 3
        } catch (Exception $e) {
60 1
            throw new UnserializeErrorException($serializedCommandData, $e->getMessage(), $e->getCode(), $e);
61
        }
62 2
        if (!is_object($command) || !$command instanceof CommandInterface) {
63 1
            throw new UnserializeErrorException($serializedCommandData, "Unserialized command should implement CommandInterface.");
64
        }
65 1
        return $command;
66
    }
67
}
68