Added getOrPut and getOrSet into Hyperf\Collection\Collection. (#6784)

Co-authored-by: 李铭昕 <715557344@qq.com>
This commit is contained in:
Deeka Wong 2024-05-23 13:47:31 +08:00 committed by GitHub
parent 12489fd143
commit 7439be84dc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 64 additions and 0 deletions

View File

@ -8,6 +8,7 @@
- [#6774](https://github.com/hyperf/hyperf/pull/6774) Support Lateral Join for `Hyperf\Database\Query\Builder`
- [#6781](https://github.com/hyperf/hyperf/pull/6781) Added some methods to `Hyperf\Collection\Arr`.
- [#6783](https://github.com/hyperf/hyperf/pull/6783) Support `insertOrIgnoreUsing` for `Hyperf\Database\Query\Builder`.
- [#6784](https://github.com/hyperf/hyperf/pull/6784) Added `getOrPut` and `getOrSet` into `Hyperf\Collection\Collection`.
## Optimized

View File

@ -423,6 +423,38 @@ class Collection implements Enumerable, ArrayAccess
return value($default);
}
/**
* Get an item from the collection by key or add it to collection if it does not exist.
*
* @template TGetOrPutValue
*
* @param (Closure(): TGetOrPutValue)|TGetOrPutValue $value
* @return TGetOrPutValue|TValue
*/
public function getOrPut(int|string $key, mixed $value): mixed
{
if (array_key_exists($key, $this->items)) {
return $this->items[$key];
}
$this->offsetSet($key, $value = value($value));
return $value;
}
/**
* Get an item from the collection by key or add it to collection if it does not exist.
*
* @template TGetOrPutValue
*
* @param (Closure(): TGetOrPutValue)|TGetOrPutValue $value
* @return TGetOrPutValue|TValue
*/
public function getOrSet(int|string $key, mixed $value): mixed
{
return $this->getOrPut($key, $value);
}
/**
* Group an associative array by a field or using a callback.
* @param mixed $groupBy

View File

@ -948,4 +948,35 @@ class CollectionTest extends TestCase
$duplicates = $collection::make([new $collection(['laravel']), $expected, $expected, [], '2', '2'])->duplicatesStrict()->all();
$this->assertSame([2 => $expected, 5 => '2'], $duplicates);
}
public function testGetOrPut()
{
$data = new Collection(['name' => 'taylor', 'email' => 'foo']);
$this->assertSame('taylor', $data->getOrPut('name', null));
$this->assertSame('foo', $data->getOrPut('email', null));
$this->assertSame('male', $data->getOrPut('gender', 'male'));
$this->assertSame('taylor', $data->get('name'));
$this->assertSame('foo', $data->get('email'));
$this->assertSame('male', $data->get('gender'));
$data = new Collection(['name' => 'taylor', 'email' => 'foo']);
$this->assertSame('taylor', $data->getOrPut('name', function () {
return null;
}));
$this->assertSame('foo', $data->getOrPut('email', function () {
return null;
}));
$this->assertSame('male', $data->getOrPut('gender', function () {
return 'male';
}));
$this->assertSame('taylor', $data->get('name'));
$this->assertSame('foo', $data->get('email'));
$this->assertSame('male', $data->get('gender'));
}
}