kuaukutsu/ds-collection

是覆盖数据结构集合功能的功能抽象层。

2.0.4 2023-11-15 13:50 UTC

This package is auto-updated.

Last update: 2024-09-29 21:35:22 UTC


README

对象集合。

PHP Version Require Latest Stable Version License static analysis

技术栈

kuaukutsu/ds-collection 是基于以下主要技术栈构建的

示例

$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

$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');

特性

Docker

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

容器

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

shell

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

测试

单元测试

该软件包使用 PHPUnit 进行测试。要运行测试

make phpunit
PHP_VERSION=7.4 make phpunit

静态分析

代码使用 Psalm 进行静态分析。要运行静态分析

make psalm
PHP_VERSION=7.4 make psalm

代码嗅探器

make phpcs

Rector

make rector