Completed
Push — master ( 513b92...79c3ce )
by Richard van
15s queued 11s
created

Collection::__call()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.5923

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 6
cts 9
cp 0.6667
rs 9.6666
c 0
b 0
f 0
cc 4
nc 3
nop 2
crap 4.5923
1
<?php
2
3
namespace Jkphl\Micrometa\Ports\Item;
4
5
use Jkphl\Micrometa\Ports\Exceptions\InvalidArgumentException;
6
use Jkphl\Micrometa\Ports\Exceptions\OutOfBoundsException;
7
8
/**
9
 * Abstract getter functionality that is applicable for implementations of ItemCollectionFacade.
10
 *
11
 * The implementation remains responsible for implementing the collection methods itself.
12
 *
13
 * Thereby is usable by both the Item for it's properties, as for an ItemList with it's items.
14
 *
15
 * @package    Jkphl\Micrometa
16
 * @subpackage Jkphl\Micrometa\Ports
17
 */
18
abstract class Collection implements CollectionFacade
19
{
20
    /**
21
     * Generic item getter
22
     *
23
     * @param string $type     Item type
24
     * @param array $arguments Arguments
25
     *
26
     * @return ItemInterface Item
27
     * @throws InvalidArgumentException If the item index is invalid
28
     * @api
29
     */
30 3
    public function __call($type, $arguments)
31
    {
32 3
        $index = 0;
33 3
        if (count($arguments)) {
34
            // If the item index is invalid
35 2
            if (!is_int($arguments[0]) || ($arguments[0] < 0)) {
36
                throw new InvalidArgumentException(
37
                    sprintf(InvalidArgumentException::INVALID_ITEM_INDEX_STR, $arguments[0]),
38
                    InvalidArgumentException::INVALID_ITEM_INDEX
39
                );
40
            }
41
42 2
            $index = $arguments[0];
43
        }
44
45
        // Return the item by type and index
46 3
        return $this->getItemByTypeAndIndex($type, $index);
47
    }
48
49
    /**
50
     * Return an item by type and index
51
     *
52
     * @param string $type Item type
53
     * @param int $index   Item index
54
     *
55
     * @return ItemInterface Item
56
     * @throws OutOfBoundsException If the item index is out of bounds
57
     */
58 3
    private function getItemByTypeAndIndex($type, $index)
59
    {
60 3
        $typeItems = $this->getItems($type);
61
62
        // If the item index is out of bounds
63 3
        if (count($typeItems) <= $index) {
64 2
            throw new OutOfBoundsException(
65 2
                sprintf(OutOfBoundsException::INVALID_ITEM_INDEX_STR, $index),
66 2
                OutOfBoundsException::INVALID_ITEM_INDEX
67
            );
68
        }
69
70 2
        return $typeItems[$index];
71
    }
72
}
73