PHP code example of alex-kassel / stub-engine

1. Go to this page and download the library: Download alex-kassel/stub-engine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

alex-kassel / stub-engine example snippets


use AlexKassel\StubEngine\Facades\StubEngine;

$result = StubEngine::from(__DIR__ . '/../stubs/runner.stub')
    ->to(base_path('bin/my-tool'))
    ->withTokens([
        '{{ runnerName }}' => 'my-tool',
        '{{ manifestPath }}' => 'tool.json',
    ])
    ->override(base_path('stubs/runner.stub')) // Optional host override
    ->force(false) // Skip if target file already exists
    ->scaffold();

if ($result->renderedFiles !== []) {
    echo "Standalone runner created at bin/my-tool!";
}

use AlexKassel\StubEngine\DTOs\ScaffoldRequest;
use AlexKassel\StubEngine\Facades\StubEngine;

$compiled = StubEngine::renderFile(new ScaffoldRequest(
    source: __DIR__ . '/../stubs/config.stub',
    tokens: [
        '{{ appName }}' => 'My Application',
    ],
    override: base_path('stubs/config.stub'),
));

use AlexKassel\StubEngine\Facades\StubEngine;

$result = StubEngine::from(__DIR__ . '/../stubs')
    ->to(base_path('packages/acme/my-tool'))
    ->withTokens([
        '{{ vendor }}' => 'acme',
        '{{ package }}' => 'my-tool',
        '{{ ClassName }}' => 'MyTool',
    ])
    ->override(base_path('stubs/my-generator'))
    ->scaffold();

echo "Rendered " . count($result->renderedFiles) . " files into {$result->request->target}!";

namespace Acme\Generator\Console;

use AlexKassel\StubEngine\StubEngine;
use Illuminate\Console\Command;

class MakeModuleCommand extends Command
{
    protected $signature = 'make:module {name}';

    public function __construct(
        protected readonly StubEngine $engine,
    ) {
        parent::__construct();
    }

    public function handle(): int
    {
        $name = trim((string) $this->argument('name'));

        $result = $this->engine->from(dirname(__DIR__, 2) . '/stubs')
            ->to(app_path("Modules/{$name}"))
            ->withTokens([
                '{{ moduleName }}' => $name,
                '{{ namespace }}' => "App\\Modules\\{$name}",
            ])
            ->override(base_path('stubs/modules'))
            ->scaffold();

        $source = $result->overrideFiles !== [] ? 'custom host stubs' : 'default stubs';
        $count = count($result->renderedFiles);
        $this->info("Module [{$name}] scaffolded successfully using {$source} ({$count} files).");

        return self::SUCCESS;
    }
}

return [
    /*
    |--------------------------------------------------------------------------
    | Token Delimiters
    |--------------------------------------------------------------------------
    | Customize delimiters to avoid syntax collisions with Blade ({{ $var }}),
    | Vue, Jinja, or bash scripts.
    */
    'delimiters' => [
        'open' => env('STUB_ENGINE_OPEN_DELIMITER', '{{'),
        'close' => env('STUB_ENGINE_CLOSE_DELIMITER', '}}'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Global Tokens
    |--------------------------------------------------------------------------
    | Shared tokens merged automatically into every scaffolding operation.
    */
    'global_tokens' => [
        'company' => env('STUB_ENGINE_COMPANY_NAME', 'Acme Corp'),
        'year' => date('Y'),
    ],
];

use AlexKassel\StubEngine\Enums\OverrideStrategy;
use AlexKassel\StubEngine\Facades\StubEngine;

// Strategy A: Overlay (Default cascading merge)
// If the override directory contains 1 file out of 10, the other 9 package defaults are preserved.
$result = StubEngine::from(__DIR__ . '/../stubs')
    ->to(base_path('app/Modules/Billing'))
    ->withTokens(['name' => 'Billing'])
    ->override(base_path('stubs/modules'))
    ->scaffold();

// Strategy B: Replace ("All-or-Nothing" complete substitution)
// Ideal for document packages or custom suites where the consumer directory completely replaces the default layout.
$docResult = StubEngine::from(__DIR__ . '/../sample_docs')
    ->to(storage_path('app/client_docs'))
    ->withTokens(['client' => 'Globex'])
    ->override(base_path('stubs/client_docs'), OverrideStrategy::Replace)
    ->scaffold();

$result = StubEngine::from(__DIR__ . '/../blade_stubs')
    ->to(resource_path('views/modules/billing'))
    ->withTokens(['entity' => 'user profile'])
    ->delimiters('<%', '%>')
    ->scaffold();

$result = StubEngine::from(__DIR__ . '/../stubs')
    ->to(base_path('app/Modules/Billing'))
    ->withTokens([
        'entity' => 'user profile',
    ])
    ->scaffold();

use AlexKassel\StubEngine\Facades\StubEngine;

StubEngine::registerModifier('slug', fn (string $val): string => \Illuminate\Support\Str::slug($val));
StubEngine::registerModifier('shout', fn (string $val): string => strtoupper($val) . '!!!');

// In stubs: {{ title|slug }} or {{ alert|shout }}

// 1. Strict scaffolding (fails fast if any placeholder is missing)
try {
    StubEngine::from(__DIR__ . '/../stubs')
        ->to(app_path('Modules/Billing'))
        ->withTokens(['name' => 'Billing'])
        ->strict() // Throws InvalidArgumentException on unresolved tokens
        ->scaffold();
} catch (\InvalidArgumentException $e) {
    // Gracefully report missing inputs to CLI user
}

// 2. Direct token diagnostics on raw strings using StubEngine or Interpolator
$tokens = StubEngine::extractTokens($content);
// Returns: ['missing_token', 'other']

$result = StubEngine::from(__DIR__ . '/../stubs')
    ->to(base_path('packages/acme/my-tool'))
    ->withTokens(['name' => 'MyTool'])
    ->override(base_path('stubs/custom'))
    ->force(false) // Skip existing files
    ->dryRun(true) // Preview changes without writing to disk
    ->scaffold();

// Count of rendered files
echo count($result->renderedFiles);

// Detailed file categorizations
$created     = $result->createdFiles;     // ['src/MyTool.php']
$overwritten = $result->overwrittenFiles; // []
$skipped     = $result->skippedFiles;     // ['composer.json']
$overridden  = $result->overrideFiles;    // ['src/MyTool.php']
$rendered    = $result->renderedFiles;    // ['src/MyTool.php']

// Direct status checks
if ($result->overrideFiles !== []) {
    echo "Custom host stubs were utilized!";
}

if ($result->skippedFiles !== []) {
    echo "Some files already existed and were protected from overwriting.";
}

public function from(string $source): ScaffoldBuilder

public function renderFile(ScaffoldRequest $request): string

public function scaffold(ScaffoldRequest $request): ScaffoldResult

public function registerModifier(string $name, callable $callback): self

public function extractTokens(
    string $content,
    ?string $open = null,
    ?string $close = null,
): array

my-package/stubs/
├── composer.json.stub
├── src/
│   └── {{ ClassName }}.php.stub
└── tests/
    └── {{ ClassName }}Test.php.stub
bash
php artisan vendor:publish --tag=stub-engine-config