Skip to content

Commit

Permalink
feat: Implement actions
Browse files Browse the repository at this point in the history
  • Loading branch information
jubianchi committed Oct 7, 2020
1 parent 8c344eb commit 8ed62a0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
5 changes: 4 additions & 1 deletion src/combinators.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,20 +95,23 @@ function opt(Parser $parser): Parser
function many(Parser $parser): Parser
{
return (new Parser('many', function (Stream $stream, string $label, ?Debugger $debugger = null) use ($parser): Result {
$count = 0;
$results = [];

while (true) {
$transaction = $stream->begin();
$result = $parser($transaction, $debugger);

if ($result->isFailure()) {
if (0 === count($results)) {
if (0 === $count) {
return $result;
}

break;
}

++$count;

if (!($result instanceof Skip)) {
$results[] = $result->result();
}
Expand Down
26 changes: 23 additions & 3 deletions src/lib/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ class Parser
private string $label;
private string $originalLabel;

/**
* @var callable
*/
private $action;

/**
* @param callable(Stream, string, ?Debugger): Result $parser
*/
Expand Down Expand Up @@ -69,7 +74,13 @@ public function __invoke(Stream $stream, ?Debugger $debugger = null): Result
return $result;
}

return ($this->mapper)($result);
$mapped = ($this->mapper)($result);

if (null !== $this->action) {
($this->action)($mapped);
}

return $mapped;
} catch (Exception $exception) {
throw new RuntimeException($this->label.': '.$exception->getMessage(), $exception->getCode(), $exception);
}
Expand All @@ -90,9 +101,18 @@ public function label(string $label): self
*/
public function map(callable $mapper): self
{
$this->mapper = $mapper;
$parser = clone $this;
$parser->mapper = $mapper;

return $parser;
}

public function do(?callable $action): self
{
$parser = clone $this;
$parser->action = $action;

return $this;
return $parser;
}

/**
Expand Down

0 comments on commit 8ed62a0

Please sign in to comment.