Search by

concept-image / php-file-editor

concept-image

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

Issues

pkg:composer/concept-image/php-file-editor

Statistics

Installs: 26

Dependents: 3

Suggesters: 0

Stars: 0

0.2.0 2026-12-03 11:24 UTC

This package is auto-updated.

Last update: 2026-12-03 10:25:06 UTC


README

PHP File Editor

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

MethodReturns
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

License

The MIT License (MIT). See LICENSE.md.