Completed
Pull Request — master (#19)
by Akihito
04:19
created

Normalizer::supportsNormalization()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
namespace Ackintosh\Snidel\Task;
3
4
use Opis\Closure\SerializableClosure;
5
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
6
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
7
8
class Normalizer implements NormalizerInterface, DenormalizerInterface
9
{
10
    /**
11
     * {@inheritdoc}
12
     */
13
    public function supportsNormalization($data, $format = null)
14
    {
15
        return $data instanceof Task;
16
    }
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function supportsDenormalization($data, $type, $format = null)
22
    {
23
        return $type === 'Ackintosh\Snidel\Task\Task';
24
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function normalize($object, $format = null, array $context = array())
30
    {
31
        $callable = $object->getCallable();
32
33
        return serialize(new Task(
34
            (self::isClosure($callable) ? new SerializableClosure($callable) : $callable),
35
            $object->getArgs(),
36
            $object->getTag()
37
        ));
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function denormalize($data, $class, $format = null, array $context = array())
44
    {
45
        $task = unserialize($data);
46
        if (self::isClosure($callable = $task->getCallable())) {
47
            $task = new Task(
48
                $callable->getClosure(),
49
                $task->getArgs(),
50
                $task->getTag()
51
            );
52
        }
53
54
        return $task;
55
    }
56
57
    /**
58
     * @param   mixed   $callable
59
     * @return  bool
60
     */
61
    private static function isClosure($callable)
62
    {
63
        return is_object($callable) && is_callable($callable);
64
    }
65
}
66