Passed
Push — master ( 7e6483...d784e3 )
by Michael
02:46
created

ResourceObject::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
crap 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Document;
5
6
use Mikemirten\Component\JsonApi\Document\Behaviour\AttributesContainer;
7
use Mikemirten\Component\JsonApi\Document\Behaviour\LinksAwareInterface;
8
use Mikemirten\Component\JsonApi\Document\Behaviour\LinksContainer;
9
use Mikemirten\Component\JsonApi\Document\Behaviour\MetadataAwareInterface;
10
use Mikemirten\Component\JsonApi\Document\Behaviour\MetadataContainer;
11
use Mikemirten\Component\JsonApi\Document\Behaviour\RelationshipsAwareInterface;
12
use Mikemirten\Component\JsonApi\Document\Behaviour\RelationshipsContainer;
13
use Mikemirten\Component\JsonApi\Document\Behaviour\ResourceBehaviour;
14
15
/**
16
 * Resource Object
17
 *
18
 * @see http://jsonapi.org/format/#document-resource-objects
19
 *
20
 * @package Mikemirten\Component\JsonApi\Document
21
 */
22
class ResourceObject implements MetadataAwareInterface, LinksAwareInterface, RelationshipsAwareInterface
23
{
24
    use ResourceBehaviour;
25
    use AttributesContainer;
26
    use MetadataContainer;
27
    use LinksContainer;
28
    use RelationshipsContainer;
29
30
    /**
31
     * ResourceObject constructor.
32
     *
33
     * @param string $id
34
     * @param string $type
35
     * @param array  $attributes
36
     * @param array  $metadata
37
     */
38 17
    public function __construct(string $id, string $type, array $attributes = [], array $metadata = [])
39
    {
40 17
        $this->id         = $id;
41 17
        $this->type       = $type;
42 17
        $this->attributes = $attributes;
43 17
        $this->metadata   = $metadata;
44 17
    }
45
46
    /**
47
     * Cast to an array
48
     *
49
     * @return array
50
     */
51 5
    public function toArray(): array
52
    {
53
        $data = [
54 5
            'meta'          => $this->getMetadata(),
55 5
            'links'         => $this->linksToArray(),
56 5
            'attributes'    => $this->getAttributes(),
57 5
            'relationships' => $this->relationshipsToArray()
58
        ];
59
60 5
        return array_merge(
61 5
            $this->resourceToArray(),
62 5
            array_filter($data, 'count')
63
        );
64
    }
65
66
    /**
67
     * Cast to a string
68
     *
69
     * @return string
70
     */
71 3
    public function __toString(): string
72
    {
73 3
        return sprintf(
74 3
            'Resource-object of type "%s" identified by "%s"',
75 3
            $this->type,
76 3
            $this->id
77
        );
78
    }
79
}