|
5 | 5 | namespace BinaryCube\ElasticTool\Support; |
6 | 6 |
|
7 | 7 | use Countable; |
| 8 | +use ArrayAccess; |
8 | 9 | use Traversable; |
9 | 10 | use ArrayIterator; |
10 | 11 | use IteratorAggregate; |
11 | 12 |
|
12 | 13 | /** |
13 | 14 | * Class Collection |
14 | 15 | */ |
15 | | -class Collection implements Countable, IteratorAggregate |
| 16 | +class Collection implements ArrayAccess, Countable, IteratorAggregate |
16 | 17 | { |
17 | 18 |
|
18 | 19 | /** |
@@ -53,7 +54,7 @@ protected function getArrayableItems($items) |
53 | 54 |
|
54 | 55 | if (\is_array($items)) { |
55 | 56 | return $items; |
56 | | - } elseif ($items instanceof self) { |
| 57 | + } elseif ($items instanceof Collection) { |
57 | 58 | $arr = $items->all(); |
58 | 59 | } elseif ($items instanceof Traversable) { |
59 | 60 | $arr = \iterator_to_array($items); |
@@ -95,8 +96,10 @@ public function values() |
95 | 96 | */ |
96 | 97 | public function add($values): self |
97 | 98 | { |
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); |
100 | 103 | } |
101 | 104 |
|
102 | 105 | return $this; |
@@ -322,6 +325,45 @@ public function getIterator(): ArrayIterator |
322 | 325 | return new ArrayIterator($this->all()); |
323 | 326 | } |
324 | 327 |
|
| 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 | + |
325 | 367 | /** |
326 | 368 | * @param array $a |
327 | 369 | * @param array $b |
|
0 commit comments