ReferenceRepository::setCollectionReference()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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