Completed
Push — master ( 722995...d594b8 )
by Tomasz
05:21
created

JmsSerializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Gendoria\CommandQueueBundle\Serializer;
4
5
use Gendoria\CommandQueue\Command\CommandInterface;
6
use Gendoria\CommandQueue\Serializer\SerializedCommandData;
7
use Gendoria\CommandQueue\Serializer\SerializerInterface;
8
use Gendoria\CommandQueue\Worker\Exception\TranslateErrorException;
9
use JMS\Serializer\Serializer;
10
11
/**
12
 * Serializer using JMS serializer module
13
 *
14
 * @author Tomasz Struczyński <[email protected]>
15
 */
16
class JmsSerializer implements SerializerInterface
17
{
18
    /**
19
     *
20
     * @var Serializer
21
     */
22
    private $serializer;
23
    
24
    /**
25
     * Serialization format.
26
     * 
27
     * @var string
28
     */
29
    private $format;
30
    
31 4
    public function __construct(Serializer $serializer, $format = "json")
32
    {
33 4
        $this->serializer = $serializer;
34 4
        $this->format = $format;
35 4
    }
36
    
37
    /**
38
     * {@inheritdoc}
39
     */
40 2
    public function serialize(CommandInterface $command)
41
    {
42 2
        return new SerializedCommandData($this->serializer->serialize($command, $this->format), get_class($command));
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48 3
    public function unserialize(SerializedCommandData $serializedCommandData)
49
    {
50
        try {
51 3
            $command = $this->serializer->deserialize($serializedCommandData->getSerializedCommand(), $serializedCommandData->getCommandClass(), $this->format);
52 3
        } catch (\Exception $e) {
53
            throw new TranslateErrorException($serializedCommandData, $e->getMessage(), $e->getCode(), $e);
54
        }
55 3
        if (!is_object($command) || !$command instanceof CommandInterface) {
56 2
            throw new TranslateErrorException($serializedCommandData, "Unserialized command should implement CommandInterface.");
57
        }
58 1
        return $command;
59
    }
60
}
61