ToolingFormatting and fixers

Tooling

Formatting and fixers

How phn fmt lays out .phn files, how your php-cs-fixer style reaches them, and how phn fix carries php-cs-fixer and Rector changes back to the source.

A .phn file has two styles to follow: Phaenon's layout, which no PHP tool knows, and your project's PHP style, which your php-cs-fixer configuration already states. phn fmt applies both, in that order. The second goes through phn fix, which runs a PHP tool on the compiled outputs and carries what it changed back into the .phn; Rector works the same way.

phn fmt

Take a file written in an older spelling, with PHP's own style left loose:

you write
namespace App;

final class PriceList {
    private map< string,int > $prices = [];

    public function set(string $sku, int $cents): void
    {
        $this->prices[$sku]=$cents;
    }

    public function get(string $sku): int THROWS \OutOfBoundsException {
        if (!isset($this->prices[$sku])) {
            throw new \OutOfBoundsException($sku);
        }
        return $this->prices[$sku];
    }
}
$ phn checkexit 1
src/Example.phn:11:43: error P1006: `THROWS` is Phaenon's `throws`, written in lower case; phn fmt rewrites it
   11 |     public function get(string $sku): int THROWS \OutOfBoundsException {
      |                                           ^^^^^^
1 files checked: 1 errors, 0 warnings

phn fmt formats the roots of phaenon.json, or the files and directories you name:

vendor/bin/phn fmt
5 files formatted, 1 changed in Phaenon's layout
PHP CS Fixer 3.95.30 Adalbertus by Fabien Potencier, Dariusz Ruminski and contributors.
…
php-cs-fixer changed 1 files: 2 changes carried back to 1 sources, 0 in text the compiler wrote
after the rebuild, php-cs-fixer changes nothing
namespace App;

final class PriceList
{
    private map<string, int> $prices = [];

    public set(string $sku, int $cents): void {
        $this->prices[$sku] = $cents;
    }

    public get(string $sku): int throws \OutOfBoundsException {
        if (!isset($this->prices[$sku])) {
            throw new \OutOfBoundsException($sku);
        }
        return $this->prices[$sku];
    }
}

The first layer moved the braces, wrote map<string, int>, lifted function off the methods and wrote throws in lower case. The second, the project's php-cs-fixer, put spaces around =.

Phaenon's layout

The first layer has no options:

  • spaces for tabs, which Phaenon forbids outside strings and comments (P1005);
  • a function's or method's opening brace on its declaration's line, a class-like's on a line of its own, {} for an empty body, and no blank line before the first line;
  • a docblock with one line of content on one line;
  • the spacing of what only Phaenon has: class Box<T of Item>, map<string, list<int>>, (int, string), Closure(int): bool, name(): string => $this->name;, throws A|B, nothrow;
  • Phaenon's words in lower case where the checker reports another case (P1006): throws, nothrow, type, of, in, out, class<T>, list<T>, (bytes). Map and Bytes stay, since they may name your classes;
  • the spellings the language withdrew: fun before a method's name goes, function is lifted off a method that does not need it (its modifiers stay as written), and is, as and as? become the PHP test each one compiled to.
you write
namespace App;

final class Parser
{
    public fun count(mixed $value): int {
        if ($value is int) {
            return $value;
        }
        return ($value as string) |> strlen(...);
    }
}
$ phn checkexit 1
src/Example.phn:5:12: error P1001: `fun` left the language (roadmap D27): a method is declared without a keyword, `count(…)`, as phn fmt writes it
    5 |     public fun count(mixed $value): int {
      |            ^^^
src/Example.phn:6:13: error P1001: `is` left the language (roadmap D26): write PHP's own test, `is_int($value)`, which phn fmt writes
    6 |         if ($value is int) {
      |             ^^^^^^^^^^^^^
src/Example.phn:9:17: error P1001: `as` left the language (roadmap D26): write PHP's own test, `is_string($value) ? $value : throw new \TypeError('expected string, got ' . get_debug_type($value))`, which phn fmt writes
    9 |         return ($value as string) |> strlen(...);
      |                 ^^^^^^^^^^^^^^^^
1 files checked: 3 errors, 0 warnings
namespace App;

final class Parser
{
    public count(mixed $value): int {
        if (is_int($value)) {
            return $value;
        }
        return (is_string($value) ? $value : throw new \TypeError('expected string, got ' . get_debug_type($value))) |> strlen(...);
    }
}

Most of those rewrites depend on the operand's type, so phn fmt checks the files that hold one first. The first layer changes nothing else in the code: turning a block body into => expr is phn migrate's, and PHP's own spacing, list<T> $items, is the second layer's.

Your PHP style

The second layer runs your fixer through phn fix. phn fmt takes the command from "fmt" in phaenon.json, else runs tools/php-cs-fixer/vendor/bin/php-cs-fixer fix, else vendor/bin/php-cs-fixer fix; without any of them the first layer is all there is. "fmt": [] turns the second layer off (phaenon.json). After the fixer, the first layer runs again.

In CI and in editors

phn fmt --check writes nothing, reports each change either layer would make, and exits with 1 when there is one:

src/PriceList.phn: not in Phaenon's layout
5 files checked, 1 not in Phaenon's layout
PHP CS Fixer 3.95.30 Adalbertus by Fabien Potencier, Dariusz Ruminski and contributors.
…
src/PriceList.phn:8: php-cs-fixer (binary_operator_spaces) changes: "" → " "
src/PriceList.phn:8: php-cs-fixer (binary_operator_spaces) changes: "" → " "
php-cs-fixer would change 1 files: 2 changes in 1 sources, 0 in text the compiler wrote

A file that does not parse is left as it is and fails either form; the others are formatted.

The editors format with the first layer alone, which takes milliseconds: the language server's formatting, and PhpStorm's Reformat Code through phn fmt --stdin, which reads standard input and writes the result to standard output. Run phn fmt for the second layer (Editors).

Configuring php-cs-fixer

php-cs-fixer runs on the outputs, where its configuration points, never on the .phn:

<?php

$finder = PhpCsFixer\Finder::create()
    ->in([__DIR__ . '/.src', __DIR__ . '/.tests']);

return (new PhpCsFixer\Config())
    ->setRules([
        '@PER-CS3x0' => true,
    ])
    ->setFinder($finder);
  • Use a PER Coding Style set, @PER-CS3x0 or a later one. The compiler lays out what it writes as PER Coding Style 3.0, so the outputs pass it with no exception for compiled code.

  • Not @PSR12. It expands every empty body {}, which is the source's text, so phn fix would carry the expansion into the .phn, and the first layer would take it out again. phn fmt detects the conflict, keeps Phaenon's layout and fails:

    src/Discount.phn: the fixer's change undoes Phaenon's layout; laid out again
    1 files laid out again after the fixer: its configuration conflicts with Phaenon's layout, as @PSR12 does on every empty body {} (a PER Coding Style set, @PER-CS3x0, keeps it)
  • Rules that rewrite code (@PHP8x2Migration, risky ones) work as in a PHP project: what they change in your code is carried back.

  • Add .php-cs-fixer.cache to .gitignore.

PHP tools through phn fix

phn fix [--check] -- <command> [<arg>...]

phn fix runs a PHP tool that rewrites files in place, such as php-cs-fixer or Rector, on the outputs. Here is a method that Rector's SimplifyIfReturnBoolRector shortens, with Rector configured on .src (phaenon.json):

namespace App;

final class Discount
{
    __construct(private int $percent) {}

    applies(int $cents): bool {
        if ($cents >= 1000) {
            return true;
        }
        return false;
    }

    apply(int $cents): int => $this->applies($cents) ? intdiv($cents * (100 - $this->percent), 100) : $cents;
}
vendor/bin/phn fix --check -- vendor/bin/rector process
src/Discount.phn:8: rector (SimplifyIfReturnBoolRector) changes: "if (" → "return "
src/Discount.phn:8: rector (SimplifyIfReturnBoolRector) changes: ") {\n            return true;\n        }\n        return false" → ""
rector would change 1 files: 2 changes in 1 sources, 0 in text the compiler wrote
vendor/bin/phn fix -- vendor/bin/rector process
rector changed 1 files: 2 changes carried back to 1 sources, 0 in text the compiler wrote
after the rebuild, rector changes nothing
namespace App;

final class Discount
{
    __construct(private int $percent) {}

    applies(int $cents): bool {
        return $cents >= 1000;
    }

    apply(int $cents): int => $this->applies($cents) ? intdiv($cents * (100 - $this->percent), 100) : $cents;
}

How changes come back

  1. phn fix builds the project and remembers, for each output, which stretches of it were copied from the source byte for byte.
  2. It runs the command, which rewrites outputs.
  3. It compares each rewritten output with what it built. A change inside copied text is applied to the .phn at the same place, and so is a deletion whose two ends lie in copied text, which takes the text between them along: a method Rector removes goes with the head the compiler wrote for it.
  4. It rebuilds and runs the tool again, and repeats while changes are still carried, three rounds at most. Then it reports what the tool still changes, puts the outputs back as built, and exits with 1 if anything is left.

For php-cs-fixer and Rector each reported change names its rule, read from the tool's own JSON report, which phn fix asks for.

What is not carried

A change of text the compiler wrote is not carried: the header, a docblock it wrote, the public function of a method declared without them, an erased type, an import it added. The rebuild writes that text anew, so the change would not survive anyway. phn fix reports it at the .phn line it belongs to:

php-cs-fixer changed 2 files: 0 changes carried back to 0 sources, 2 in text the compiler wrote
src/Inventory.phn:11: php-cs-fixer (general_phpdoc_annotation_remove) changes text the compiler wrote: " @throws OutOfStock\n     *" → ""
src/PriceList.phn:11: php-cs-fixer (general_phpdoc_annotation_remove) changes text the compiler wrote: " @throws \\OutOfBoundsException\n     *" → ""
after the rebuild, php-cs-fixer still changes 2 files: 0 changes in 0 sources, 2 in text the compiler wrote

That rule removes the @throws tags the compiler writes for each throws clause: the clause is the source, so the place to change it is the .phn. A tool that keeps wanting to change compiler text points at a rule to turn off, or at a compiler bug worth reporting.

Also not carried: a replacement that spans copied and compiler-written text, and a file the tool creates or removes in an output directory, which the rebuild undoes. A file the tool changes outside the output directories, its own configuration for one, keeps the change. A .php that a root holds as plain PHP is copied to the output whole, so every change to its copy is carried.

--check writes no source: it reports every change at its .phn line and exits with 1 when there is one, which is the CI form of a Rector or php-cs-fixer run.