Passed
Push — master ( c1150e...84b7ab )
by Michael
02:30
created

ResourceCollectionDocument::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
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
    public function __construct(array $metadata = [])
28
    {
29
        $this->metadata = $metadata;
30
    }
31
32
    /**
33
     * Add resource
34
     *
35
     * @param ResourceObject $resource
36
     */
37
    public function addResource(ResourceObject $resource)
38
    {
39
        $this->resources[] = $resource;
40
    }
41
42
    /**
43
     * Get first resource from collection
44
     *
45
     * @return ResourceObject
46
     */
47
    public function getFirstResource(): ResourceObject
48
    {
49
        return reset($this->resources);
50
    }
51
52
    /**
53
     * Get all resources
54
     *
55
     * @return ResourceObject[]
56
     */
57
    public function getResources(): array
58
    {
59
        return $this->resources;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function getIterator(): \Traversable
66
    {
67
        return new \ArrayIterator($this->getResources());
68
    }
69
70
    /**
71
     * Cast to an array
72
     *
73
     * @return array
74
     */
75
    public function toArray(): array
76
    {
77
        $resources = [];
78
79
        foreach ($this->getResources() as $resource)
80
        {
81
            $resources[] = $resource->toArray();
82
        }
83
84
        $data = parent::toArray();
85
86
        $data['data'] = $resources;
87
88
        return $data;
89
    }
90
}