Skip to content

Commit 80e7b00

Browse files
committed
Collection improvements
1 parent d68ce14 commit 80e7b00

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

src/Support/Collection.php

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
namespace BinaryCube\ElasticTool\Support;
66

77
use Countable;
8+
use ArrayAccess;
89
use Traversable;
910
use ArrayIterator;
1011
use IteratorAggregate;
1112

1213
/**
1314
* Class Collection
1415
*/
15-
class Collection implements Countable, IteratorAggregate
16+
class Collection implements ArrayAccess, Countable, IteratorAggregate
1617
{
1718

1819
/**
@@ -53,7 +54,7 @@ protected function getArrayableItems($items)
5354

5455
if (\is_array($items)) {
5556
return $items;
56-
} elseif ($items instanceof self) {
57+
} elseif ($items instanceof Collection) {
5758
$arr = $items->all();
5859
} elseif ($items instanceof Traversable) {
5960
$arr = \iterator_to_array($items);
@@ -95,8 +96,10 @@ public function values()
9596
*/
9697
public function add($values): self
9798
{
98-
foreach ($values as $value) {
99-
$this->offsetSet(null, $value);
99+
$assoc = self::isAssociative($this->items);
100+
101+
foreach ($values as $key => $value) {
102+
$this->offsetSet($assoc ? $key : null, $value);
100103
}
101104

102105
return $this;
@@ -322,6 +325,45 @@ public function getIterator(): ArrayIterator
322325
return new ArrayIterator($this->all());
323326
}
324327

328+
/**
329+
* Returns a value indicating whether the given array is an associative array.
330+
*
331+
* An array is associative if all its keys are strings. If `$allStrings` is false,
332+
* then an array will be treated as associative if at least one of its keys is a string.
333+
*
334+
* Note that an empty array will NOT be considered associative.
335+
*
336+
* @param array $array the array being checked
337+
* @param bool $allStrings whether the array keys must be all strings in order for
338+
* the array to be treated as associative.
339+
*
340+
* @return bool whether the array is associative
341+
*/
342+
protected static function isAssociative(array $array, bool $allStrings = true)
343+
{
344+
if (! \is_array($array) || empty($array)) {
345+
return false;
346+
}
347+
348+
if ($allStrings) {
349+
foreach ($array as $key => $value) {
350+
if (! \is_string($key)) {
351+
return false;
352+
}
353+
}
354+
355+
return true;
356+
}
357+
358+
foreach ($array as $key => $value) {
359+
if (\is_string($key)) {
360+
return true;
361+
}
362+
}
363+
364+
return false;
365+
}
366+
325367
/**
326368
* @param array $a
327369
* @param array $b

0 commit comments

Comments
 (0)