Passed
Push — master ( 1150b8...9cbbc5 )
by Michael
02:35
created

JsonApiExtension::hydrate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0932

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 5
cts 7
cp 0.7143
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 3
crap 2.0932
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Hydrator\Extension;
5
6
use Mikemirten\Component\JsonApi\Document\AbstractDocument;
7
use Mikemirten\Component\JsonApi\Document\JsonApiObject;
8
use Mikemirten\Component\JsonApi\Exception\InvalidDocumentException;
9
use Mikemirten\Component\JsonApi\Hydrator\DocumentHydrator;
10
11
/**
12
 * "jsonapi" object extension
13
 *
14
 * @see http://jsonapi.org/format/#document-jsonapi-object
15
 *
16
 * @package Mikemirten\Component\JsonApi\Hydrator\SectionHandler
17
 */
18
class JsonApiExtension implements ExtensionInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23 1
    public function hydrate($object, $source, DocumentHydrator $hydrator)
24
    {
25 1
        if (! $object instanceof AbstractDocument) {
26
            throw new InvalidDocumentException(sprintf(
27
                'Only top-level of document can contains "jsonapi"-object. Instance of "%s" given.',
28
                get_class($object)
29
            ));
30
        }
31
32 1
        $jsonApi = $this->createJsonApi($source, $hydrator);
33
34 1
        $object->setJsonApi($jsonApi);
35 1
    }
36
37
    /**
38
     * Create JsonAPI-object
39
     *
40
     * @param  $source
41
     * @param  DocumentHydrator $hydrator
42
     * @return JsonApiObject
43
     */
44 1
    protected function createJsonApi($source, DocumentHydrator $hydrator): JsonApiObject
45
    {
46 1
        $jsonApi = isset($source->version)
47 1
            ? new JsonApiObject($source->version)
48 1
            : new JsonApiObject();
49
50 1
        $hydrator->hydrateObject($jsonApi, $source);
51
52 1
        return $jsonApi;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 1
    public function supports(): array
59
    {
60 1
        return ['jsonapi'];
61
    }
62
}