sebastian / shaku
此包已被废弃,不再维护。未建议替代包。
自动生成类型安全的 Collection 和 CollectionIterator 类的工具
1.4.0
2018-11-09 11:19 UTC
Requires
- php: ^7.2
- sebastian/version: ^2.0.1
- symfony/console: ^4.0
README
shaku
可以自动生成类型安全的 Collection
和 CollectionIterator
类。
安装
推荐使用此工具的方式是 PHP Archive (PHAR)
$ wget https://phar.phpunit.de/shaku.phar $ php shaku.phar --version
此外,建议使用 Phive 来安装和更新项目的工具依赖。
或者,您也可以使用 Composer 下载并安装此工具以及其依赖项。尽管如此,这并不推荐。
使用方法
假设您有一个名为 Value
的类(在 src/Value.php
中声明),并需要一个用于此类型对象的类型安全 ValueCollection
namespace vendor; final class Value { // ... }
生成 Collection
和 CollectionIterator
您可以使用此工具自动生成如下 ValueCollection
和 ValueCollectionIterator
类的代码
$ php shaku.phar --immutable vendor Value src
上述代码将生成以下代码
<?php declare(strict_types=1); namespace vendor; final class ValueCollection implements \Countable, \IteratorAggregate { /** * @var Value[] */ private $items = []; public static function fromArray(array $items): self { $collection = new self; foreach ($items as $item) { $collection->add($item); } return $collection; } public static function fromList(Value ...$items): self { return self::fromArray($items); } private function __construct() { } private function add(Value $item): void { $this->items[] = $item; } /** * @return Value[] */ public function toArray(): array { return $this->items; } public function getIterator(): ValueCollectionIterator { return new ValueCollectionIterator($this); } public function count(): int { return \count($this->items); } public function isEmpty(): bool { return empty($this->items); } public function contains(Value $item): bool { foreach ($this->items as $_item) { if ($_item === $item) { return true; } } return false; } }
<?php declare(strict_types=1); namespace vendor; final class ValueCollectionIterator implements \Countable, \Iterator { /** * @var Value[] */ private $items; /** * @var int */ private $position; public function __construct(ValueCollection $collection) { $this->items = $collection->toArray(); } public function count(): int { return \iterator_count($this); } public function rewind(): void { $this->position = 0; } public function valid(): bool { return $this->position < \count($this->items); } public function key(): int { return $this->position; } public function current(): Value { return $this->items[$this->position]; } public function next(): void { $this->position++; } }
使用生成的 Collection
和 CollectionIterator
从对象数组创建集合
$values = ValueCollection::fromArray([new Value, new Value]);
从对象列表创建集合
$values = ValueCollection::fromList(new Value, new Value);
创建一个空集合并向其中添加对象
$values = new ValueCollection; $values->add(new Value); $values->add(new Value);
Shaku?
此工具以 "Shaku, the Collector" 命名,版权属于 Blizzard Entertainment, Inc.