Skip to content
This repository has been archived by the owner on Aug 13, 2023. It is now read-only.

🌴 Immutable collections which provide commonly used functionality missing from arrays

License

Notifications You must be signed in to change notification settings

palmtreephp/easy-collection

Repository files navigation

WARNING: THIS REPO IS ABANDONDED. THE LIBRARY IS BEING MAINTAINED UNDER A NEW NAME AND A NEW HOME

🌴 Easy Collection

License Build

Immutable collections which provide commonly used functionality missing from arrays.

Requirements

  • PHP >= 8.1

Installation

Use composer to add the package to your dependencies:

composer require palmtree/easy-collection

Usage

Collections can be used just like arrays for the most part. They implement ArrayAccess, Traversable and Countable:

use function Palmtree\EasyCollection\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\EasyCollection\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);

Many other methods are provided. Read through the documented source code to see more.

Generics

The library supports template annotations for use by static analysers such as Psalm and 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
}

License

Released under the MIT license

About

🌴 Immutable collections which provide commonly used functionality missing from arrays

Resources

License

Stars

Watchers

Forks

Languages