Skip to content

Commit 989dcbd

Browse files
authored
[Feat] Add Support Clone Collection (#156)
* feat: add support clone collection * refactor: collection clone use native clone - move test case to realete class test
1 parent 006127a commit 989dcbd

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

src/System/Collection/AbstractCollectionImmutable.php

+30
Original file line numberDiff line numberDiff line change
@@ -328,4 +328,34 @@ public function getIterator(): \Traversable
328328
{
329329
return new \ArrayIterator($this->all());
330330
}
331+
332+
public function __clone()
333+
{
334+
$this->collection = $this->deepClone($this->collection);
335+
}
336+
337+
/**
338+
* @param array<TKey, TValue> $collection
339+
*
340+
* @return array<TKey, TValue>
341+
*/
342+
protected function deepClone($collection)
343+
{
344+
$clone = [];
345+
foreach ($collection as $key => $value) {
346+
if (is_array($value)) {
347+
$clone[$key] = $this->deepClone($value);
348+
continue;
349+
}
350+
351+
if (is_object($value)) {
352+
$clone[$key] = clone $value;
353+
continue;
354+
}
355+
356+
$clone[$key] = $value;
357+
}
358+
359+
return $clone;
360+
}
331361
}

src/System/Collection/Collection.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ public function sortKeyDesc(): self
243243
*/
244244
public function clone(): Collection
245245
{
246-
return new Collection($this->collection);
246+
return clone $this;
247247
}
248248

249249
/**

tests/Collection/CollectionTest.php

+21
Original file line numberDiff line numberDiff line change
@@ -355,4 +355,25 @@ public function itCanByShuffle()
355355
$this->assertArrayHasKey($key, $coll);
356356
}
357357
}
358+
359+
/** @test */
360+
public function itCanCloneColection()
361+
{
362+
$ori = new Collection([
363+
'one' => 'one',
364+
'two' => [
365+
'one',
366+
'two' => [1, 2],
367+
],
368+
'three' => new Collection([]),
369+
]);
370+
371+
$clone = clone $ori;
372+
373+
$ori->set('one', 'uno');
374+
$this->assertEquals('one', $clone->get('one'));
375+
376+
$clone->set('one', 1);
377+
$this->assertEquals('uno', $ori->get('one'));
378+
}
358379
}

0 commit comments

Comments
 (0)