kartavik/generic-collection-php

This package is abandoned and no longer maintained. The author suggests using the kartavik/typed-collection package instead.

Implementation of typed collection

v2.0.0RC1 2018-11-08 09:44 UTC

This package is auto-updated.

Last update: 2022-02-01 13:14:02 UTC


README

Latest Stable Version Latest Unstable Version Total Downloads License

Scrutinizer Code Quality Build Status codecov

Strongly typed generic collection implementation

Installation

Use composer to install:

composer require kartavik/typed-collection

Usage

Dynamic

  • internal types
<?php

use kartavik\Support\Collection;
use kartavik\Support\Strict;

$items = [1, 2, 3, 4,];
$collection = new Collection(Strict::integer(), $items); // Return instance of typed collection
$collection = Collection::{'integer'}($items); // Work same as constructor

// Another examples

// string
Collection::{Strict::STRING}(['str1', 'str2']);

// float
Collection::{Strict::FLOAT}([12.3, 23.5, 3., 54.321,]);

// array
Collection::{Strict::ARRAYABLE}([[1, 2], ['str1'], [123.456]]);

// boolean
Collection::{Strict::BOOLEAN}([true, false]);

// object
Collection::{Strict::OBJECT}([new stdClass(), new Exception()]);
  • User types
<?php

use kartavik\Support\Collection;
use kartavik\Support\Strict;

// You can put name of class to static call
// In this case collection can take only stdClass
// It will work with any declared classes
$collection = Collection::{stdClass::class}([]);

// you can also do it with constructor
$collection = new Collection(Strict::object(stdClass::class), []);

// Strict class also support static call for class name
$strict = Strict::{stdClass::class}();
$collection = new Collection($strict, []);

Extend

StringCollection.php:

<?php

use kartavik\Support;

class StringCollection extends Support\Collection
{
    public function __construct(array $items)
    {
        // do something
        
        parent::__construct(Support\Strict::string(), $items);
    }
}

Where is strong type?

Class Strict help collection to validate type of elements;

If you will try in any moment put to the collection element that is not of element type you will get Exception\Validation

If you will try set some specific type you will catch Exception\UnprocessedType

Authors:

License

MIT