Skip to content

Commit bceb79a

Browse files
committed
feat(collection): return existing collection instance when already resolved
1 parent b31954b commit bceb79a

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

src/Core/Serialize/Resolver/CollectionValue.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ public function resolve(ReflectionParameter $parameter, Set $set): Value
3737
*/
3838
private function resolveCollection(string $collectionName, mixed $value): Value
3939
{
40+
if ($value instanceof $collectionName) {
41+
return new Value($value);
42+
}
43+
4044
$reflection = new ReflectionClass($collectionName);
4145
$type = $this->detectCollectionType($reflection);
4246

@@ -45,6 +49,15 @@ private function resolveCollection(string $collectionName, mixed $value): Value
4549
if ($type === null || ! is_array($value)) {
4650
return new Value($collection);
4751
}
52+
return $this->populateCollection($collection, $type, $value);
53+
}
54+
55+
/**
56+
* @param class-string $type
57+
* @param array<mixed> $value
58+
*/
59+
private function populateCollection(Collectable $collection, string $type, array $value): Value
60+
{
4861
foreach ($value as $datum) {
4962
$datum = arrayify($datum);
5063
$set = Set::createFrom($datum);

tests/Core/Serialize/Resolver/CollectionValueTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,32 @@ public function testShouldResolveCollectionWithArrayData(): void
9494
$this->assertInstanceOf(FeatureCollection::class, $result->content);
9595
$this->assertCount(2, $result->content);
9696
}
97+
98+
public function testShouldReturnSameCollectionWhenValueIsAlreadyCollectionInstance(): void
99+
{
100+
// Arrange
101+
$type = $this->createMock(ReflectionNamedType::class);
102+
$type->expects($this->once())
103+
->method('getName')
104+
->willReturn(FeatureCollection::class);
105+
$parameter = $this->createMock(ReflectionParameter::class);
106+
$parameter->expects($this->once())
107+
->method('getType')
108+
->willReturn($type);
109+
$parameter->expects($this->once())
110+
->method('getName')
111+
->willReturn('features');
112+
113+
$existingCollection = new FeatureCollection();
114+
$set = Set::createFrom([
115+
'features' => $existingCollection,
116+
]);
117+
$collectionValue = new CollectionValue();
118+
119+
// Act
120+
$result = $collectionValue->resolve($parameter, $set);
121+
122+
// Assert
123+
$this->assertSame($existingCollection, $result->content);
124+
}
97125
}

0 commit comments

Comments
 (0)