kuaukutsu/ds-collection

Is the abstract layer which covers functionality the data structure Collection.

2.0.4 2023-11-15 13:50 UTC

This package is auto-updated.

Last update: 2024-03-29 20:33:46 UTC


README

Коллекция объектов.

PHP Version Require Latest Stable Version License static analysis

Tech Stack

kuaukutsu/ds-collection is built on the following main stack:

Примеры

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));

$collectionOther = new DtoCollection();
$collectionOther->attach(new Dto(3, 'third'));
$collectionOther->attach(new Dto(4, 'fourth'));

$collection->merge($collectionOther);

Фильтрация

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));
$collection->attach(new Dto(3, 'first'));
$collection->attach(new Dto(4, 'second'));

$collectionByFiltered = $collection->filter(
    static fn(Dto $dto): bool => $dto->name === 'first'
);

Сортировка

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));
$collection->attach(new Dto(3, 'first'));
$collection->attach(new Dto(4, 'second'));

$sortCollection = $collection->sort(
    static fn(Dto $a, Dto $b): int => strcmp($a->name, $b->name)
);

Индексация

В классе коллекции необходимо указать на основании какого свойства объекта индексировать коллекцию. Это делается при помощи метода indexBy, например:

/**
 * @param Dto $item
 * @return int
 */
protected function indexBy($item): int
{
    return $item->id;
}
/**
 * @param Dto $item
 * @return string
 */
protected function indexBy($item): string
{
    return $item->name;
}

Это позволяет получить быстрый доступ к объекту по ключу индекса, например для indexBy по ключу name:

$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));

$dto = $collection->get('second');

Составные ключи

Ключ индексирования может быть составным, например:

/**
 * @param Dto $item
 * @return array<scalar>
 */
protected function indexBy($item): array
{
    return [$item->id, $item->name];
}
$collection = new DtoCollection();
$collection->attach(new Dto(1, 'first'));
$collection->attach(new Dto(2, 'second'));
$collection->attach(new Dto(3, 'third'));

$dto = $collection->get(2, 'second');

Feature

Docker

docker pull ghcr.io/kuaukutsu/php:8.1-cli
docker pull ghcr.io/kuaukutsu/php:8.2-cli

Container:

  • ghcr.io/kuaukutsu/php:${PHP_VERSION}-cli (default)
  • jakzal/phpqa:php${PHP_VERSION}

shell

docker run --init -it --rm -v "$(pwd):/app" -w /app ghcr.io/kuaukutsu/php:8.1-cli sh

Testing

Unit testing

The package is tested with PHPUnit. To run tests:

make phpunit
PHP_VERSION=7.4 make phpunit

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

make psalm
PHP_VERSION=7.4 make psalm

Code Sniffer

make phpcs

Rector

make rector