Installation | Functionality | Usage | For developers | License | Related projects
- php 8.0 or higher
composer require petrenkoanton/php-collection
Method | Exception |
---|---|
__construct(Collectable ...$items) | - |
add(Collectable $item): void | InvalidItemTypeException | InvalidConstructorDeclarationException |
filter(callable $callback): Collection | - |
getItems(): array | - |
getItem(int $key): Collectable | InvalidKeyException |
first(): Collectable | InvalidKeyException |
count(): int | - |
Main library exception is CollectionException.
Code | Message pattern | Exception | Parent |
---|---|---|---|
100 | Collection: %s | Expected item type: %s | Given: %s | InvalidItemTypeException | CollectionException |
101 | Collection: %s | Err: Invalid constructor declaration | InvalidConstructorDeclarationException | CollectionException |
200 | Collection: %s | Invalid key: %d | InvalidKeyException | CollectionException |
<?php
declare(strict_types=1);
use Collection\Arrayable;
use Collection\Collectable;
use Collection\Collection;
// All collection items must implements `Collection\Collectable` interface
interface EntityInterface extends Collectable
{
}
class Entity implements Arrayable, EntityInterface
{
public function __construct(private int $id)
{
}
public function getId(): int
{
return $this->id;
}
public function toArray(): array
{
return ['id' => $this->id];
}
}
class EntityInterfaceCollection extends Collection
{
public function __construct(EntityInterface ...$items)
{
parent::__construct(...$items); // Mandatory call of the parent constructor
}
}
$firstEntity = new Entity(1);
$secondEntity = new Entity(2);
$collection = new EntityInterfaceCollection($firstEntity);
$collection->add($secondEntity);
$firstEntityId = $collection->first()->getId(); // 1
$count = $collection->count(); // 2
$collectionAsArray = $collection->toArray() // [['id' => 1], ['id' => 2]];
Utils:
- make
- docker-compose
Create ./docker/.env
make init
php 8.0
make up80
php 8.1
make up81
php 8.2
make up82
php 8.3
make up83
Also you need to run this command before build container with another php version. It will remove network and previously created container.
make down
Go inside of the container
make inside
Check php version
make php-v
Check package version
make v
Run PHPUnit tests with code coverage
make test-c
Run Psalm
make psalm
Run PHP_CodeSniffer
make phpcs
Or by all-in-one command from the inside of the container
composer check-all
The php-collection library is open-sourced software licensed under the MIT license.