palmtree/

collection

不可变集合,提供数组中缺失的常用功能

v6.1.1 2023-11-15 14:38 UTC

README

License Build Packagist Version

不可变集合,提供数组中缺失的常用功能。

需求

  • PHP >= 8.1

安装

使用composer将包添加到依赖项

composer require palmtree/collection

用法

大部分情况下,集合可以像数组一样使用。它们实现了ArrayAccessTraversableCountable

use function Palmtree\Collection\c;

$collection = c(['foo' => 'bar', 'baz' => 'qux']);

$foo = $collection['foo'];
$collection['baz2'] = 'qux';

isset($collection['baz']); // true
unset($collection['baz']);
count($collection);

foreach ($collection as $key => $value) {
    // do stuff with value and/or key
}

// find returns the first matching element
$foo = $collection->find(fn ($v) => $v === 'bar');

// filter returns a new filtered collection
$quxCollection = $collection->filter(fn ($v) => $v === 'qux');
use function Palmtree\Collection\c;

$collection = c([1, 9, 5, 3, 7, 10])
    ->sort()
    ->filter(fn ($i) $i < 10)
    ->values()

// returns true as every element remaining in the collection is odd
$isAllOdd = $collection->every(fn ($i) => $i % 2 !== 0);
// returns false as it was removed in our filter
$collection->contains(10);

// returns true as at least one of the elements is false
c([true, true, false, true, true])->some(fn ($v) => !$v);

提供了许多其他方法。阅读文档中的源代码以了解更多。

泛型

库支持模板注解,以便静态分析器(如Psalm和PHPStan)使用

/** @var Collection<int, Foo> **/
$collection = new Collection();
$collection->add(new Foo());

foreach ($collection as $foo) {
    // Psalm/PHPStan and PhpStorm know that $foo is an instance of Foo here
}

许可证

MIT许可证下发布