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.
Last active
November 8, 2018 13:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
}]]# | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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