1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the xAPI package. |
5
|
|
|
* |
6
|
|
|
* (c) Christian Flothmann <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Xabbuh\XApi\Serializer\Symfony\Normalizer; |
13
|
|
|
|
14
|
|
|
use Symfony\Component\Serializer\Exception\LogicException; |
15
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
16
|
|
|
use Symfony\Component\Serializer\SerializerAwareInterface; |
17
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
18
|
|
|
use Xabbuh\XApi\Model\Activity; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Normalizes xAPI activities. |
22
|
|
|
* |
23
|
|
|
* @author Jérôme Parmentier <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
class ActivityNormalizer implements NormalizerInterface, SerializerAwareInterface |
26
|
|
|
{ |
27
|
|
|
private $serializer; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* {@inheritdoc} |
31
|
|
|
*/ |
32
|
|
|
public function setSerializer(SerializerInterface $serializer) |
33
|
|
|
{ |
34
|
|
|
$this->serializer = $serializer; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
|
|
public function normalize($object, $format = null, array $context = array()) |
41
|
|
|
{ |
42
|
|
|
if (!$object instanceof Activity) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$data = array( |
47
|
|
|
'id' => $this->normalizeAttribute($object->getId(), $format, $context), |
48
|
|
|
); |
49
|
|
|
|
50
|
|
|
if (null !== $definition = $object->getDefinition()) { |
51
|
|
|
$data['definition'] = $this->normalizeAttribute($definition, $format, $context); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $data; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritdoc} |
59
|
|
|
*/ |
60
|
|
|
public function supportsNormalization($data, $format = null) |
61
|
|
|
{ |
62
|
|
|
return $data instanceof Activity; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
View Code Duplication |
private function normalizeAttribute($value, $format = null, array $context = array()) |
|
|
|
|
66
|
|
|
{ |
67
|
|
|
if (!$this->serializer instanceof NormalizerInterface) { |
68
|
|
|
throw new LogicException('Cannot normalize attribute because the injected serializer is not a normalizer'); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $this->serializer->normalize($value, $format, $context); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.