1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cycle\ORM\Collection\Pivoted; |
6
|
|
|
|
7
|
|
|
use loophp\collection\Collection; |
8
|
|
|
use loophp\collection\CollectionDecorator; |
9
|
|
|
use SplObjectStorage; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Collection with associated relation context. Attention, pivot context is lost when collection is partitioned or |
13
|
|
|
* filtered. |
14
|
|
|
* |
15
|
|
|
* @psalm-template TKey of array-key |
16
|
|
|
* @psalm-template TEntity of object |
17
|
|
|
* @psalm-template TPivot of object |
18
|
|
|
* |
19
|
|
|
* @template-extends CollectionDecorator<TKey, TEntity> |
20
|
|
|
* |
21
|
|
|
* @template-implements PivotedCollectionInterface<TEntity, TPivot> |
22
|
|
|
*/ |
23
|
|
|
class LoophpPivotedCollection extends CollectionDecorator implements PivotedCollectionInterface, \Countable |
24
|
|
|
{ |
25
|
|
|
/** @var SplObjectStorage<TEntity, TPivot> */ |
26
|
|
|
protected SplObjectStorage $pivotContext; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param array<TKey, TEntity> $elements |
30
|
|
|
* @param SplObjectStorage<TEntity, TPivot>|null $pivotData |
31
|
|
|
*/ |
32
|
|
|
final public function __construct(array $elements = [], SplObjectStorage $pivotData = null) |
33
|
|
|
{ |
34
|
|
|
parent::__construct(Collection::fromIterable($elements)); |
35
|
|
|
$this->pivotContext = $pivotData ?? new SplObjectStorage(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function hasPivot(object $element): bool |
39
|
|
|
{ |
40
|
|
|
return $this->pivotContext->offsetExists($element); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function getPivot(object $element): mixed |
44
|
|
|
{ |
45
|
|
|
return $this->pivotContext[$element] ?? null; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function setPivot(object $element, mixed $pivot): void |
49
|
|
|
{ |
50
|
|
|
$this->pivotContext[$element] = $pivot; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function getPivotContext(): SplObjectStorage |
54
|
|
|
{ |
55
|
|
|
return $this->pivotContext; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function count(): int |
59
|
|
|
{ |
60
|
|
|
return \iterator_count($this->innerCollection); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public static function fromIterable(iterable $iterable): static |
64
|
|
|
{ |
65
|
|
|
return new static($iterable instanceof \Traversable ? \iterator_to_array($iterable) : $iterable); |
|
|
|
|
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param array<K, V> $elements |
70
|
|
|
* |
71
|
|
|
* @return static<K, V, TPivot> |
72
|
|
|
* |
73
|
|
|
* @template K of TKey |
74
|
|
|
* @template V of TEntity |
75
|
|
|
*/ |
76
|
|
|
protected function createFrom(array $elements): static |
77
|
|
|
{ |
78
|
|
|
$new = parent::fromIterable($elements); |
79
|
|
|
$new->pivotContext = $this->pivotContext; |
80
|
|
|
|
81
|
|
|
return $new; |
|
|
|
|
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|