northrook/php-generator

PHP code generation

Maintainers

Package info

codeberg.org/northrook/php-generator

Issues

pkg:composer/northrook/php-generator

Transparency log

Statistics

Installs: 20

Dependents: 3

Suggesters: 0

dev-main 2026-08-12 10:22 UTC

This package is auto-updated.

Last update: 2026-08-12 09:22:34 UTC


README

Emit PHP source files: open tag, strict types, optional banner, namespace, sorted use statements, and a body.

Write atomically through an injected FilesystemInterface.

Requires PHP >=8.5, northrook/core-contracts, northrook/hashes, and symfony/var-exporter (for PhpFile).

Inject any FilesystemInterface implementation.

Installation

composer require northrook/php-generator

Quick start

use Northrook\PhpGenerator\PhpFile;

$file = new PhpFile($filesystem); // Northrook\Contracts\FilesystemInterface
$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 [
    '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() wraps the value with VarExporter::export as return …;.

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; Timestamp/DateTimeInterface convert to unix seconds.

Use statements

$generator->useStatements:

  • add() / constants() / functions() — validated FQCNs, no leading \
  • freeform() — aliases, brace groups, etc. (unvalidated; stored between use and ;)

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.