aeiiq/collection

一个提供PHP严格类型集合的库。

v4.0.2 2024-02-20 12:16 UTC

README

原因

为了提供一个简单的方式确保集合/数组上的类型安全,并提供对对象集合有用的自定义方法,如下面的示例所示。

安装

composer require aeviiq/collection

声明

/**
 * @extends ObjectCollection<int, Foo>
 *
 * @method \ArrayIterator|Foo[] getIterator()
 * @method Foo|null first()
 * @method Foo|null last()
 */
final class FooCollection extends ObjectCollection
{
    public function filterReleasedBefore(\DateTimeInterface $dateTime): FooCollection
    {
        return $this->filter(static function (Foo $foo) use ($dateTime): bool {
            return $foo->getReleaseDate() < $dateTime;
        });
    }

    public function filterActives(): FooCollection
    {
        return $this->filter(static function (Foo $foo): bool {
            return $foo->isActive();
        });
    }
    
    protected function allowedInstance(): string
    {
        return Foo::class;
    }
}

使用

// Useful custom methods for ObjectCollections:
$fooCollection = new FooCollection([$foo1, $foo2]);
$result = $fooCollection->filterReleasedBefore(new DateTime('now'))->filterActives();

// Basic type collections that are provided
$intCollection = new IntCollection([1, 2]);
$intCollection->append(3);

$intCollection = new IntCollection([1, '2']); // InvalidArgumentException thrown
$intCollection->append('3');  // InvalidArgumentException thrown