Mapping to Objects
Parser types
Most of the parsers that come with Parsica, return strings as outputs.
In PHP 7.x, the type of $parser
is Parser
, but you can think of it having the type Parser<string>
. PHP doesn't support generics, so it doesn't enforce that. However, working with Parsica is easier if you always think of parsers having an inner type.
Parser<T>
means that if we successfully run the parser on an input, it will output a value of typeT
.
Here's an example of a parser of type Parser<array<string>>
:
The map combinator
The point of parsing to turn strings into more useful data structures. The combinator map
can help you with that. It does the same thing as PHP's array_map
function. You combine a parser and a callable
, and you get a new parser. This new parser will apply the callable to the output of the parser.
We can use it for manipulating the output. Here's a simple example:
If the parser fails, the callable is not applied to the output (because there is no output). So you don't need to worry about error handling.
Casting to scalars
We can now use this to cast the parser's output to scalars:
It also works inside nested parsers. We can use this on the sepBy
example from above:
The type of this last parser is now Parser<array<int>>
instead of the original Parser<array<string>>
.
Casting to objects
We'll want to cast to much more interesting data structures than scalars and arrays. Let's parse some monetary values into a nested value object structure. Money
is composed of an integer value and a Currency
value object: