phug / reader
Pug (ex-Jade) string reader for PHP, HTML template engine structured by indentation
Fund package maintenance!
kylekatarnls
Open Collective
Tidelift
Installs: 91 605
Dependents: 1
Suggesters: 0
Security: 0
Stars: 4
Watchers: 3
Forks: 1
Open Issues: 0
Requires
- php: >=5.5.0
- phug/util: ^0.3.5 || ^1.0
- psr/http-message: ^1.0
- symfony/polyfill-mbstring: *
- dev-master / 1.x-dev
- 1.13.0
- 1.12.3
- 1.12.2
- 1.12.1
- 1.12.0
- 1.11.0
- 1.10.0
- 1.9.0
- 1.8.3
- 1.8.2
- 1.8.1
- 1.8.0
- 1.7.3
- 1.7.2
- 1.7.1
- 1.7.0
- 1.6.0
- 1.5.0
- 1.4.0
- 1.4.0-beta2
- 1.4.0-beta1
- 1.3.0
- 1.2.0
- 1.1.0
- 1.0.1
- 1.0.0
- 1.0.0-RC3
- 1.0.0-RC.2
- 1.0.0-rc.1
- 0.2.2
- 0.2.1
- 0.2.0
- 0.1.4
- 0.1.3
- 0.1.2
- 0.1.1
- 0.1.0
- dev-analysis-xgmrM9
- dev-feature/abstract-token-handler
- dev-feature/duplication-threshold
- dev-feature/multi-tester-3
- dev-feature/symfony-7
- dev-fix/strict-in-array
- dev-remotes/pull/100/merge
- dev-remotes/pull/101/merge
- dev-remotes/pull/102/merge
- dev-remotes/pull/104/merge
- dev-remotes/pull/105/merge
- dev-remotes/pull/106/merge
- dev-remotes/pull/107/merge
- dev-remotes/pull/108/merge
- dev-remotes/pull/109/merge
- dev-remotes/pull/110/merge
- dev-remotes/pull/111/merge
- dev-remotes/pull/113/merge
- dev-remotes/pull/114/merge
- dev-remotes/pull/98/merge
- dev-remotes/pull/99/merge
- dev-simplify-split-script
- dev-multitest-php-8
- dev-feature/check-php-8
- dev-feature/issue-69-interpolations-in-comments
- dev-feature/issue-70-disallow-new-line-in-interpolations
- dev-feature/php-8-namespace
This package is auto-updated.
Last update: 2024-12-19 16:30:30 UTC
README
What is Phug Reader?
The Reader-class is a small utility that can parse and scan strings for specific entities.
It's mostly based on Regular Expressions, but also brings in tools to scan strings and expressions of any kind (e.g. string escaping, bracket counting etc.)
The string passed to the reader is swallowed byte by byte through consume
-mechanisms.
When the string is empty, the parsing is done (usually).
This class is specifically made for lexical analysis and expression-validation.
Installation
Install via Composer
composer require phug/reader
Usage
Basics
The process of reading with the Phug\Reader
involves peeking and consuming.
You peek, check, if it's what you wanted and if it is, you consume.
read-methods on the Reader will peek and consume automatically until they found what you searched for. match-methods work like peek, but work with regular expressions.
Lets create a small example code to parse:
$code = 'someString = "some string"';
Now we create a reader for that code
$reader = new Reader($code);
If you want a fixed encoding, use the second $encoding
parameter.
Now we can do our reading process.
First we want to read our identifier. We can do that easily with readIdentifier()
which returns null
if no identifier has been encountered and the identifier found otherwise.
It will stop on anything that is not an identifier-character (The space after the identifier, in this case)
$identifier = $reader->readIdentifier(); if ($identifier === null) { throw new Exception("Failed to read: Identifier expected"); } var_dump($identifier); //`someString`
To get to our =
-character directly, we can just skip all spaces we encounter.
This also allows for any spacing you want (e.g. you can indent the above with tabs if you like)
$reader->readSpaces();
If we need the spaces, we can always catch the returned result.
If no spaces are encountered, it just returns null
.
Now we want to parse the assignment-operator (=
) (or rather, validate that it's there)
if (!$reader->peekChar('=')) { throw new Exception("Failed to read: Assignment expected"); } //Consume the result, since we're `peek`ing, not `read`ing. $reader->consume();
Skip spaces again
$reader->readSpaces();
and read the string.
If no quote-character ("
or '
) is encountered, it will return null.
Otherwise, it will return the (already parsed) string, without quotes.
Notice that you have to check null
explicitly, since we could also have an empty string (""
) which evaluates to true
in PHP
$string = $reader->readString(); if ($string === null) { throw new Exception("Failed to read: Expected string"); } var_dump($string); //`some string`
The quote-style encountered will be escaped by default, so you can scan "some \" string"
correctly.
If you want to add other escaping, use the first parameter of readString
.
Now you have all parts parsed to make up your actual action
echo "Set `$identifier` to `$string`"; //Set `someString` to `some string`
and it was validated on that way.
This was just a small example, Phug Reader is made for loop-parsing.
Build a small tokenizer
use Phug\Reader; //Some C-style example code $code = 'someVar = {a, "this is a string (really, it \"is\")", func(b, c), d}'; $reader = new Reader($code); $tokens = []; $blockLevel = 0; $expressionLevel = 0; while ($reader->hasLength()) { //Skip spaces of any kind. $reader->readSpaces(); //Scan for identifiers if ($identifier = $reader->readIdentifier()) { $tokens[] = ['type' => 'identifier', 'name' => $identifier]; continue; } //Scan for Assignments if ($reader->peekChar('=')) { $reader->consume(); $tokens[] = ['type' => 'assignment']; continue; } //Scan for strings if (($string = $reader->readString()) !== null) { $tokens[] = ['type' => 'string', 'value' => $string]; continue; } //Scan block start if ($reader->peekChar('{')) { $reader->consume(); $blockLevel++; $tokens[] = ['type' => 'blockStart']; continue; } //Scan block end if ($reader->peekChar('}')) { $reader->consume(); $blockLevel--; $tokens[] = ['type' => 'blockEnd']; continue; } //Scan parenthesis start if ($reader->peekChar('(')) { $reader->consume(); $expressionLevel++; $tokens[] = ['type' => 'listStart']; continue; } //Scan parenthesis end if ($reader->peekChar(')')) { $reader->consume(); $expressionLevel--; $tokens[] = ['type' => 'listEnd']; continue; } //Scan comma if ($reader->peekChar(',')) { $reader->consume(); $tokens[] = ['type' => 'next']; continue; } throw new \Exception( "Unexpected ".$reader->peek(10) ); } if ($blockLevel || $expressionLevel) throw new \Exception("Unclosed bracket encountered"); var_dump($tokens); /* Output: [ ['type' => 'identifier', 'name' => 'someVar'], ['type' => 'assignment'], ['type' => 'blockStart'], ['type' => 'identifier', 'name' => 'a'], ['type' => 'next'], ['type' => 'string', 'value' => 'this is a string (really, it "is")'], ['type' => 'next'], ['type' => 'identifier', 'name' => 'func'], ['type' => 'listStart'], ['type' => 'identifier', 'name' => 'b'], ['type' => 'next'], ['type' => 'identifier', 'name' => 'c'], ['type' => 'listEnd'], ['type' => 'next'], ['type' => 'identifier', 'name' => 'd'], ['type' => 'blockEnd'] ] */
Keep expressions intact
Sometimes you want to keep expressions intact, e.g. when you allow inclusion of third-party-code that needs to be parsed separately.
The Reader brings a bracket-counting-utility that can do just that exactly.
Let's take Jade
as an example:
a(href=getUri('/abc', true), title=(title ? title : 'Sorry, no title.'))
To parse this, let's do the following:
//Scan Identifier ("a") $identifier = $reader->readIdentifier(); $attributes = []; //Enter an attribute block if available if ($reader->peekChar('(')) { $reader->consume(); while ($reader->hasLength()) { //Ignore spaces $reader->readSpaces(); //Scan the attribute name if (!($name = $this->readIdentifier())) { throw new \Exception("Attributes need a name!"); } //Ignore spaces $reader->readSpaces(); //Make sure there's a =-character if (!$reader->peekChar('=')) { throw new \Exception("Failed to read: Expected attribute value"); } $reader->consume(); //Ignore spaces $reader->readSpaces(); //Read the expression until , or ) is encountered //It will ignore , and ) inside any kind of brackets and count brackets correctly until we actually //reached the end-bracket $value = $reader->readExpression([',', ')']); //Add the attribute to our attribute array $attributes[$name] = $value; //If we don't encounter a , to go on, we break the loop if (!$reader->peekChar(',')) { break; } //Else we consume the , and continue our attribute parsing $reader->consume(); } //Now make sure we actually closed our attribute block correctly. if (!$reader->peekChar(')')) { throw new \Exception("Failed to read: Expected closing bracket"); } } $element = ['identifier' => $identifier, 'attributes' => $attributes]; var_dump($element); /* Output: [ 'identifier' => 'a', 'attributes' => [ 'href' => 'getUri(\'/abc\', true)', 'title' => '(title ? title : \'Sorry, no title.\')' ] ] */
You now got a parser for (really, really basic) Jade-elements! It can handle as many attributes as you like with all possible values you could think of without ever breaking the listing, regardless of contained commas and brackets.
Digging deeper, the Phug Reader is actually able to lex source code and text of any kind.