JmsArrayTransformerHandler   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 45
c 0
b 0
f 0
wmc 4
lcom 1
cbo 3
ccs 14
cts 14
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A toResource() 0 9 2
A fromResource() 0 9 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Mapper\Handler;
5
6
use JMS\Serializer\ArrayTransformerInterface;
7
use JMS\Serializer\DeserializationContext;
8
use Mikemirten\Component\JsonApi\Document\ResourceObject;
9
use Mikemirten\Component\JsonApi\Mapper\MappingContext;
10
11
/**
12
 * Attributes handler
13
 *
14
 * This handler is an integration with JMS Serializer library.
15
 * It using JMS Array Transformer ability for attributes mapping.
16
 *
17
 * @see http://jmsyst.com/libs/serializer
18
 * @see https://github.com/schmittjoh/serializer
19
 *
20
 * @package Mikemirten\Component\JsonApi\ObjectTransformer\Handler
21
 */
22
class JmsArrayTransformerHandler implements HandlerInterface
23
{
24
    /**
25
     * JMS Array Transformer
26
     *
27
     * @var ArrayTransformerInterface
28
     */
29
    protected $transformer;
30
31
    /**
32
     * JmsArrayTransformerHandler constructor.
33
     *
34
     * @param ArrayTransformerInterface $arrayTransformer
35
     */
36 2
    public function __construct(ArrayTransformerInterface $arrayTransformer)
37
    {
38 2
        $this->transformer = $arrayTransformer;
39 2
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 1
    public function toResource($object, ResourceObject $resource, MappingContext $context)
45
    {
46 1
        $data = $this->transformer->toArray($object);
47
48 1
        foreach ($data as $name => $value)
49
        {
50 1
            $resource->setAttribute($name, $value);
51
        }
52 1
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 1
    public function fromResource($object, ResourceObject $resource, MappingContext $context)
58
    {
59 1
        $data = $resource->getAttributes();
60
61 1
        $deserializationContext = new DeserializationContext();
62 1
        $deserializationContext->setAttribute('target', $object);
63
64 1
        $this->transformer->fromArray($data, get_class($object), $deserializationContext);
65
    }
66
}