Skip to content

Creating your own Rules

gossi edited this page Oct 18, 2014 · 1 revision

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 Formatter Process

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.

Parsing

Albeit tokenizing the code, the parser does a lot more things, so here is what's happening:

  1. Tokenize the given code
  2. Fix stuff, so we have a reliable token set
  3. Filter tokens (at the moment, whitespace tokens are filtered out)
  4. 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.

Formatting

After parsing, the formatting happens. There is a DelegateFormatter that iterates over the tokens and visits each registered formatter with the current token.

Post-Processing

At the moment, nothing is happening here, but it's planned to have a sanitizing step here.

How Formatters work

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

Processing a token can be done in two ways.

  1. Implement the doVisitToken method on the formatter, or if present add a method for whatever you want to format and call it from doVisitToken (Example: WhitespaceFormatter).
  2. Register a listener on the Context using the init method (Example: NewlineFormatter).

Controlling the Output

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.

Place your Code

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).