ReferenceRepository::hasCollectionReference()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasDoctrineFixtures\Service\Repository;
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
9
/**
10
 * @author  Alex Patterson <[email protected]>
11
 * @package Arp\LaminasDoctrineFixtures\Service\Repository
12
 */
13
class ReferenceRepository extends \Doctrine\Common\DataFixtures\ReferenceRepository
14
{
15
    /**
16
     * @var array
17
     */
18
    private $collectionReferences = [];
19
20
    /**
21
     * @param string $name
22
     *
23
     * @return bool
24
     */
25
    public function hasCollectionReference(string $name): bool
26
    {
27
        return array_key_exists($name, $this->collectionReferences);
28
    }
29
30
    /**
31
     * @param string $name
32
     *
33
     * @return iterable
34
     */
35
    public function getCollectionReference(string $name): iterable
36
    {
37
        if (! $this->hasCollectionReference($name)) {
38
            throw new \OutOfBoundsException(sprintf('Collection reference to "%s" does not exist', $name));
39
        }
40
41
        $collection = [];
42
        foreach ($this->collectionReferences[$name] as $index => $reference) {
43
            $collection[$index] = $this->getReference($reference);
44
        }
45
46
        return $collection;
47
    }
48
49
    /**
50
     * @param string   $name
51
     * @param iterable $collection
52
     */
53
    public function setCollectionReference(string $name, iterable $collection): void
54
    {
55
        foreach ($collection as $index => $item) {
56
            $itemName = $name . '.' . $index;
57
            $this->setReference($itemName, $item);
58
            $this->collectionReferences[$name][$index] = $itemName;
59
        }
60
    }
61
62
    /**
63
     * @param string   $name
64
     * @param iterable $collection
65
     *
66
     * @throws \BadFunctionCallException
67
     */
68
    public function addCollectionReference(string $name, iterable $collection): void
69
    {
70
        if ($this->hasCollectionReference($name)) {
71
            throw new \BadMethodCallException(
72
                sprintf(
73
                    'Reference to "%s" already exists, use method setCollectionReference in order to override it',
74
                    $name
75
                )
76
            );
77
        }
78
        $this->setCollectionReference($name, $collection);
79
    }
80
}
81