Getting startedMigrate a PHP project

Getting started

Migrate a PHP project

phn migrate turns .php files into .phn, lifting PHPStan's docblock types into the language; then the checker, the build and your tests take over.

phn migrate turns .php files into .phn files. It strips the <?php tag, lifts the types PHPStan reads from docblocks into the signatures, drops the function keyword from methods and lays the code out as Phaenon writes it. Everything it cannot convert exactly, it leaves in place and reports with the reason. The compiled output of a migrated file keeps the signatures the PHP had.

This page migrates a real library, the sources of amphp/cache 2.0.1: nine files, generic, written for Psalm rather than for PHPStan at level max.

Before you start

  • Commit your work. phn migrate rewrites the files in place: Foo.php becomes Foo.phn, and the .php is gone. Version control is how you review the change and how you undo it.
  • Install the dependencies. Migrate reads the project's other files and its vendor code through Composer, to know what an interface or a parent class declares.
  • Require the compiler, as Install describes, so that vendor/bin/phn exists.

Run it

Give it the directories or files to convert. --php states the target, the oldest PHP the output must run on, and writes it into phaenon.json:

vendor/bin/phn migrate --php 8.5 src
phaenon.json: target PHP 8.5
phaenon.json:2:12: warning P4008: the target is PHP 8.5, but composer.json admits PHP 8.1 (require.php ">=8.1"): an install on 8.1 would load code it cannot run; raise require.php to ">=8.5"
src/AtomicCache.php:37: kept @throws CacheException: it has a description
src/AtomicCache.php:63: kept @throws CacheException: it has a description
…
src/LocalCache.php:27: kept @var int<1, max>|null: no Phaenon spelling for it
src/LocalCache.php:31: kept @param int<1, max>|null: no Phaenon spelling for it
…
src/StringCache.php:48: kept @throws CacheException: it has a description
9 files migrated, 0 skipped, 0 .phn files updated, 18 docblock tags kept
9 @throws lifted, 10 bodies written as =>, 19 braces moved up, 0 class braces moved down, 5 empty bodies written as {}, 4 docblocks collapsed; 690 lines became 557
1 arrays and iterables declared without an element type written <mixed>
0 chains as pipelines, 0 left as calls

Every .php under src/ is now a .phn:

git status --short
 D src/AtomicCache.php
 D src/Cache.php
…
?? phaenon.json
?? src/AtomicCache.phn
?? src/Cache.phn
…

Running it again changes nothing. It also runs on .phn files, so a tree migrated with an older release can be lifted further by a newer one.

What it rewrites

The library's PrefixCache, before:

src/PrefixCache.php
<?php declare(strict_types=1);

namespace Amp\Cache;

use Amp\ForbidCloning;
use Amp\ForbidSerialization;

/**
 * @template TValue
 * @implements Cache<TValue>
 */
final class PrefixCache implements Cache
{
    use ForbidCloning;
    use ForbidSerialization;

    public function __construct(
        private readonly Cache $cache,
        private readonly string $keyPrefix,
    ) {
    }

    /**
     * Gets the specified key prefix.
     */
    public function getKeyPrefix(): string
    {
        return $this->keyPrefix;
    }

    public function get(string $key): mixed
    {
        return $this->cache->get($this->keyPrefix . $key);
    }

    public function set(string $key, mixed $value, ?int $ttl = null): void
    {
        $this->cache->set($this->keyPrefix . $key, $value, $ttl);
    }

    public function delete(string $key): ?bool
    {
        return $this->cache->delete($this->keyPrefix . $key);
    }
}

and after:

src/PrefixCache.phn
namespace Amp\Cache;

use Amp\ForbidCloning;
use Amp\ForbidSerialization;

final class PrefixCache<TValue> implements Cache<TValue>
{
    use ForbidCloning;
    use ForbidSerialization;

    __construct(
        private readonly Cache $cache,
        private readonly string $keyPrefix,
    ) {}

    /** Gets the specified key prefix. */
    getKeyPrefix(): string => $this->keyPrefix;

    get(string $key): mixed => $this->cache->get($this->keyPrefix . $key);

    set(string $key, mixed $value, ?int $ttl = null): void => $this->cache->set($this->keyPrefix . $key, $value, $ttl);

    delete(string $key): ?bool => $this->cache->delete($this->keyPrefix . $key);
}

In order, migrate:

  • strips <?php, declare(strict_types=1) and a closing ?>: every compiled file declares strict types;
  • lifts generic docblocks into syntax: @template TValue becomes <TValue> on the class, @implements Cache<TValue> becomes implements Cache<TValue>, @param list<T> $xs becomes list<T> $xs, @return T becomes : T;
  • lifts a @throws X without a description into a throws X clause after the return type, and a lone @throws void into nothrow;
  • drops function from methods and the public that PHP implies, public function get() → get();
  • writes a body that is one return, or one expression under void, as => expr;, moves a function's opening brace up to its declaration, writes an empty body as {} and a docblock of one line on one line;
  • writes a chain of three nested calls or more as a pipeline with |>, where the pipeline is exact.

A tag is lifted only when its type has a Phaenon spelling and erases to the type PHP already sees, so the compiled output keeps the signatures the PHP had. Prose survives: @param $key string Cache key. in a docblock becomes @param $key - string Cache key., its description kept and its type left to the signature.

What it reports and leaves

Each line before the summary is a tag left in place, with the reason:

  • it has a description: a @throws or @return with prose stays, so the prose is not lost. Where the type could be lifted, it is in the signature too ("the type is now also in the declaration").
  • no Phaenon spelling for it: PHPStan types such as int<1, max> or non-negative-int have no syntax in Phaenon. They stay docblock types, which the checker reads as PHPStan does.
  • it erases to a different type than the declared …: lifting would change the signature PHP sees.

The summary counts what changed. "Arrays and iterables declared without an element type written <mixed>" is the one change of meaning: a bare array becomes array<mixed>, since the checker, like PHPStan at level max, asks every array for its element type. --list-types does better, below.

Lists and pipelines: an example

A small class of the kind most projects have:

src/Inbox.php
<?php

declare(strict_types=1);

namespace App;

final class Inbox
{
    private array $subjects = [];

    public function receive(string $subject): void
    {
        $this->subjects[] = $subject;
    }

    public function latest(): array
    {
        return array_slice(array_reverse(array_unique($this->subjects)), 0, 10);
    }
}

--list-types types a bare array from the values it holds: a private property's writes, the returns of a private or final method, the arguments of a private method. Where the evidence is complete, the array becomes list<T>, map<K, V>, array<V> or a tuple; every candidate left is reported with the reason.

vendor/bin/phn migrate --list-types src
1 files migrated, 0 skipped, 0 .phn files updated, 0 docblock tags kept
0 @throws lifted, 2 bodies written as =>, 0 braces moved up, 0 class braces moved down, 0 empty bodies written as {}, 0 docblocks collapsed; 20 lines became 13
2 arrays typed as lists and maps, 0 left
1 chains as pipelines, 0 left as calls
src/Inbox.phnyou write
namespace App;

final class Inbox
{
    private list<string> $subjects = [];

    receive(string $subject): void => $this->subjects[] = $subject;

    latest(): list<string> => $this->subjects
        |> array_unique(...)
        |> array_reverse(...)
        |> array_slice(?, 0, 10);
}
.src/Inbox.phpphn build writes
<?php

/* @generated by phaenon from Inbox.phn */

declare(strict_types=1);

namespace App;

final class Inbox
{
    /**
     * @var list<string>
     */
    private array $subjects = [];

    public function receive(string $subject): void
    {
        $this->subjects[] = $subject;
    }

    /**
     * @return list<string>
     */
    public function latest(): array
    {
        return array_slice(array_reverse(array_unique($this->subjects)), 0, 10);
    }
}

The nested calls became a pipeline, read in the order they run. For a PHP 8.5 target the compiler writes the pipeline back as the nested calls, since the ? placeholder is PHP 8.6's. Without --list-types, both arrays would have been array<mixed>. Migrate type-checks each file before and after: a file whose findings would grow gets its arrays back, and a file whose types a pipeline would change gets its calls back.

Point Composer at the outputs

--php wrote a project file that holds only the target. Add the roots:

phaenon.json
{
    "roots": {"src": ".src"},
    "php": "8.5"
}

In composer.json, point the autoloader at the output and raise require.php to the target, as the warning above asked:

@@ -21,7 +21,7 @@
         }
     ],
     "require": {
-        "php": ">=8.1",
+        "php": ">=8.5",
         "amphp/amp": "^3",
         "amphp/serialization": "^1",
         "amphp/sync": "^2",
@@ -36,7 +36,7 @@
     },
     "autoload": {
         "psr-4": {
-            "Amp\\Cache\\": "src"
+            "Amp\\Cache\\": ".src/"
         }
     },
     "autoload-dev": {

Add /.src/ to .gitignore. Point PHPUnit, PHPStan and php-cs-fixer at .src/ (and .tests/) where they read src/ today, as A first project shows.

Check afterwards

vendor/bin/phn check
src/AtomicCache.phn:83:20: error P2202: Amp\Cache\AtomicCache::computeIfPresent() should return TValue but returns null
   83 |             return null;
      |                    ^^^^
…
src/PrefixCache.phn:19:32: error P2202: Amp\Cache\PrefixCache::get() should return TValue|null but returns mixed
   19 |     get(string $key): mixed => $this->cache->get($this->keyPrefix . $key);
      |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
…
9 files checked: 30 errors, 0 warnings

Thirty errors, in four files, 25 of them in one. Migrate does not change what the code does, so these were there before: the checker reports what PHPStan reports at level max, and PHPStan at level max finds 34 in the original sources, of the same kinds. A project that already passes PHPStan at level max starts close to clean; one that does not meets that standard now.

While a .phn has errors, phn build does not write its output, and the Composer plugin's build fails the autoload dump:

> phn build
…
4 of 9 files failed to compile

phn build --emit-on-error writes every output all the same and still exits with status 1, so that a project can run while it fixes the findings. The usual way is smaller steps.

A directory at a time

Migrate takes paths, and a root may hold .phn and .php files side by side: phn build compiles the one and copies the other. So a project moves over a directory, or a file, at a time. Here, three files of the library:

vendor/bin/phn migrate --php 8.5 src/PrefixCache.php src/NullCache.php src/StringCacheAdapter.php
…
3 files migrated, 0 skipped, 0 .phn files updated, 0 docblock tags kept
0 @throws lifted, 8 bodies written as =>, 2 braces moved up, 0 class braces moved down, 2 empty bodies written as {}, 2 docblocks collapsed; 117 lines became 71
0 chains as pipelines, 0 left as calls

One of them has the finding seen above: PrefixCache holds a Cache without saying of what, so its get() returns mixed where the interface promises TValue|null. The fix is the type argument, in the constructor:

private readonly Cache<TValue> $cache,

Leave the files not yet migrated out of the check with "exclude", and the project checks clean:

phaenon.json
{
    "roots": {"src": ".src"},
    "exclude": ["src/AtomicCache.php", "src/LocalCache.php", "src/SerializedCache.php"],
    "php": "8.5"
}
vendor/bin/phn check
composer dump-autoload
6 files checked: 0 errors, 0 warnings
Generating autoload files
> phn build
3 files compiled, 3 written, 6 files copied, 0 stale outputs removed
Generated autoload files

Three classes compiled, six copied as they were, and the autoloader serves all nine from .src/.

Options

OptionEffect
--php X.YWrites the target into phaenon.json, creating the file if needed
--list-typesTypes bare arrays as lists and maps from the values they hold
--keep-docblocksLeaves generic docblocks as they are: no tag is lifted
--keep-publicKeeps the public of a method lifted out of function, of a constant, and before private(set)
--keep-layoutKeeps braces, docblocks and bodies as they are
--keep-callsKeeps nested calls as they are: no pipelines
--pipes=NWrites chains of N nested calls or more as pipelines (2 or more; 3 by default)

phn fmt lays out the files later edits leave out of shape; Formatting and fixers covers it, and The phn command lists every command.