jojo1981/typed-set

类型化集合

5.0.1 2023-02-06 09:29 UTC

This package is auto-updated.

Last update: 2024-09-06 12:50:41 UTC


README

Build Status Coverage Status Latest Stable Version Total Downloads License

作者:Joost Nijhuis <jnijhuis81@gmail.com>

类型化集合是一个无序可变集合。

创建新的集合时,必须给出集合的type
还可以通过以下方式使用元素创建集合: \Jojo1981\TypedSet\Set::createFromElements
集合具有特定的type,并保证集合中所有元素具有相同的type
type可以是原始type或为集合设置class/interface type

当元素的哈希值相同时,元素被认为是相等的。
当元素是\Jojo1981\TypedSet\HashableInterface的实例或
存在支持该类型的处理器时,可以检索哈希值。处理器是实现
接口: \Jojo1981\TypedSet\HandlerInterface的类,并注册到GlobalHandler中。与处理器相比,HashableInterface具有更高的优先级。

GlobalHandler是一个单例,可以在应用程序启动时进行配置。
可以启用默认处理器和自定义处理器。

当元素是未实现HashableInterface的对象且没有处理器支持该元素时,
将回退到根据对象哈希值生成哈希值。
这个集合将是一个具有唯一对象实例的集合。

可用类型有

  • int(整数别名)
  • float(别名real、double或number)
  • string(别名text)
  • array
  • object
  • callable(别名callback)
  • iterable
  • class(类或接口名称)

\Jojo1981\TypedSet\Set类是可计数的并且是可遍历的(可迭代的)。
集合具有以下方便的实例方法

  • add($element): void
  • addAll(array $elements = []): void
  • contains($element): bool
  • remove($element): void
  • clear(): void
  • isEmpty(): bool
  • isNonEmpty(): bool
  • toArray(): array
  • getType(): string
  • isEqualType(TypeInterface $type): bool
  • isEqual(Set $other): bool
  • compare(Set $other): DifferenceResult
  • map(callable $mapper, ?string $type = null): Set
  • filter(callable $predicate): Set
  • find(callable $predicate): mixed
  • all(callable $predicate): bool
  • some(callable $predicate): bool
  • none(callable $predicate): bool
  • count(): int

\Jojo1981\TypedSet\Set具有静态方法createFromElements

安装

git clone https://github.com/jojo1981/typed-set.git

Composer

安装PHP Composer

composer require jojo1981/typed-set

基本用法

<?php

require 'vendor/autoload.php';

// Some examples on how to construct a set

$set1 = new \Jojo1981\TypedSet\Set('string', ['text1', 'text2', 'text1']);
$set1->count(); // will return 2
$set1->contains('text1'); // will return true
$set1->contains('text3'); // will return false

$set2 = \Jojo1981\TypedSet\Set::createFromElements([1, 6, 7, 1, 2, 2, 9]);
$set2->count(); // will return 5
$set2->add(7);
$set2->count(); // will return 5
$set2->add(8);
$set2->count(); // will return 6

$set3 = new \Jojo1981\TypedSet\Set(\Jojo1981\TypedSet\TestSuite\Fixture\InterfaceTestEntity::class);
$set3->addAll([new \Jojo1981\TypedSet\TestSuite\Fixture\TestEntity(), new \Jojo1981\TypedSet\TestSuite\Fixture\TestEntityBase()]);
$set1->count(); // will return 2

配置GlobalHandler

<?php

require 'vendor/autoload.php';

// Optionally you can enable the default handlers before or after registering your own handlers.
\Jojo1981\TypedSet\Handler\GlobalHandler::getInstance()->addDefaultHandlers();

// Register a custom handler
\Jojo1981\TypedSet\Handler\GlobalHandler::getInstance()->registerHandler(new \Jojo1981\TypedSet\TestSuite\Fixture\PersonHandler());