-
Notifications
You must be signed in to change notification settings - Fork 12
Creating your own Rules
This is a little how-to on creating your own rules or extending existing ones. This page will tell you, how the formatter works, how to get the processed tokens and where to put your code.
The first thing the formatter does is parsing the given code and create a token collection. The token collection will be iterated and each formatter will be applied.
Albeit tokenizing the code, the parser does a lot more things, so here is what's happening:
- Tokenize the given code
- Fix stuff, so we have a reliable token set
- Filter tokens (at the moment, whitespace tokens are filtered out)
- Analyze tokens (finding units with start and end)
An accompanying parsing compartment is the Context, which is a powerful helper to manage various contexts in the token collection.
After parsing, the formatting happens. There is a DelegateFormatter
that iterates over the tokens and visits each registered formatter with the current token.
At the moment, nothing is happening here, but it's planned to have a sanitizing step here.
Formatters (such as WhitespaceFormatter
or NewlineFormatter
) are instantiated by the DelegateFormatter
who keeps track of the right order in which they are applied. The DelegateFormatter
iterates over the tokens and visits each formatter with the current token. Formatters extend the SpecializedFormatter
to inherit all dependencies.
Processing a token can be done in two ways.
- Implement the
doVisitToken
method on the formatter, or if present add a method for whatever you want to format and call it fromdoVisitToken
(Example:WhitespaceFormatter
). - Register a listener on the Context using the
init
method (Example:NewlineFormatter
).
You have access to the writer
property to print something on the output. By default at the end of visiting all specialized formatters the token will be printed there, too. You might want to write something, too. You have access to the DefaultFormatter
where you enqueue commands that are executed before or after the token is printed. Use either $this->defaultFormatter->addPre*()
or $this->defaultFormatter->addPost*()
to enqueue commands.
In very rare cases you might want to suppress the token output, because you modify the token contents. Suppress the token output with $this->defaultFormatter->hideToken()
and access $this->writer
to handle the output on your own.
Your formatter rules should go into the formatter package either as new class or into an existing one. If you need to add some analysis, Analyzer
resp. Context
is for you (remark: See issue #17 on this).