concept-image / php-file-editor
Edit PHP source files as text without breaking their layout: PhpToken navigation, class name resolution and Pint-ordered imports, array literal appends. Pure PHP, no framework.
Package info
gitlab.com/concept-image-public/php-file-editor
pkg:composer/concept-image/php-file-editor
Requires
- php: >=8.3
Requires (Dev)
- laravel/pint: ^1.18
- pestphp/pest: ^4.0|^5.0
- pestphp/pest-plugin-arch: ^4.0|^5.0
- phpstan/phpstan: ^2.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Edit PHP source files without breaking their layout
concept-image/php-file-editor edits PHP source files as text. It locates code with PHP's
tokenizer (PhpToken) and inserts text at the right offset, so the file keeps its comments, indentation and order:
append an item to an array literal, add a use import in Pint's order, insert lines before a statement.
It is the shared engine of the Concept Image code generators (wp-acorn-stubs, wp-make-block, wp-make-cpt). Pure PHP, no framework dependency.
Requirements
- PHP 8.3+
Installation
composer require concept-image/php-file-editor
Usage
Every class is immutable: an edit returns a new PhpFile, written with write().
use ConceptImage\PhpFileEditor\PhpFile;
use ConceptImage\PhpFileEditor\PhpNames;
$file = PhpFile::fromFile($path);
// Import the class when its short name is free (else the alias or the fully qualified name), then append it.
[$file, $name] = (new PhpNames($file))->import('App\Hooks\Seo');
$equals = $file->followedBy($file->find('$hooks')[0], ['=']); // `$hooks =`
$hooks = $equals === null ? null : $file->arrayAfter($equals);
$hooks?->append($name.'::class')->write($path);
// config file: return ['blocks_to_register' => ['base' => [...]]]
$base = $file->arrayAfter($file->find(T_RETURN)[0])?->valueOf('blocks_to_register')?->valueOf('base');
if ($base !== null && ! in_array('base-quote', $base->strings(), true)) {
$base->append("'base-quote'")->write($path);
}
// Lines before a statement, indented like it.
$file->insertLinesBefore($returnIndex, "\$group\n ->addText('title');\n")->write($path);
// Calls appended to the `$variable->method(…)…;` chain ending at a `;`, indented like its first `->`.
$end = $file->previous($returnIndex); // the `;` before `return $group->build();`
$start = $file->chainStart($end); // `$group`, or null when it isn't a chain
if ($start !== null && $file->token($start)->text === '$group') {
$file->appendToChain($end, "->addText('subtitle', [\n 'label' => 'Subtitle',\n])")?->write($path);
}
// Names appended to a property array, once: protected array $fields = ['title'];
$equals = $file->followedBy($file->find('$fields')[0], ['=']);
$fields = $equals === null ? null : $file->arrayAfter($equals);
if ($fields !== null && ! in_array('subtitle', $fields->strings(), true)) {
$fields->append("'subtitle'")->write($path);
}
PhpFile
| Method | Returns |
|---|---|
fromString($code), fromFile($path), write($path) | Build from code or a file, write to a file (RuntimeException when it can't) |
$code, $tokens, token($i) | The code, the PhpToken list, one token |
find($kind) | Indices of the tokens of a kind: id (T_RETURN), text ('$hooks') or a list |
next($i), previous($i) | The next / previous significant token (whitespace and comments skipped) |
followedBy($i, ['->', 'build', '(']) | Index of the last token when the next significant ones have these texts (case-insensitive) |
matching($open) | Index of the bracket closing (, [ or { |
isName($i), stringValue($i) | Whether a token is a class name; the value of a quoted string literal |
statementStart($end) | First token of the statement ending at the ; at $end |
chainStart($end) | The variable starting the statement ending at the ; at $end when it is a method chain ($group->add(…)…;), or null |
appendToChain($end, $calls) | A new file with the ->call(…) lines appended before that ;, indented like the chain's first -> (+ INDENT when it is on the variable's line), or null |
arrayAfter($i) | The [...] array literal right after a token (ArrayRange), or null |
functionBodies($name) | The {...} bodies of the functions/methods with this name |
lineStart($offset), indentation($offset), PhpFile::indent($code, $indentation) | Line and indentation helpers |
insert($offset, $text), insertLinesBefore($i, $code) | A new file with text inserted |
ArrayRange
isEmpty() (comments only count as empty), valueOf('key') (the [...] value of a string key), strings() (the
string literals written directly in the array) and append($item, $inline = null): on its own line, indented like the
last item, with a trailing comma (a missing one is added after the last item); , $inline in an inline array; an
empty inline array is opened over several lines.
PhpNames
namespace(), imports() (alias ⇒ class: aliases, group imports, imported namespaces), declaredClasses(),
resolve($name), classReferences($from, $to) (X::class and class-like strings, resolved), aliasOf($class),
usesName($short), importInsertion($class) and import($class) (the file with use added in Pint's
ordered_imports order, and the name to write).
Testing
composer ci
Pint, PHPStan (level max) and Pest. Without PHP on the host:
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app -w /app composer:2 composer ci.
Changelog
See CHANGELOG.md.
Credits
- Banner icon: Register icons created by Magnific - Flaticon
License
The MIT License (MIT). See LICENSE.md.