Passed
Push — master ( 98afe9...62e274 )
by Michael
02:28
created

JmsArrayTransformerHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 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
10
/**
11
 * Attributes handler
12
 *
13
 * This handler is an integration with JMS Serializer library.
14
 * It using JMS Array Transformer ability for attributes mapping.
15
 *
16
 * @see http://jmsyst.com/libs/serializer
17
 * @see https://github.com/schmittjoh/serializer
18
 *
19
 * @package Mikemirten\Component\JsonApi\ObjectTransformer\Handler
20
 */
21
class JmsArrayTransformerHandler implements HandlerInterface
22
{
23
    /**
24
     * JMS Array Transformer
25
     *
26
     * @var ArrayTransformerInterface
27
     */
28
    protected $transformer;
29
30
    /**
31
     * JmsArrayTransformerHandler constructor.
32
     *
33
     * @param ArrayTransformerInterface $arrayTransformer
34
     */
35 2
    public function __construct(ArrayTransformerInterface $arrayTransformer)
36
    {
37 2
        $this->transformer = $arrayTransformer;
38 2
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 1
    public function toResource($object, ResourceObject $resource)
44
    {
45 1
        $data = $this->transformer->toArray($object);
46
47 1
        foreach ($data as $name => $value)
48
        {
49 1
            $resource->setAttribute($name, $value);
50
        }
51 1
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 1
    public function fromResource($object, ResourceObject $resource)
57
    {
58 1
        $data = $resource->getAttributes();
59
60 1
        $context = new DeserializationContext();
61 1
        $context->setAttribute('target', $object);
62
63 1
        $this->transformer->fromArray($data, get_class($object), $context);
64
    }
65
}