gamez/typed-collection

Type-safe collections based on Laravel Collections

2.2.1 2019-12-19 16:08 UTC

This package is auto-updated.

Last update: 2020-01-19 16:15:59 UTC


README

Latest Stable Version Total Downloads Build Status

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.