Skip to content

Commit

Permalink
Iterators improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ben-synapse committed May 5, 2017
1 parent 50eafeb commit 7b233ff
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/Iterator/TextLinesIterator.php
Expand Up @@ -31,12 +31,37 @@ public function __construct(string $content, bool $skipEmptyLines = true)
* @return string[]
*/
public function getIterator()
{
if (true === $this->skipEmptyLines) {
return $this->traverseWithStrTok();
}
else {
return $this->traverseWithPregSplit();
}
}

/**
* Uses a regex to split lines.
* @return \Generator|string[]
*/
private function traverseWithPregSplit()
{
$lines = preg_split("/((\r?\n)|(\r\n?))/", $this->content);
foreach ($lines as $line) {
if (true === $this->skipEmptyLines && 0 === mb_strlen($line)) {
continue;
}
yield $line;
}
}

/**
* Uses strtok to split lines. Provides better performance, but skips empty lines.
* @return \Generator|string[]
*/
private function traverseWithStrTok()
{
$tok = strtok($this->content, "\r\n");
while (false !== $tok) {
$line = $tok;
$tok = strtok("\n\r");
yield $line;
}
}
Expand Down

0 comments on commit 7b233ff

Please sign in to comment.