Completed
Push — master ( a1e9b9...722995 )
by Tomasz
05:32
created

SymfonySerializer::unserialize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
crap 3.0261
1
<?php
2
3
namespace Gendoria\CommandQueueBundle\Serializer;
4
5
use Exception;
6
use Gendoria\CommandQueue\Command\CommandInterface;
7
use Gendoria\CommandQueue\Serializer\SerializedCommandData;
8
use Gendoria\CommandQueue\Serializer\SerializerInterface;
9
use Gendoria\CommandQueue\Worker\Exception\TranslateErrorException;
10
use Symfony\Component\Serializer\Serializer;
11
12
/**
13
 * Description of SymfonySerializer
14
 *
15
 * @author Tomasz Struczyński <[email protected]>
16
 */
17
class SymfonySerializer 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 4
    public function __construct(Serializer $serializer, $format = "json")
33
    {
34 4
        $this->serializer = $serializer;
35 4
        $this->format = $format;
36 4
    }
37
    
38 2
    public function serialize(CommandInterface $command)
39
    {
40 2
        return new SerializedCommandData($this->serializer->serialize($command, $this->format), get_class($command));
41
    }
42
43 3
    public function unserialize(SerializedCommandData $serializedCommandData)
44
    {
45
        try {
46 3
            $command = $this->serializer->deserialize($serializedCommandData->getSerializedCommand(), $serializedCommandData->getCommandClass(), $this->format);
47 3
        } catch (Exception $e) {
48
            throw new TranslateErrorException($serializedCommandData, $e->getMessage(), $e->getCode(), $e);
49
        }
50 3
        if (!$command instanceof CommandInterface) {
51 2
            throw new TranslateErrorException($serializedCommandData, "Unserialized command should implement CommandInterface.");
52
        }
53 1
        return $command;
54
    }
55
56
}
57