Passed
Push — master ( dc473e...3aff2b )
by Michael
02:45
created

ErrorsExtension::hydrate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
c 0
b 0
f 0
ccs 9
cts 9
cp 1
rs 9.4285
cc 3
eloc 9
nc 3
nop 3
crap 3
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Hydrator\Extension;
5
6
use Mikemirten\Component\JsonApi\Document\Behaviour\ErrorsAwareInterface;
7
use Mikemirten\Component\JsonApi\Document\ErrorObject;
8
use Mikemirten\Component\JsonApi\Exception\InvalidDocumentException;
9
use Mikemirten\Component\JsonApi\Hydrator\DocumentHydrator;
10
11
/**
12
 * "errors" object extension
13
 *
14
 * @see http://jsonapi.org/format/#errors
15
 *
16
 * @package Mikemirten\Component\JsonApi\Hydrator\SectionHandler
17
 */
18
class ErrorsExtension implements ExtensionInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23 2
    public function hydrate($object, $source, DocumentHydrator $hydrator)
24
    {
25 2
        if (! $object instanceof ErrorsAwareInterface) {
26 1
            throw new InvalidDocumentException(sprintf(
27 1
                'Given instance of "%s" does not implements "%s"',
28
                get_class($object),
29 1
                ErrorsAwareInterface::class
30
            ));
31
        }
32
33 1
        foreach ($source as $content)
34
        {
35 1
            $error = $this->createError($content, $hydrator);
36
37 1
            $object->addError($error);
38
        }
39 1
    }
40
41
    /**
42
     * Create error
43
     *
44
     * @param  $source
45
     * @param  DocumentHydrator $hydrator
46
     * @return ErrorObject
47
     */
48 1
    protected function createError($source, DocumentHydrator $hydrator): ErrorObject
49
    {
50 1
        $error = new ErrorObject();
51
52 1
        foreach (['id', 'status', 'code', 'title', 'detail'] as $property)
53
        {
54 1
            if (isset($source->$property)) {
55 1
                $error->{'set' . ucfirst($property)}($source->$property);
56
            }
57
        }
58
59 1
        $hydrator->hydrateObject($error, $source);
60
61 1
        return $error;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 1
    public function supports(): array
68
    {
69 1
        return ['errors'];
70
    }
71
}