Strongly typed generic collection implementation
Use composer to install:
composer require kartavik/typed-collection
- 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, []);
StringCollection.php:
<?php
use kartavik\Support;
class StringCollection extends Support\Collection
{
public function __construct(array $items)
{
// do something
parent::__construct(Support\Strict::string(), $items);
}
}
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