northrook / php-generator
PHP code generation
Requires
- php: >=8.5
- northrook/hashes: dev-main
Requires (Dev)
- northrook/error-handler: dev-main
- northrook/php-cs: dev-main
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^13
This package is auto-updated.
Last update: 2026-08-27 07:08:51 UTC
README
Emit PHP source files: open tag, strict types, optional banner, namespace, sorted use statements, and a body.
saveToFile() writes atomically (temp file + rename).
Requires PHP >=8.5 and northrook/hashes.
Installation
composer require northrook/php-generator
Quick start
use Northrook\PhpGenerator\PhpFile;
$file = new PhpFile();
$file->set(namespace: 'App\\Config');
$file->banner
->timestamp('1700000000') // pin for stable output; omit → current time
->line('Generated config')
->list('source: build', 'format: php');
$file->useStatements->add('App\\Helper');
$file->setReturnValue(['enabled' => true]);
$file->saveToFile($path); // or $file->generate()
Section order in the emitted file:
<?php
declare(strict_types=1);
/*%1700000000%---
…
---#xxxxxxxx#--*/
namespace App\Config;
use App\Helper;
return array (
'enabled' => true,
);
Knobs
Defaults: openTag and strict on, closeTag off.
set(...) — null leaves a field unchanged; false clears namespace or fileComment.
fileComment sits on the opening line as <?php // ….
setBodyCode() sets raw PHP. PhpFile::setReturnValue() exports the value as return …;. Default exporter prefers (if already loaded) Northrook\Contracts\Export::value, then Symfony VarExporter::export, else var_export. Pass a callable(mixed): string as the second argument to override.
Banner
Emitted only when it has content lines — timestamp or fingerprint alone is not enough.
fingerprint() accepts an external alphanumeric token (framework convention: Crockford checksum from Hash::checksum($body)).
generate() auto-fingerprints the body with Hash::checksum() when a banner has content, no fingerprint is set, and a body is present.
setBodyCode() clears the fingerprint so the next generate refreshes it.
Pin timestamp() for reproducible files — int/string are opaque labels embedded as-is; DateTimeInterface converts to unix seconds.
Use statements
$generator->useStatements:
add()/constants()/functions()— validated FQCNs, no leading\freeform()— aliases, brace groups, etc. (unvalidated; stored betweenuseand;)
Emitted sorted alphabetically.
Trust boundary
Metadata (file comment, banner text, namespace, validated uses) rejects comment breakouts and invalid identifiers.
setBodyCode() and freeform() are trusted and written as-is.
Development
composer test
composer phpstan
License
BSD-3-Clause. See LICENSE.