Commit 989dcbd 1 parent 006127a commit 989dcbd Copy full SHA for 989dcbd
File tree 3 files changed +52
-1
lines changed
3 files changed +52
-1
lines changed Original file line number Diff line number Diff line change @@ -328,4 +328,34 @@ public function getIterator(): \Traversable
328
328
{
329
329
return new \ArrayIterator ($ this ->all ());
330
330
}
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
+ }
331
361
}
Original file line number Diff line number Diff line change @@ -243,7 +243,7 @@ public function sortKeyDesc(): self
243
243
*/
244
244
public function clone (): Collection
245
245
{
246
- return new Collection ( $ this -> collection ) ;
246
+ return clone $ this ;
247
247
}
248
248
249
249
/**
Original file line number Diff line number Diff line change @@ -355,4 +355,25 @@ public function itCanByShuffle()
355
355
$ this ->assertArrayHasKey ($ key , $ coll );
356
356
}
357
357
}
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
+ }
358
379
}
You can’t perform that action at this time.
0 commit comments