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

SymfonySerializer::__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 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
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 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
    /**
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 2
    public function serialize(CommandInterface $command)
45
    {
46 2
        return new SerializedCommandData($this->serializer->serialize($command, $this->format), get_class($command));
47
    }
48
49 3
    public function unserialize(SerializedCommandData $serializedCommandData)
50
    {
51
        try {
52 3
            $command = $this->serializer->deserialize($serializedCommandData->getSerializedCommand(), $serializedCommandData->getCommandClass(), $this->format);
53 3
        } catch (Exception $e) {
54 1
            throw new UnserializeErrorException($serializedCommandData, $e->getMessage(), $e->getCode(), $e);
55
        }
56 2
        if (!is_object($command) || !$command instanceof CommandInterface) {
57 1
            throw new UnserializeErrorException($serializedCommandData, "Unserialized command should implement CommandInterface.");
58
        }
59 1
        return $command;
60
    }
61
62
}
63