Passed
Push — master ( 64594b...98afe9 )
by Michael
04:03
created

AbstractObjectMapper::fromArray()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Mapper;
5
6
use Mikemirten\Component\JsonApi\Document\ResourceObject;
7
use Mikemirten\Component\JsonApi\Mapper\IdentifierHandler\IdentifierHandlerInterface;
8
use Mikemirten\Component\JsonApi\Mapper\TypeHandler\TypeHandlerInterface;
9
10
/**
11
 * Abstract mapper
12
 * Contains implementation of ID and type handling, expects data mapping from extension
13
 *
14
 * @package Mikemirten\Component\JsonApi\ObjectTransformer
15
 */
16
abstract class AbstractObjectMapper implements ObjectMapperInterface
17
{
18
    /**
19
     * Identifier of resource handler
20
     *
21
     * @var IdentifierHandlerInterface
22
     */
23
    protected $identifierHandler;
24
25
    /**
26
     * Type of resource handler
27
     *
28
     * @var TypeHandlerInterface
29
     */
30
    protected $typeHandler;
31
32
    /**
33
     * AbstractObjectMapper constructor.
34
     *
35
     * @param IdentifierHandlerInterface $identifierHandler
36
     * @param TypeHandlerInterface       $typeHandler
37
     */
38 2
    public function __construct(IdentifierHandlerInterface $identifierHandler, TypeHandlerInterface $typeHandler)
39
    {
40 2
        $this->identifierHandler = $identifierHandler;
41 2
        $this->typeHandler       = $typeHandler;
42 2
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 1
    final public function toResource($object): ResourceObject
48
    {
49 1
        $id   = $this->identifierHandler->getIdentifier($object);
50 1
        $type = $this->typeHandler->getType($object);
51
52 1
        $attributes = $this->toArray($object);
53
54 1
        return new ResourceObject($id, $type, $attributes);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 1
    final public function fromResource($object, ResourceObject $resource)
61
    {
62 1
        $this->identifierHandler->setIdentifier($object, $resource->getId());
63
64 1
        $this->fromArray($object, $resource->getAttributes());
65 1
    }
66
67
    /**
68
     * Map properties of object to an array
69
     * [name => value]
70
     *
71
     * @param  mixed $object
72
     * @return array
73
     */
74
    abstract protected function toArray($object): array;
75
76
    /**
77
     * Map an array of data to object
78
     * [name => value]
79
     *
80
     * @param  mixed $object
81
     * @param  array $data
82
     */
83
    abstract protected function fromArray($object, array $data);
84
}