gamez/typed-collection

Type-safe collections based on Laravel Collections

4.0.0 2020-12-10 12:50 UTC

This package is auto-updated.

Last update: 2021-07-10 14:11:12 UTC


README

Latest Stable Version Total Downloads Build Status Sponsor

Installation

The package can be installed with Composer:

$ composer require gamez/typed-collection

Usage

class Person
{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }
}

$taylor = new Person('Taylor');
$jeffrey = new Person('Jeffrey');

Typed Collections

use Gamez\Illuminate\Support\TypedCollection;

class People extends TypedCollection
{
    protected static $allowedTypes = [Person::class];
}

$people = People::make([$taylor, $jeffrey])
    ->each(function (Person $person) {
        printf("This is %s.\n", $person->name);
    });
/* Output:
This is Taylor.
This is Jeffrey.
*/

try {
    People::make('Not a person');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage().PHP_EOL;
}
/* Output:
Output: A People collection only accepts objects of the following type(s): Person.
*/

Lazy Typed Collections

use Gamez\Illuminate\Support\LazyTypedCollection;

class LazyPeople extends LazyTypedCollection
{
    protected static $allowedTypes = [Person::class];
}

$lazyPeople = LazyPeople::make([$taylor, $jeffrey])
    ->each(function (Person $person) {
        printf("This is %s.\n", $person->name);
    });
/* Output:
This is Lazy Taylor.
This is Lazy Jeffrey.
*/

try {
    LazyPeople::make('Nope!');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage().PHP_EOL;
}
/* Output:
Output: A People collection only accepts objects of the following type(s): Person.
*/

For further information on how to use Laravel Collections, have a look at the official documentation.