Skip to content

Commit

Permalink
Refactor unique filtering in formatter combiner
Browse files Browse the repository at this point in the history
  • Loading branch information
Stadly committed Jan 22, 2019
1 parent 3a94f63 commit b04e783
Showing 1 changed file with 5 additions and 23 deletions.
28 changes: 5 additions & 23 deletions src/WordFormatter/FormatterCombiner.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,47 +14,29 @@ final class FormatterCombiner extends ChainableFormatter
*/
private $wordFormatters;

/**
* @var bool Whether the result should only contain unique words.
*/
private $filterUnique;

/**
* @param WordFormatter[] $wordFormatters Word formatters.
* @param bool $includeUnformatted Whether the result should also include the words unformatted.
* @param bool $filterUnique Whether the result should only contain unique words.
*/
public function __construct(array $wordFormatters, bool $includeUnformatted = true, bool $filterUnique = true)
{
if ($includeUnformatted) {
if ($filterUnique) {
$formatterCombiner = new FormatterCombiner($wordFormatters, $includeUnformatted, false);
$formatterCombiner->setNext(new UniqueFilter());
$wordFormatters = [$formatterCombiner];
} elseif ($includeUnformatted) {
$wordFormatters[] = new Unformatter();
}

$this->wordFormatters = $wordFormatters;
$this->filterUnique = $filterUnique;
}

/**
* @param iterable<string> $words Words to format.
* @return Traversable<string> The words formatted by all the word formatters in the formatter combiner.
*/
protected function applyCurrent(iterable $words): Traversable
{
$formatted = $this->applyFormatters($words);

if ($this->filterUnique) {
$uniqueFilter = new UniqueFilter();
yield from $uniqueFilter->apply($formatted);
} else {
yield from $formatted;
}
}

/**
* @param iterable<string> $words Words to format.
* @return Traversable<string> The words formatted by all the word formatters in the formatter combiner.
*/
private function applyFormatters(iterable $words): Traversable
{
foreach ($this->wordFormatters as $wordFormatter) {
yield from $wordFormatter->apply($words);
Expand Down

0 comments on commit b04e783

Please sign in to comment.