PHPackages                             pixielity/stub-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. pixielity/stub-generator

ActiveLibrary[Templating &amp; Views](/categories/templating)

pixielity/stub-generator
========================

A powerful, fluent stub template processor for PHP with support for placeholders and optional sections

v1.0.1(3mo ago)066[2 PRs](https://github.com/pixielity-inc/stub-generator/pulls)1MITPHPPHP ^8.4CI passing

Since Feb 12Pushed 3mo agoCompare

[ Source](https://github.com/pixielity-inc/stub-generator)[ Packagist](https://packagist.org/packages/pixielity/stub-generator)[ Docs](https://github.com/pixielity-co/stub-generator)[ RSS](/packages/pixielity-stub-generator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (7)Versions (5)Used By (1)

[![Stub Generator Banner](.github/assets/banner.svg)](.github/assets/banner.svg)

Stub Generator
==============

[](#stub-generator)

**A powerful, fluent stub template processor for PHP with support for placeholders and optional sections**

[![PHP Version](https://camo.githubusercontent.com/51482859d8bb7cd31d259f58cf02b8eb7e56c51ad36c462afa3484f3b7a8fc2c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e342532422d3737374242343f7374796c653d666c61742d737175617265266c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://www.php.net/)[![Packagist Version](https://camo.githubusercontent.com/01c4fdafd8fc477bf17619255f5c96d98969b61d194d94606c2e580660366fc5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70697869656c6974792f737475622d67656e657261746f723f7374796c653d666c61742d737175617265266c6f676f3d7061636b6167697374266c6f676f436f6c6f723d7768697465)](https://packagist.org/packages/pixielity/stub-generator)[![Downloads](https://camo.githubusercontent.com/3f77414afb4f8869ad80c7e797cff675049ee59f2e0a53ced22f27dcc38ad92d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f70697869656c6974792f737475622d67656e657261746f723f7374796c653d666c61742d737175617265266c6f676f3d7061636b6167697374266c6f676f436f6c6f723d7768697465266c6162656c3d646f776e6c6f616473)](https://packagist.org/packages/pixielity/stub-generator)[![License](https://camo.githubusercontent.com/152aa2a37725b9fd554b28ff24d270f6071c67927a63e6d635a55c8e188e20c7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e3f7374796c653d666c61742d737175617265)](LICENSE)[![Tests](https://camo.githubusercontent.com/42acdb406b5265f5e7c976d9bd1ccb2568ad3a85e18e1bf57983e50366d85834/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d70617373696e672d737563636573733f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974266c6f676f436f6c6f723d7768697465)](https://github.com/pixielity-co/stub-generator/actions)

[Features](#-features) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Documentation](#-documentation) • [API Reference](#-api-reference)

---

🎯 What is Stub Generator?
-------------------------

[](#-what-is-stub-generator)

Stub Generator is a lightweight, zero-dependency PHP library for processing template files (stubs) with placeholder replacement and optional sections. Inspired by Laravel Modules' Stub class, it provides a fluent, chainable API for generating files from templates.

### Why Stub Generator?

[](#why-stub-generator)

- **🚀 Zero Dependencies** - Pure PHP, no external dependencies required
- **⚡ Fluent API** - Chainable methods for elegant code
- **🎯 Simple &amp; Powerful** - Easy to use, yet feature-rich
- **💎 Laravel-Style** - Familiar API for Laravel developers
- **🔧 Flexible** - Supports multiple placeholder formats
- **📦 Lightweight** - Minimal footprint, maximum performance

---

✨ Features
----------

[](#-features)

### Core Features

[](#core-features)

- **Fluent Interface** - Chainable methods for better developer experience
- **Placeholder Replacement** - Replace `$PLACEHOLDER$` or `{{PLACEHOLDER}}` with values
- **Optional Sections** - Remove optional sections based on conditions
- **File Operations** - Read templates and save processed content
- **Custom Base Path** - Support for custom stub directories
- **Magic Methods** - Use stub object directly as string

### Developer Experience

[](#developer-experience)

- **Automatic Uppercase** - Keys automatically converted to UPPERCASE
- **Backward Compatible** - Supports both `$KEY$` and `{{KEY}}` formats
- **Clear Exceptions** - Helpful error messages with context
- **Well Documented** - Comprehensive docblocks and examples
- **Type Safe** - Full PHP 8.4 type declarations

---

📦 Installation
--------------

[](#-installation)

### Requirements

[](#requirements)

- **PHP**: 8.4 or higher

### Via Composer

[](#via-composer)

```
composer require pixielity/stub-generator
```

---

⚡ Quick Start
-------------

[](#-quick-start)

### 1. Basic Usage

[](#1-basic-usage)

```
use Pixielity\StubGenerator\StubGenerator;

// Create and render a stub
$content = StubGenerator::create('template.stub', [
    'name' => 'John Doe',
    'email' => 'john@example.com',
])->render();

echo $content;
```

### 2. Save to File

[](#2-save-to-file)

```
// Generate and save to file
StubGenerator::create('docker/redis.yml', [
    'container_prefix' => 'myapp',
    'redis_port' => '6379',
])->saveTo('/path/to/output', 'docker-compose.yml');
```

### 3. Remove Optional Sections

[](#3-remove-optional-sections)

```
// Remove optional sections
$content = StubGenerator::create('docker/elasticsearch.yml', [
    'elasticsearch_password' => 'secret',
])
->removeSection('kibana')  // Remove Kibana section
->render();
```

### 4. Chainable API

[](#4-chainable-api)

```
// Chain multiple operations
$stub = StubGenerator::create('template.stub')
    ->replace(['key1' => 'value1'])
    ->replace(['key2' => 'value2'])
    ->removeSection('optional')
    ->render();
```

---

📚 Documentation
---------------

[](#-documentation)

### Placeholder Format

[](#placeholder-format)

Stub Generator supports two placeholder formats:

#### Primary Format (Recommended)

[](#primary-format-recommended)

```
$PLACEHOLDER_NAME$

```

#### Legacy Format (Backward Compatibility)

[](#legacy-format-backward-compatibility)

```
{{PLACEHOLDER_NAME}}

```

### Example Template

[](#example-template)

```
# template.yml
container_name: "$CONTAINER_PREFIX$-redis"
ports:
  - "$REDIS_PORT$:6379"
environment:
  REDIS_PASSWORD: "$REDIS_PASSWORD$"
```

### Usage

[](#usage)

```
$content = StubGenerator::create('template.yml', [
    'container_prefix' => 'myapp',  // Auto-converted to $CONTAINER_PREFIX$
    'redis_port' => '6379',         // Auto-converted to $REDIS_PORT$
    'redis_password' => 'secret',   // Auto-converted to $REDIS_PASSWORD$
])->render();
```

### Optional Sections

[](#optional-sections)

Mark optional sections in your templates:

```
services:
  elasticsearch:
    image: elasticsearch:8.11.0

  # SECTION:kibana
  kibana:
    image: kibana:8.11.0
    depends_on:
      - elasticsearch
  # END_SECTION:kibana
```

Remove sections programmatically:

```
// Include Kibana
$withKibana = StubGenerator::create('elasticsearch.yml', [...])->render();

// Exclude Kibana
$withoutKibana = StubGenerator::create('elasticsearch.yml', [...])
    ->removeSection('kibana')
    ->render();
```

---

🎮 API Reference
---------------

[](#-api-reference)

### Static Factory Method

[](#static-factory-method)

```
/**
 * Create a new stub generator instance.
 *
 * @param  string $path     Relative path to stub file
 * @param  array  $replaces Placeholder replacements
 * @return self
 */
public static function create(string $path, array $replaces = []): self
```

### Instance Methods

[](#instance-methods)

```
/**
 * Set or merge placeholder replacements.
 *
 * @param  array $replaces Placeholder replacements
 * @return self
 */
public function replace(array $replaces): self

/**
 * Remove an optional section from the template.
 *
 * @param  string $name Section name
 * @return self
 */
public function removeSection(string $name): self

/**
 * Render the stub with all replacements applied.
 *
 * @return string Processed content
 */
public function render(): string

/**
 * Alias for render().
 *
 * @return string Processed content
 */
public function getContents(): string

/**
 * Render and save to file.
 *
 * @param  string $path     Directory path
 * @param  string $filename File name
 * @return bool Success status
 */
public function saveTo(string $path, string $filename): bool

/**
 * Set custom base path for stubs.
 *
 * @param  string $path Base path
 * @return void
 */
public static function setBasePath(string $path): void

/**
 * Get current base path.
 *
 * @return string|null Base path
 */
public static function getBasePath(): ?string

/**
 * Magic method to convert stub to string.
 *
 * @return string Processed content
 */
public function __toString(): string
```

---

🏗️ Advanced Usage
-----------------

[](#️-advanced-usage)

### Custom Base Path

[](#custom-base-path)

```
// Set custom stub directory
StubGenerator::setBasePath('/custom/stubs/path');

// Now all stubs are loaded from custom path
$content = StubGenerator::create('template.stub', [...])->render();

// Reset to default
StubGenerator::setBasePath(null);
```

### Multiple Sections

[](#multiple-sections)

```
// Remove multiple sections
$content = StubGenerator::create('template.stub', [...])
    ->removeSection('section1')
    ->removeSection('section2')
    ->removeSection('section3')
    ->render();
```

### Direct String Conversion

[](#direct-string-conversion)

```
// Use __toString() magic method
$stub = StubGenerator::create('template.stub', [...]);
echo $stub;  // Automatically calls render()
```

---

🧪 Testing
---------

[](#-testing)

```
# Run tests
composer test

# Run tests with coverage
composer test:coverage

# Run all quality checks
composer check
```

---

🤝 Contributing
--------------

[](#-contributing)

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

### Quick Contribution Guide

[](#quick-contribution-guide)

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run quality checks (`composer check`)
5. Commit your changes (`git commit -m 'feat: add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request

---

📄 License
---------

[](#-license)

Stub Generator is open-sourced software licensed under the [MIT license](LICENSE).

---

🙏 Credits
---------

[](#-credits)

Inspired by:

- [Laravel Modules](https://github.com/nWidart/laravel-modules) - Original Stub class design
- [Laravel](https://laravel.com/) - Fluent API patterns

---

📞 Support
---------

[](#-support)

- **Documentation**: [GitHub README](https://github.com/pixielity-co/stub-generator#readme)
- **Issues**: [GitHub Issues](https://github.com/pixielity-co/stub-generator/issues)
- **Packagist**: [pixielity/stub-generator](https://packagist.org/packages/pixielity/stub-generator)

---

Made with ❤️ by the Pixielity team

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance82

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

96d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/097bcf744614fce2b94aae3463aaa5d875496df7dcf0c1a825f83f88a62bf618?d=identicon)[pixielity](/maintainers/pixielity)

---

Top Contributors

[![abdokouta](https://avatars.githubusercontent.com/u/12934929?v=4)](https://github.com/abdokouta "abdokouta (16 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

phpscaffoldingstubgeneratortemplatecode-generationplaceholder

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/pixielity-stub-generator/health.svg)

```
[![Health](https://phpackages.com/badges/pixielity-stub-generator/health.svg)](https://phpackages.com/packages/pixielity-stub-generator)
```

###  Alternatives

[anourvalar/office

Generate documents from existing Excel &amp; Word templates | Export tables to Excel (Grids)

24085.2k](/packages/anourvalar-office)[tomatophp/filament-plugins

Manage your modules as a plugin system with plugin generator

644.7k2](/packages/tomatophp-filament-plugins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
