A laravel package to generate class files from stub files.

Overview

Laravel Stub Generator

A php laravel package to generate useable php files from given stub files .

Installation

Require the package using composer:

composer require touhidurabir/laravel-stub-generator

Usage

The best approach to use this via the facade as

use Touhidurabir\StubGenerator\Facades\StubGenerator

and then implement as follow

StubGenerator::from('some/path/to/stub/file.stub') // the stub file path
    ->to('some/path/to/store/generated/file') // the store directory path
    ->as('TheGeneratingFileNameItself') // the generatable file name without extension 
    ->withReplacers([]) // the stub replacing params
    ->save(); // save the file

Also possible to get the generated content as string or download the generated file

StubGenerator::from('path')->to('path')->as('name')->withReplacers([])->toString(); // get generated content
StubGenerator::from('path')->as('name')->withReplacers([])->download(); // download the file

By default it assume all the given path for from and to methods are relative path, but it can also work with absolute path by specifying that.

StubGenerator::from('some/path/to/stub/file.stub', true) // the second argument **true** specify absolute path
    ->to('some/path/to/store/generated/file', false, true) // the third argument **true** specify absolute path
    ->as('TheGeneratingFileNameItself') 
    ->withReplacers([]) 
    ->save();

Also if the store directory path does not exists, it can create that target store path if that is specified in the method call.

StubGenerator::from('some/path/to/stub/file.stub', true)
    ->to('some/path/to/store/generated/file', true, true) // the second argument **true** specify to generated path if not exists
    ->as('TheGeneratingFileNameItself')
    ->withReplacers([])
    ->save();

If the saved generated file aleady exists, it is also possible to replace that with the newly generated one if that is specified via the replace method.

StubGenerator::from('some/path/to/stub/file.stub') // the stub file path
    ->to('some/path/to/store/generated/file') // the store directory path
    ->as('TheGeneratingFileNameItself') // the generatable file name without extension 
    ->withReplacers([]) // the stub replacing params
    ->replace(true) // instruct to replace if already exists at the give path
    ->save(); // save the file

One important thing to note that this package can handle not just string type values to but also hanlde array and boolean type also. So basically it can do as :

->withReplacers([
    'replacer_1' = 'some value',
    'replacer_2' = ['some', 'more', 'values'],
    'replacer_3' = true,
])  

Example

Considering the following stub file

 ${{modelInstance}}
     * @return void
     */
    public function __construct({{model}} ${{modelInstance}}) {

        $this->model = ${{modelInstance}};

        $this->modelClass = get_class(${{modelInstance}});
    }

}

If the stub file stored at the location of app/stubs/repository.stub and we want to create a new repository file named UserRepository.php at the path app/Repositories/, then

StubGeneratorFacade::from('/app/stubs/repository.stub')
    ->to('/app/Repositories', true)
    ->as('UserRepository')
    ->withReplacers([
        'class'             => 'UserRepository',
        'model'             => 'User',
        'modelInstance'     => 'user',
        'modelNamespace'    => 'App\\Models',
        'baseClass'         => 'Touhidurabir\\ModelRepository\\BaseRepository',
        'baseClassName'     => 'BaseRepository',
        'classNamespace'    => 'App\\Repositories',
    ])
    ->save();

will generate such file content of UserRepository.php



namespace App\Repositories;

use Touhidurabir\ModelRepository\BaseRepository;
use App\Models\User;

class UserRepository extends BaseRepository {

	/**
     * Constructor to bind model to repo
     *
     * @param  object
    
      $user
    
     * @return void
     */
    public function __construct(User $user) {

        $this->model = $user;

        $this->modelClass = get_class($user);
    }

}

Extras

Sometimes what we have is the namespace that follows the psr-4 standeard and that namespace path is what we intend to use for path. This package can not direcly work with the namespace path and it includes a handy trait that can help up to some extent.

To use the trait

use Touhidurabir\StubGenerator\Concerns\NamespaceResolver;

class Someclass {

    use NamespaceResolver;
}

Available Methods of NamespaceResolver

resolveClassName(string $name)

As per defination

/**
 * Resolve the class name and class store path from give class namespace
 * In case a full class namespace provides, need to extract class name
 *
 * @param  string $name
 * @return string
 */
public function resolveClassName(string $name)

It extract the class name from given full class namespace.

resolveClassNamespace(string $name)

As per defination

/**
 * Resolve the class namespace from given class name
 *
 * @param  string $name
 * @return mixed
   
 */
public function resolveClassNamespace(string $name)

It extract the class namespace only from given full class namespace.

generateFilePathFromNamespace(string $namespace = null)

As per defination

/**
 * Generate class store path from give namespace
 *
 * @param  mixed
   
     $namespace
   
 * @return mixed
   
 */
public function generateFilePathFromNamespace(string $namespace = null)

It generate the class relative path from given class full namespace.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

You might also like...
This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords.

Laravel Otpify 🔑 Introduction Otpify is a Laravel package that provides a simple and elegant way to generate and validate one time passwords. Install

This package provides a trait that will generate a unique uuid when saving any Eloquent model.

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique uuid when saving any Eloquent model. $model = new

A simple package that helps PHP developers to generate the QR code signature as per Zakat authority (ZATCA) requirements of Saudi Arabia.

A PHP package that implements the e-invoice QR code signature requirements as designed by the Zakat authority of Saudi Arabia. How to install? compose

A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

Make any class queue aware in a Laravel app
Make any class queue aware in a Laravel app

Make any class queue aware This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. Support us We in

Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string template and recompiles it if needed.

Laravel-fly-view Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string temp

Helper class for working with Laravel Mix in WordPress themes and plugins.

Hybrid\Mix Hybrid Mix is a class for working with Lavarel Mix. It adds helper methods for quickly grabbing asset files cached in the mix-manifest.json

Comments
  • [Feature Request]: Allow for repeater placeholder

    [Feature Request]: Allow for repeater placeholder

    Feature Description

    This would be useful for classes or templates where code is being repeated and placeholders non foreseeable.

    Is this feature valuable for other users as well and why?

    No response

    opened by nicolasbinet 3
  • Fix both white spaces limitation and prepending slash

    Fix both white spaces limitation and prepending slash

    • This PR allows stub with variable written like this : {{ var1 }} {{ var2}}, {{var3 }} to be parsed.

    • This PR removes the prepending slash added ("/") on the path. This slash is not allowed on windows OS.

    opened by GENL 3
  • Support for other file types

    Support for other file types

    Feature Description

    It seems .php file extension has been hardcoded into the package. Although it seems to be able to handle other file types.hardcoded

    I wanted to know if you are open to a PR for this fix as well.

    Is this feature valuable for other users as well and why?

    Creating other file types such as yml can be useful.

    opened by amirmasoud 2
  • Support for Laravel 9 and generating file without ext

    Support for Laravel 9 and generating file without ext

    In this PR:

    • Add support for laravel 9 by bumping the illuminate/support version
    • Add a new feature to generate files without an extension like .env files.

    Tests were added accordingly.

    opened by amirmasoud 0
Releases(1.0.6)
Owner
Touhidur Rahman
Husband, father, big time documentary tv series lover and software engineer . Passionate about PHP, Laravel, Ruby on Rails, Vue.js and C/C++ . Learning Rust .
Touhidur Rahman
Generate and autoload custom Helpers, Builder Scope, Service class, Trait

laravel-make-extender Generate and autoload custom helpers, It can generate multilevel helpers in the context of the directory. Generate Service class

Limewell 30 Dec 24, 2022
Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Boilerplate code for protecting a form with proof of work. Uses javascript in the browser to generate the hashcash and PHP on the server to generate the puzzle and validate the proof of work.

Jameson Lopp 28 Dec 19, 2022
Generate trends for your models. Easily generate charts or reports.

Laravel Trend Generate trends for your models. Easily generate charts or reports. Support us Like our work? You can support us by purchasing one of ou

Flowframe 139 Dec 27, 2022
Laravel Package to generate CRUD Files using TALL Stack

tall-crud-generator Laravel Package to generate CRUD Files using TALL Stack Requirements Make sure that Livewire is installed properly on your project

AscSoftwares 75 Jan 2, 2023
A simple way to generate files from stubs.

STUBBY A simple way to generate files from stubs. Usage For example we have a stub file that looks like this: <?php namespace {{ namespace }}; use A

Prince John Santillan 4 May 12, 2022
A Laravel package that allows you to use multiple ".env" files in a precedent manner. Use ".env" files per domain (multi-tentant)!

Laravel Multi ENVs Use multiple .envs files and have a chain of precedence for the environment variables in these different .envs files. Use the .env

Allyson Silva 48 Dec 29, 2022
27Laracurl Laravel wrapper package for PHP cURL class that provides OOP interface to cURL. [10/27/2015] View Details

Laracurl Laravel cURL Wrapper for Andreas Lutro's OOP cURL Class Installation To install the package, simply add the following to your Laravel install

zjango 8 Sep 9, 2018
Laravel package to generate and to validate a UUID according to the RFC 4122 standard. Only support for version 1, 3, 4 and 5 UUID are built-in.

Laravel Uuid Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for versio

Christoph Kempen 1.7k Dec 28, 2022
A package to generate modules for a Laravel project.

Laravel Modular A package to generate modules for a Laravel project. Requirements PHP 7.4 or greater Laravel version 8 Installation Install using comp

DPTSI 5 Mar 16, 2022
The package lets you generate TypeScript interfaces from your Laravel models.

Laravel TypeScript The package lets you generate TypeScript interfaces from your Laravel models. Introduction Say you have a model which has several p

Boris Lepikhin 296 Dec 24, 2022