Skip to content

Instantly share code, notes, and snippets.

@Basster
Last active November 8, 2018 13:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Basster/b7ce19ab0ce291cfb07fc5bae8a59088 to your computer and use it in GitHub Desktop.
Save Basster/b7ce19ab0ce291cfb07fc5bae8a59088 to your computer and use it in GitHub Desktop.
Generate Collection and CollectionIterator for a PHP class. Inspired by https://github.com/sebastianbergmann/shaku

Place both files into ${idea.config.path}/fileTemplates (%userprofile%\.PhpStorm<Version>\config\fileTemplates on Windows, ~/.PhpStorm<Version>/config/fileTemplates on Mac or Linux) and Restart PhpStorm. Now you will find Collection and CollectionIterator on the "Generate" menu of the file browser.

<?php declare(strict_types=1);
#parse("PHP File Header.php")
namespace ${NAMESPACE};
final class ${CLASS}Collection implements \Countable, \IteratorAggregate
{
/**
* @var ${CLASS}[]
*/
#[[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(${CLASS} ...#[[$items): self
{
return self::fromArray($items);
}]]#
#{if}($IMMUTABLE == "true")private#{else}public#{end} function add(${CLASS} #[[$item): void
{
$this->items[] = $item;
}]]#
/**
* @return ${CLASS}[]
*/
#[[public function items(): array
{
return $this->items;
}]]#
public function getIterator(): ${CLASS}CollectionIterator
{
return new ${CLASS}CollectionIterator(#[[$this]]#);
}
#[[public function count(): int
{
return \count($this->items);
}]]#
}
<?php declare(strict_types=1);
#parse("PHP File Header.php")
namespace ${NAMESPACE};
final class ${CLASS}CollectionIterator implements \Iterator
{
/**
* @var ${CLASS}[]
*/
#[[private $items;]]#
/**
* @var int
*/
#[[private $position;]]#
public function __construct(${CLASS}Collection #[[$collection)
{
$this->items = $collection->items();
}
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(): ${CLASS}
{
#[[return $this->items[$this->position];
}
public function next(): void
{
$this->position++;
}]]#
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment