ResourceCollectionDocument   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 88
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 88
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A addResource() 0 4 1
A getFirstResource() 0 4 1
A getResources() 0 4 1
A getIterator() 0 4 1
A toArray() 0 15 2
A __toString() 0 4 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Document;
5
6
/**
7
 * Resource Collection Document
8
 *
9
 * @see http://jsonapi.org/format/#document-structure
10
 *
11
 * @package Mikemirten\Component\JsonApi\Document
12
 */
13
class ResourceCollectionDocument extends AbstractDocument implements \IteratorAggregate
14
{
15
    /**
16
     * Resources
17
     *
18
     * @var ResourceObject[]
19
     */
20
    protected $resources = [];
21
22
    /**
23
     * ResourceCollectionDocument constructor.
24
     *
25
     * @param array $metadata
26
     */
27 20
    public function __construct(array $metadata = [])
28
    {
29 20
        $this->metadata = $metadata;
30 20
    }
31
32
    /**
33
     * Add resource
34
     *
35
     * @param ResourceObject $resource
36
     */
37 4
    public function addResource(ResourceObject $resource)
38
    {
39 4
        $this->resources[] = $resource;
40 4
    }
41
42
    /**
43
     * Get first resource from collection
44
     *
45
     * @return ResourceObject
46
     */
47 1
    public function getFirstResource(): ResourceObject
48
    {
49 1
        return reset($this->resources);
50
    }
51
52
    /**
53
     * Get all resources
54
     *
55
     * @return ResourceObject[]
56
     */
57 9
    public function getResources(): array
58
    {
59 9
        return $this->resources;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 1
    public function getIterator(): \Traversable
66
    {
67 1
        return new \ArrayIterator($this->getResources());
68
    }
69
70
    /**
71
     * Cast to an array
72
     *
73
     * @return array
74
     */
75 6
    public function toArray(): array
76
    {
77 6
        $resources = [];
78
79 6
        foreach ($this->getResources() as $resource)
80
        {
81 1
            $resources[] = $resource->toArray();
82
        }
83
84 6
        $data = parent::toArray();
85
86 6
        $data['data'] = $resources;
87
88 6
        return $data;
89
    }
90
91
    /**
92
     * Cast to a string
93
     *
94
     * @return string
95
     */
96 3
    public function __toString(): string
97
    {
98 3
        return 'Document with collection of resources';
99
    }
100
}