Commit f2511980 authored by m-wynn's avatar m-wynn

artisanコマンド名、copyrightをwinasに変更

言語対応(英語、日本語)
parent bbeca1ef
/vendor
/.env
composer.phar
composer.lock
.DS_Store
Thumbs.db
.idea
.phpunit.result.cache
\ No newline at end of file
The MIT License (MIT)
Copyright © 2024 Winas, INC. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{
"name": "infyomlabs/laravel-generator",
"type": "library",
"description": "InfyOm Laravel Generator",
"keywords": [
"laravel",
"api",
"model",
"request",
"migration",
"model",
"crud",
"repository",
"view",
"test",
"generator",
"swagger"
],
"license": "MIT",
"authors": [{
"name": "Mitul Golakiya",
"email": "me@mitul.me"
}],
"require": {
"php": "^8.1.0",
"illuminate/support": "^10.0",
"illuminate/console": "^10.0",
"laracasts/flash": "^3.2.2",
"laravelcollective/html": "^6.4",
"symfony/var-exporter": "^6.2.5"
},
"require-dev": {
"phpunit/phpunit": "^10.0.7",
"mockery/mockery": "^1.5.1",
"orchestra/testbench": "^8.0.0",
"pestphp/pest": "2.x-dev",
"pestphp/pest-plugin-laravel": "2.x-dev"
},
"autoload": {
"psr-4": {
"InfyOm\\Generator\\": "src/"
},
"files": [
"src/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"\\InfyOm\\Generator\\InfyOmGeneratorServiceProvider"
]
}
},
"funding": [{
"type": "opencollective",
"url": "https://opencollective.com/infyomlabs"
}],
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"allow-plugins": {
"pestphp/pest-plugin": true
}
}
}
<?php
return [
/*
|--------------------------------------------------------------------------
| Paths
|--------------------------------------------------------------------------
|
*/
'path' => [
'migration' => database_path('migrations/'),
'model' => app_path('Models/'),
'datatables' => app_path('DataTables/'),
'livewire_tables' => app_path('Http/Livewire/'),
'repository' => app_path('Repositories/'),
'routes' => base_path('routes/web.php'),
'api_routes' => base_path('routes/api.php'),
'request' => app_path('Http/Requests/'),
'api_request' => app_path('Http/Requests/API/'),
'controller' => app_path('Http/Controllers/'),
'api_controller' => app_path('Http/Controllers/API/'),
'api_resource' => app_path('Http/Resources/'),
'schema_files' => resource_path('model_schemas/'),
'seeder' => database_path('seeders/'),
'database_seeder' => database_path('seeders/DatabaseSeeder.php'),
'factory' => database_path('factories/'),
'view_provider' => app_path('Providers/ViewServiceProvider.php'),
'tests' => base_path('tests/'),
'repository_test' => base_path('tests/Repositories/'),
'api_test' => base_path('tests/APIs/'),
'views' => resource_path('views/'),
'menu_file' => resource_path('views/layouts/menu.blade.php'),
],
/*
|--------------------------------------------------------------------------
| Namespaces
|--------------------------------------------------------------------------
|
*/
'namespace' => [
'model' => 'App\Models',
'datatables' => 'App\DataTables',
'livewire_tables' => 'App\Http\Livewire',
'repository' => 'App\Repositories',
'controller' => 'App\Http\Controllers',
'api_controller' => 'App\Http\Controllers\API',
'api_resource' => 'App\Http\Resources',
'request' => 'App\Http\Requests',
'api_request' => 'App\Http\Requests\API',
'seeder' => 'Database\Seeders',
'factory' => 'Database\Factories',
'tests' => 'Tests',
'repository_test' => 'Tests\Repositories',
'api_test' => 'Tests\APIs',
],
/*
|--------------------------------------------------------------------------
| Templates
|--------------------------------------------------------------------------
|
*/
'templates' => 'adminlte-templates',
/*
|--------------------------------------------------------------------------
| Model extend class
|--------------------------------------------------------------------------
|
*/
'model_extend_class' => 'Illuminate\Database\Eloquent\Model',
/*
|--------------------------------------------------------------------------
| API routes prefix & version
|--------------------------------------------------------------------------
|
*/
'api_prefix' => 'api',
/*
|--------------------------------------------------------------------------
| Options
|--------------------------------------------------------------------------
|
*/
'options' => [
'soft_delete' => false,
'save_schema_file' => true,
'localized' => false,
'repository_pattern' => true,
'resources' => false,
'factory' => false,
'seeder' => false,
'swagger' => false, // generate swagger for your APIs
'tests' => false, // generate test cases for your APIs
'excluded_fields' => ['id'], // Array of columns that doesn't required while creating module
],
/*
|--------------------------------------------------------------------------
| Prefixes
|--------------------------------------------------------------------------
|
*/
'prefixes' => [
'route' => '', // e.g. admin or admin.shipping or admin.shipping.logistics
'namespace' => '', // e.g. Admin or Admin\Shipping or Admin\Shipping\Logistics
'view' => '', // e.g. admin or admin/shipping or admin/shipping/logistics
],
/*
|--------------------------------------------------------------------------
| Table Types
|
| Possible Options: blade, datatables, livewire
|--------------------------------------------------------------------------
|
*/
'tables' => 'blade',
/*
|--------------------------------------------------------------------------
| Timestamp Fields
|--------------------------------------------------------------------------
|
*/
'timestamps' => [
'enabled' => true,
'created_at' => 'created_at',
'updated_at' => 'updated_at',
'deleted_at' => 'deleted_at',
],
/*
|--------------------------------------------------------------------------
| Specify custom doctrine mappings as per your need
|--------------------------------------------------------------------------
|
*/
'from_table' => [
'doctrine_mappings' => [],
],
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
'full_name' => 'Full Name',
'email' => 'Email',
'password' => 'Password',
'confirm_password' => 'Confirm Password',
'remember_me' => 'Remember Me',
'sign_in' => 'Sign In',
'sign_out' => 'Sign out',
'register' => 'Register',
'login' => [
'title' => 'Sign in to start your session',
'forgot_password' => 'I forgot my password',
],
'registration' => [
'title' => 'Register a new membership',
'i_agree' => 'I agree to',
'terms' => 'the terms',
'have_membership' => 'I already have a membership',
],
'forgot_password' => [
'title' => 'You forgot your password? Here you can easily retrieve a new password.',
'send_pwd_reset' => 'Send Password Reset Link',
],
'reset_password' => [
'title' => 'You are only one step a way from your new password, recover your password now.',
'reset_pwd_btn' => 'Reset Password',
],
'confirm_passwords' => [
'title' => 'Please confirm your password before continuing.',
'forgot_your_password' => 'Forgot Your Password?',
],
'verify_email' => [
'title' => 'Verify Your Email Address',
'success' => 'A fresh verification link has been sent to your email address',
'notice' => 'Before proceeding, please check your email for a verification link.If you did not receive the email,',
'another_req' => 'click here to request another',
],
'emails' => [
'password' => [
'reset_link' => 'Click here to reset your password',
],
],
];
<?php
return [
'add_new' => 'Add New',
'cancel' => 'Cancel',
'create' => 'Create',
'edit' => 'Edit',
'save' => 'Save',
'delete' => 'Delete',
'detail' => 'Detail',
'back' => 'Back',
'search' => 'Search',
'export' => 'Export',
'print' => 'Print',
'reset' => 'Reset',
'reload' => 'Reload',
'action' => 'Action',
'id' => 'Id',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'deleted_at' => 'Deleted At',
'are_you_sure' => 'Are you sure?',
];
<?php
return [
'retrieved' => ':model retrieved successfully.',
'saved' => ':model saved successfully.',
'updated' => ':model updated successfully.',
'deleted' => ':model deleted successfully.',
'not_found' => ':model not found',
];
<?php
return [
'failed' => 'メールアドレス、もしくはパスワードが違います',
'throttle' => 'ログイン試行回数がしきい値を超えました。 時間をおいてログインしてください。',
'login' => 'ログインしました',
'logout' => 'ログアウトしました',
'notVerified' => 'メールが認証されていません',
'verified' => 'メールの認証に成功しました',
'alreadyVerified' => '既に認証済みのメールアドレスです',
'sendVerifyMail' => '認証メールを再送しました',
'noUser' => '入力されたメールアドレスのユーザーが存在しません',
'email' => 'メールアドレス',
'password' => 'パスワード',
'confirm_password' => 'パスワードを確認',
'sign_in' => 'ログイン',
'admin_sign_in' => '管理者ログイン',
'sign_out' => 'ログアウト',
'register' => 'ユーザー登録',
'full_name' => '氏名',
'login' => [
'forgot_password' => 'パスワードを忘れた時',
],
'forgot_password' => [
'send_pwd_reset' => 'パスワード変更リンクを送る',
],
'reset_password' => [
'title' => 'パスワードを変更',
'enter_email' => 'メールアドレスを入力してください'
],
'registration' => [
'have_membership' => '既にアカウントを持っている方はこちら'
]
];
\ No newline at end of file
<?php
return [
'add_new' => '新規追加',
'cancel' => 'キャンセル',
'create' => '作成',
'edit' => '編集',
'save' => '保存',
'delete' => '削除',
'detail' => '詳細',
'back' => '戻る',
'search' => '検索',
'export' => 'エクスポート',
'print' => '印刷',
'reset' => 'リセット',
'reload' => '再読み込み',
'action' => 'アクション',
'id' => 'ID',
'created_at' => '作成日時',
'updated_at' => '更新日時',
'deleted_at' => '削除日時',
'are_you_sure' => '本当によろしいですか?',
];
<?php
return [
'retrieved' => ':model が正常に取得されました。',
'saved' => ':model が正常に保存されました。',
'updated' => ':model が正常に更新されました。',
'deleted' => ':model が正常に削除されました。',
'not_found' => ':model が見つかりません。',
];
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_KEY" value="BckfSJCXivnK6r38GVIWUAxmbBSjTsmF"/>
</php>
</phpunit>
\ No newline at end of file
[
{
"name": "id",
"dbType": "id",
"htmlType": null,
"validations": null,
"searchable": false,
"fillable": false,
"primary": true,
"inForm": false,
"inIndex": false,
"inView": false
},
{
"name": "user_id",
"dbType": "foreignId:constrained",
"htmlType": "number",
"relation": "mt1,User,user_id,id",
"validations": "required|min:1",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "title",
"dbType": "string",
"htmlType": "text",
"validations": "required",
"searchable": true,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "body",
"dbType": "text",
"htmlType": "textarea",
"validations": "",
"searchable": true,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "is_featured",
"dbType": "boolean",
"htmlType": "boolean",
"validations": "",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "is_enabled",
"dbType": "boolean",
"htmlType": "checkbox",
"validations": "",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "published_at",
"dbType": "date",
"htmlType": "date",
"validations": "",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "password",
"dbType": "string",
"htmlType": "password",
"validations": "",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "post_type",
"dbType": "integer",
"htmlType": "radio:Blog:1,Event:2,Guest:3",
"validations": "",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "status",
"dbType": "integer",
"htmlType": "select:Draft:1,Published:2,Archived:3",
"validations": "",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "created_by",
"dbType": "unsignedBigInteger:foreign,users,id",
"htmlType": "number",
"relation": "mt1,User,user_id,id",
"validations": "required|min:1",
"searchable": false,
"fillable": true,
"primary": false,
"inForm": true,
"inIndex": true,
"inView": true
},
{
"name": "created_at",
"dbType": "timestamp",
"htmlType": null,
"validations": null,
"searchable": false,
"fillable": false,
"primary": false,
"inForm": false,
"inIndex": false,
"inView": true
},
{
"name": "updated_at",
"dbType": "timestamp",
"htmlType": null,
"validations": null,
"searchable": false,
"fillable": false,
"primary": false,
"inForm": false,
"inIndex": false,
"inView": true
}
]
<?php
namespace InfyOm\Generator\Commands\API;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\API\APIControllerGenerator;
class APIControllerGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.api:controller';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create an api controller command';
public function handle()
{
parent::handle();
/** @var APIControllerGenerator $controllerGenerator */
$controllerGenerator = app(APIControllerGenerator::class);
$controllerGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\API;
use InfyOm\Generator\Commands\BaseCommand;
class APIGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:api';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a full CRUD API for given model';
public function handle()
{
parent::handle();
$this->fireFileCreatingEvent('api');
$this->generateCommonItems();
$this->generateAPIItems();
$this->performPostActionsWithMigration();
$this->fireFileCreatedEvent('api');
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\API;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\API\APIRequestGenerator;
class APIRequestsGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.api:requests';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create an api request command';
public function handle()
{
parent::handle();
/** @var APIRequestGenerator $controllerGenerator */
$controllerGenerator = app(APIRequestGenerator::class);
$controllerGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\API;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\API\APITestGenerator;
use InfyOm\Generator\Generators\RepositoryTestGenerator;
class TestsGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.api:tests';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create tests command';
public function handle()
{
parent::handle();
/** @var RepositoryTestGenerator $repositoryTestGenerator */
$repositoryTestGenerator = app(RepositoryTestGenerator::class);
$repositoryTestGenerator->generate();
/** @var APITestGenerator $apiTestGenerator */
$apiTestGenerator = app(APITestGenerator::class);
$apiTestGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands;
class APIScaffoldGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:api_scaffold';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a full CRUD API and Scaffold for given model';
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
parent::handle();
$this->fireFileCreatingEvent('api_scaffold');
$this->generateCommonItems();
$this->generateAPIItems();
$this->generateScaffoldItems();
$this->performPostActionsWithMigration();
$this->fireFileCreatedEvent('api_scaffold');
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
This diff is collapsed.
<?php
namespace InfyOm\Generator\Commands\Common;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\MigrationGenerator;
class MigrationGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:migration';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create migration command';
public function handle()
{
parent::handle();
if ($this->option('fromTable')) {
$this->error('fromTable option is not allowed to use with migration generator');
return;
}
/** @var MigrationGenerator $migrationGenerator */
$migrationGenerator = app(MigrationGenerator::class);
$migrationGenerator->generate();
$this->performPostActionsWithMigration();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\Common;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\ModelGenerator;
class ModelGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create model command';
public function handle()
{
parent::handle();
/** @var ModelGenerator $modelGenerator */
$modelGenerator = app(ModelGenerator::class);
$modelGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\Common;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\RepositoryGenerator;
class RepositoryGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:repository';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create repository command';
public function handle()
{
parent::handle();
/** @var RepositoryGenerator $repositoryGenerator */
$repositoryGenerator = app(RepositoryGenerator::class);
$repositoryGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\Publish;
use Symfony\Component\Console\Input\InputOption;
class GeneratorPublishCommand extends PublishBaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:publish';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publishes & init api routes, base controller, base test cases traits.';
public function handle()
{
$this->updateRouteServiceProvider();
$this->publishTestCases();
$this->publishBaseController();
$repositoryPattern = config('laravel_generator.options.repository_pattern', true);
if ($repositoryPattern) {
$this->publishBaseRepository();
}
if ($this->option('localized')) {
$this->publishLocaleFiles();
}
}
private function updateRouteServiceProvider()
{
$routeServiceProviderPath = app_path('Providers'.DIRECTORY_SEPARATOR.'RouteServiceProvider.php');
if (!file_exists($routeServiceProviderPath)) {
$this->error("Route Service provider not found on $routeServiceProviderPath");
return;
}
$fileContent = g_filesystem()->getFile($routeServiceProviderPath);
$search = "Route::middleware('api')".infy_nl().str(' ')->repeat(16)."->prefix('api')";
$beforeContent = str($fileContent)->before($search);
$afterContent = str($fileContent)->after($search);
$finalContent = $beforeContent.$search.infy_nl().str(' ')->repeat(16)."->as('api.')".$afterContent;
g_filesystem()->createFile($routeServiceProviderPath, $finalContent);
}
private function publishTestCases()
{
$testsPath = config('laravel_generator.path.tests', base_path('tests/'));
$testsNameSpace = config('laravel_generator.namespace.tests', 'Tests');
$createdAtField = config('laravel_generator.timestamps.created_at', 'created_at');
$updatedAtField = config('laravel_generator.timestamps.updated_at', 'updated_at');
$templateData = view('laravel-generator::api.test.api_test_trait', [
'timestamps' => "['$createdAtField', '$updatedAtField']",
'namespacesTests' => $testsNameSpace,
])->render();
$fileName = 'ApiTestTrait.php';
if (file_exists($testsPath.$fileName) && !$this->confirmOverwrite($fileName)) {
return;
}
g_filesystem()->createFile($testsPath.$fileName, $templateData);
$this->info('ApiTestTrait created');
$testAPIsPath = config('laravel_generator.path.api_test', base_path('tests/APIs/'));
if (!file_exists($testAPIsPath)) {
g_filesystem()->createDirectoryIfNotExist($testAPIsPath);
$this->info('APIs Tests directory created');
}
$testRepositoriesPath = config('laravel_generator.path.repository_test', base_path('tests/Repositories/'));
if (!file_exists($testRepositoriesPath)) {
g_filesystem()->createDirectoryIfNotExist($testRepositoriesPath);
$this->info('Repositories Tests directory created');
}
}
private function publishBaseController()
{
$controllerPath = app_path('Http/Controllers/');
$fileName = 'AppBaseController.php';
if (file_exists($controllerPath.$fileName) && !$this->confirmOverwrite($fileName)) {
return;
}
$templateData = view('laravel-generator::stubs.app_base_controller', [
'namespaceApp' => $this->getLaravel()->getNamespace(),
'apiPrefix' => config('laravel_generator.api_prefix'),
])->render();
g_filesystem()->createFile($controllerPath.$fileName, $templateData);
$this->info('AppBaseController created');
}
private function publishBaseRepository()
{
$repositoryPath = app_path('Repositories/');
$fileName = 'BaseRepository.php';
if (file_exists($repositoryPath.$fileName) && !$this->confirmOverwrite($fileName)) {
return;
}
g_filesystem()->createDirectoryIfNotExist($repositoryPath);
$templateData = view('laravel-generator::stubs.base_repository', [
'namespaceApp' => $this->getLaravel()->getNamespace(),
])->render();
g_filesystem()->createFile($repositoryPath.$fileName, $templateData);
$this->info('BaseRepository created');
}
private function publishLocaleFiles()
{
$localesDir = __DIR__.'/../../../locale/';
$this->publishDirectory($localesDir, lang_path(), 'lang', true);
$this->comment('Locale files published');
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return [
['localized', null, InputOption::VALUE_NONE, 'Localize files.'],
];
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
}
<?php
namespace InfyOm\Generator\Commands\Publish;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class PublishBaseCommand extends Command
{
public function handle()
{
// Do Nothing
}
public function publishFile($sourceFile, $destinationFile, $fileName)
{
if (file_exists($destinationFile) && !$this->confirmOverwrite($destinationFile)) {
return;
}
copy($sourceFile, $destinationFile);
$this->comment($fileName.' published');
$this->info($destinationFile);
}
public function publishDirectory(string $sourceDir, string $destinationDir, string $dirName, bool $force = false): bool
{
if (file_exists($destinationDir) && !$force && !$this->confirmOverwrite($destinationDir)) {
return false;
}
File::makeDirectory($destinationDir, 493, true, true);
File::copyDirectory($sourceDir, $destinationDir);
$this->comment($dirName.' published');
$this->info($destinationDir);
return true;
}
protected function confirmOverwrite(string $fileName, string $prompt = ''): bool
{
$prompt = (empty($prompt))
? $fileName.' already exists. Do you want to overwrite it? [y|N]'
: $prompt;
return $this->confirm($prompt, false);
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return [];
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
}
<?php
namespace InfyOm\Generator\Commands\Publish;
use Exception;
use Illuminate\View\Factory;
use Symfony\Component\Console\Input\InputArgument;
class PublishTablesCommand extends PublishBaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.publish:tables';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publishes Table files';
public function handle()
{
$tableType = $this->argument('type');
if ($tableType === 'datatable') {
$this->publishDataTableViews();
return;
}
if ($tableType === 'livewire') {
$this->publishLivewireTableViews();
return;
}
throw new Exception('Invalid Table Type');
}
public function publishLivewireTableViews()
{
$viewsPath = config('laravel_generator.path.views', resource_path('views/'));
$templateType = config('laravel_generator.templates', 'adminlte-templates');
$files = [
'templates.scaffold.table.livewire.actions' => 'common/livewire-tables/actions.blade.php',
];
g_filesystem()->createDirectoryIfNotExist($viewsPath.'common/livewire-tables');
/** @var Factory $viewFactory */
$viewFactory = view();
foreach ($files as $templateView => $destinationView) {
$templateViewPath = $viewFactory->getFinder()->find($templateType.'::'.$templateView);
$content = g_filesystem()->getFile($templateViewPath);
$destinationFile = $viewsPath.$destinationView;
g_filesystem()->createFile($destinationFile, $content);
}
}
protected function publishDataTableViews()
{
$viewsPath = config('laravel_generator.path.views', resource_path('views/'));
$files = [
'layouts.datatables_css' => 'layouts/datatables_css.blade.php',
'layouts.datatables_js' => 'layouts/datatables_js.blade.php',
];
foreach ($files as $templateView => $destinationView) {
$content = view('laravel-generator::scaffold.'.$templateView)->render();
$destinationFile = $viewsPath.$destinationView;
g_filesystem()->createFile($destinationFile, $content);
}
}
/**
* Get the console command arguments.
*
* @return array
*/
public function getArguments()
{
return [
['type', InputArgument::REQUIRED, 'Types of Tables (datatable / livewire)'],
];
}
}
<?php
namespace InfyOm\Generator\Commands\Publish;
class PublishUserCommand extends PublishBaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.publish:user';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publishes Users CRUD file';
public function handle()
{
$this->copyViews();
$this->updateRoutes();
$this->updateMenu();
$this->publishUserController();
if (config('laravel_generator.options.repository_pattern')) {
$this->publishUserRepository();
}
$this->publishCreateUserRequest();
$this->publishUpdateUserRequest();
}
private function copyViews()
{
$viewsPath = config('laravel_generator.path.views', resource_path('views/'));
$templateType = config('laravel_generator.templates', 'adminlte-templates');
$this->createDirectories($viewsPath.'users');
$files = $this->getViews();
foreach ($files as $templateView => $destinationView) {
$content = view($templateType.'::'.$templateView);
$destinationFile = $viewsPath.$destinationView;
g_filesystem()->createFile($destinationFile, $content);
}
}
private function createDirectories($dir)
{
g_filesystem()->createDirectoryIfNotExist($dir);
}
private function getViews(): array
{
return [
'users.create' => 'users/create.blade.php',
'users.edit' => 'users/edit.blade.php',
'users.fields' => 'users/fields.blade.php',
'users.index' => 'users/index.blade.php',
'users.show' => 'users/show.blade.php',
'users.show_fields' => 'users/show_fields.blade.php',
'users.table' => 'users/table.blade.php',
];
}
private function updateRoutes()
{
$path = config('laravel_generator.path.routes', base_path('routes/web.php'));
$routeContents = g_filesystem()->getFile($path);
$controllerNamespace = config('laravel_generator.namespace.controller');
$routeContents .= infy_nls(2)."Route::resource('users', '$controllerNamespace\UserController')->middleware('auth');";
g_filesystem()->createFile($path, $routeContents);
$this->comment("\nUser route added");
}
private function updateMenu()
{
$viewsPath = config('laravel_generator.path.views', resource_path('views/'));
$templateType = config('laravel_generator.templates', 'adminlte-templates');
$path = $viewsPath.'layouts/menu.blade.php';
$menuContents = g_filesystem()->getFile($path);
$usersMenuContent = view($templateType.'::templates.users.menu')->render();
$menuContents .= infy_nl().$usersMenuContent;
g_filesystem()->createFile($path, $menuContents);
$this->comment("\nUser Menu added");
}
private function publishUserController()
{
$name = 'user_controller';
if (!config('laravel_generator.options.repository_pattern')) {
$name = 'user_controller_without_repository';
}
$controllerPath = config('laravel_generator.path.controller', app_path('Http/Controllers/'));
$controllerPath .= 'UserController.php';
$controllerContents = view('laravel-generator::scaffold.user.'.$name)->render();
g_filesystem()->createFile($controllerPath, $controllerContents);
$this->info('UserController created');
}
private function publishUserRepository()
{
$repositoryPath = config('laravel_generator.path.repository', app_path('Repositories/'));
$fileName = 'UserRepository.php';
g_filesystem()->createDirectoryIfNotExist($repositoryPath);
if (file_exists($repositoryPath.$fileName) && !$this->confirmOverwrite($fileName)) {
return;
}
$templateData = view('laravel-generator::scaffold.user.user_repository')->render();
g_filesystem()->createFile($repositoryPath.$fileName, $templateData);
$this->info('UserRepository created');
}
private function publishCreateUserRequest()
{
$requestPath = config('laravel_generator.path.request', app_path('Http/Requests/'));
$fileName = 'CreateUserRequest.php';
g_filesystem()->createDirectoryIfNotExist($requestPath);
if (file_exists($requestPath.$fileName) && !$this->confirmOverwrite($fileName)) {
return;
}
$templateData = view('laravel-generator::scaffold.user.create_user_request')->render();
g_filesystem()->createFile($requestPath.$fileName, $templateData);
$this->info('CreateUserRequest created');
}
private function publishUpdateUserRequest()
{
$requestPath = config('laravel_generator.path.request', app_path('Http/Requests/'));
$fileName = 'UpdateUserRequest.php';
if (file_exists($requestPath.$fileName) && !$this->confirmOverwrite($fileName)) {
return;
}
$templateData = view('laravel-generator::scaffold.user.update_user_request')->render();
g_filesystem()->createFile($requestPath.$fileName, $templateData);
$this->info('UpdateUserRequest created');
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return [];
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
}
<?php
namespace InfyOm\Generator\Commands;
use InfyOm\Generator\Common\GeneratorConfig;
use InfyOm\Generator\Generators\API\APIControllerGenerator;
use InfyOm\Generator\Generators\API\APIRequestGenerator;
use InfyOm\Generator\Generators\API\APIRoutesGenerator;
use InfyOm\Generator\Generators\API\APITestGenerator;
use InfyOm\Generator\Generators\FactoryGenerator;
use InfyOm\Generator\Generators\MigrationGenerator;
use InfyOm\Generator\Generators\ModelGenerator;
use InfyOm\Generator\Generators\RepositoryGenerator;
use InfyOm\Generator\Generators\RepositoryTestGenerator;
use InfyOm\Generator\Generators\Scaffold\ControllerGenerator;
use InfyOm\Generator\Generators\Scaffold\MenuGenerator;
use InfyOm\Generator\Generators\Scaffold\RequestGenerator;
use InfyOm\Generator\Generators\Scaffold\RoutesGenerator;
use InfyOm\Generator\Generators\Scaffold\ViewGenerator;
use InfyOm\Generator\Generators\SeederGenerator;
use Symfony\Component\Console\Input\InputArgument;
class RollbackGeneratorCommand extends BaseCommand
{
public GeneratorConfig $config;
protected $name = 'winas:rollback';
protected $description = 'Rollback a full CRUD API and Scaffold for given model';
public function handle()
{
$this->config = app(GeneratorConfig::class);
$this->config->setCommand($this);
$this->config->init();
$type = $this->argument('type');
if (!in_array($type, ['api', 'scaffold', 'api_scaffold'])) {
$this->error('Invalid rollback type');
return 1;
}
$this->fireFileDeletingEvent($type);
$views = $this->option('views');
if (!empty($views)) {
$views = explode(',', $views);
$viewGenerator = new ViewGenerator();
$viewGenerator->rollback($views);
$this->info('Generating autoload files');
$this->composer->dumpOptimized();
$this->fireFileDeletedEvent($type);
return 0;
}
$migrationGenerator = app(MigrationGenerator::class);
$migrationGenerator->rollback();
$modelGenerator = app(ModelGenerator::class);
$modelGenerator->rollback();
if ($this->config->options->repositoryPattern) {
$repositoryGenerator = app(RepositoryGenerator::class);
$repositoryGenerator->rollback();
}
if (in_array($type, ['api', 'api_scaffold'])) {
$requestGenerator = app(APIRequestGenerator::class);
$requestGenerator->rollback();
$controllerGenerator = app(APIControllerGenerator::class);
$controllerGenerator->rollback();
$routesGenerator = app(APIRoutesGenerator::class);
$routesGenerator->rollback();
}
if (in_array($type, ['scaffold', 'api_scaffold'])) {
$requestGenerator = app(RequestGenerator::class);
$requestGenerator->rollback();
$controllerGenerator = app(ControllerGenerator::class);
$controllerGenerator->rollback();
$viewGenerator = app(ViewGenerator::class);
$viewGenerator->rollback();
$routeGenerator = app(RoutesGenerator::class);
$routeGenerator->rollback();
$menuGenerator = app(MenuGenerator::class);
$menuGenerator->rollback();
}
if ($this->config->options->tests) {
$repositoryTestGenerator = app(RepositoryTestGenerator::class);
$repositoryTestGenerator->rollback();
$apiTestGenerator = app(APITestGenerator::class);
$apiTestGenerator->rollback();
}
if ($this->config->options->factory or $this->config->options->tests) {
$factoryGenerator = app(FactoryGenerator::class);
$factoryGenerator->rollback();
}
if ($this->config->options->seeder) {
$seederGenerator = app(SeederGenerator::class);
$seederGenerator->rollback();
}
$this->info('Generating autoload files');
$this->composer->dumpOptimized();
$this->fireFileDeletedEvent($type);
return 0;
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['model', InputArgument::REQUIRED, 'Singular Model name'],
['type', InputArgument::REQUIRED, 'Rollback type: (api / scaffold / api_scaffold)'],
];
}
}
<?php
namespace InfyOm\Generator\Commands\Scaffold;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\Scaffold\ControllerGenerator;
class ControllerGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.scaffold:controller';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create controller command';
public function handle()
{
parent::handle();
/** @var ControllerGenerator $controllerGenerator */
$controllerGenerator = app(ControllerGenerator::class);
$controllerGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\Scaffold;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\Scaffold\RequestGenerator;
class RequestsGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.scaffold:requests';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a full CRUD views for given model';
public function handle()
{
parent::handle();
/** @var RequestGenerator $requestGenerator */
$requestGenerator = app(RequestGenerator::class);
$requestGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Commands\Scaffold;
use InfyOm\Generator\Commands\BaseCommand;
class ScaffoldGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'winas:scaffold';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a full CRUD views for given model';
public function handle()
{
parent::handle();
if ($this->checkIsThereAnyDataToGenerate()) {
$this->fireFileCreatingEvent('scaffold');
$this->generateCommonItems();
$this->generateScaffoldItems();
$this->performPostActionsWithMigration();
$this->fireFileCreatedEvent('scaffold');
} else {
$this->config->commandInfo('There are not enough input fields for scaffold generation.');
}
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
protected function checkIsThereAnyDataToGenerate(): bool
{
if (count($this->config->fields) > 1) {
return true;
}
return false;
}
}
<?php
namespace InfyOm\Generator\Commands\Scaffold;
use InfyOm\Generator\Commands\BaseCommand;
use InfyOm\Generator\Generators\Scaffold\ViewGenerator;
class ViewsGeneratorCommand extends BaseCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'infyom.scaffold:views';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create views file command';
public function handle()
{
parent::handle();
/** @var ViewGenerator $viewGenerator */
$viewGenerator = app(ViewGenerator::class);
$viewGenerator->generate();
$this->performPostActions();
}
/**
* Get the console command options.
*
* @return array
*/
public function getOptions()
{
return array_merge(parent::getOptions(), []);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array_merge(parent::getArguments(), []);
}
}
<?php
namespace InfyOm\Generator\Common;
class FileSystem
{
public function getFile(string $path): string
{
if (!file_exists($path)) {
return '';
}
return file_get_contents($path);
}
public function createFile(string $file, string $contents): bool|int
{
$path = dirname($file);
if (!empty($path) && !file_exists($path)) {
mkdir($path, 0755, true);
}
return file_put_contents($file, $contents);
}
public function createDirectoryIfNotExist(string $path, bool $replace = false): bool
{
if (!empty($path) && file_exists($path) && $replace) {
return rmdir($path);
}
if (!empty($path) && !file_exists($path)) {
return mkdir($path, 0755, true);
}
return false;
}
public function deleteFile(string $path, string $fileName): bool
{
if (file_exists($path.$fileName)) {
return unlink($path.$fileName);
}
return false;
}
}
This diff is collapsed.
<?php
namespace InfyOm\Generator\Common;
use Illuminate\Support\Str;
class GeneratorField
{
/** @var string */
public string $name;
public string $dbType;
public array $dbTypeParams = [];
public array $dbExtraFunctions = [];
public string $htmlType = '';
public array $htmlValues = [];
public string $description;
public string $validations = '';
public bool $isSearchable = true;
public bool $isFillable = true;
public bool $isPrimary = false;
public bool $inForm = true;
public bool $inIndex = true;
public bool $inView = true;
public bool $isNotNull = false;
public string $migrationText = '';
public string $foreignKeyText = '';
public int $numberDecimalPoints = 2;
/** @var \Doctrine\DBAL\Schema\Column */
public $fieldDetails = null;
public function parseDBType(string $dbInput)
{
$dbInputArr = explode(':', $dbInput);
$dbType = (string) array_shift($dbInputArr);
if (Str::contains($dbType, ',')) {
$dbTypeArr = explode(',', $dbType);
$this->dbType = (string) array_shift($dbTypeArr);
$this->dbTypeParams = $dbTypeArr;
} else {
$this->dbType = $dbType;
}
$this->dbExtraFunctions = $dbInputArr;
// if (!is_null($column)) {
// $this->dbType = ($column->getLength() > 0) ? $this->dbType.','.$column->getLength() : $this->dbType;
// $this->dbType = (!$column->getNotnull()) ? $this->dbType.':nullable' : $this->dbType;
// }
$this->prepareMigrationText();
}
public function parseHtmlInput(string $htmlInput)
{
if (empty($htmlInput)) {
$this->htmlType = 'text';
return;
}
if (!Str::contains($htmlInput, ':')) {
$this->htmlType = $htmlInput;
return;
}
$htmlInputArr = explode(':', $htmlInput);
$this->htmlType = (string) array_shift($htmlInputArr);
$this->htmlValues = explode(',', implode(':', $htmlInputArr));
}
public function parseOptions(string $options)
{
$options = strtolower($options);
$optionsArr = explode(',', $options);
if (in_array('s', $optionsArr)) {
$this->isSearchable = false;
}
if (in_array('p', $optionsArr)) {
// if field is primary key, then its not searchable, fillable, not in index & form
$this->isPrimary = true;
$this->isSearchable = false;
$this->isFillable = false;
$this->inForm = false;
$this->inIndex = false;
$this->inView = false;
}
if (in_array('f', $optionsArr)) {
$this->isFillable = false;
}
if (in_array('if', $optionsArr)) {
$this->inForm = false;
}
if (in_array('ii', $optionsArr)) {
$this->inIndex = false;
}
if (in_array('iv', $optionsArr)) {
$this->inView = false;
}
}
protected function prepareMigrationText()
{
$this->migrationText = '$table->';
$this->migrationText .= $this->dbType."('".$this->name."'";
if (!count($this->dbTypeParams) and !count($this->dbExtraFunctions)) {
$this->migrationText .= ');';
return;
}
if (count($this->dbTypeParams)) {
// if ($this->dbType === 'enum') {
// $this->migrationText .= ', [';
// foreach ($fieldTypeParams as $param) {
// $this->migrationText .= "'".$param."',";
// }
// $this->migrationText = substr($this->migrationText, 0, strlen($this->migrationText) - 1);
// $this->migrationText .= ']';
// }
foreach ($this->dbTypeParams as $dbTypeParam) {
$this->migrationText .= ', '.$dbTypeParam;
}
}
$this->migrationText .= ')';
if (!count($this->dbExtraFunctions)) {
$this->migrationText .= ';';
return;
}
$this->foreignKeyText = '';
foreach ($this->dbExtraFunctions as $dbExtraFunction) {
$dbExtraFunctionArr = explode(',', $dbExtraFunction);
$functionName = (string) array_shift($dbExtraFunctionArr);
if ($functionName === 'foreign') {
$foreignTable = array_shift($dbExtraFunctionArr);
$foreignField = array_shift($dbExtraFunctionArr);
$this->foreignKeyText .= "\$table->foreign('".$this->name."')->references('".$foreignField."')->on('".$foreignTable."')";
if (count($dbExtraFunctionArr)) {
$cascade = array_shift($dbExtraFunctionArr);
if ($cascade === 'cascade') {
$this->foreignKeyText .= "->onUpdate('cascade')->onDelete('cascade')";
}
}
$this->foreignKeyText .= ';';
} else {
$this->migrationText .= '->'.$functionName;
$this->migrationText .= '(';
$this->migrationText .= implode(', ', $dbExtraFunctionArr);
$this->migrationText .= ')';
}
}
$this->migrationText .= ';';
}
public static function parseFieldFromConsoleInput(string $fieldInput, string $validations = ''): self
{
/*
* Field Input Format: field_name <space> db_type <space> html_type(optional) <space> options(optional)
* Options are to skip the field from certain criteria like searchable, fillable, not in form, not in index
* Searchable (s), Fillable (f), In Form (if), In Index (ii)
* Sample Field Inputs
*
* title string text
* body text textarea
* name string,20 text
* post_id integer:unsigned:nullable
* post_id unsignedinteger:nullable:foreign,posts,id
* password string text if,ii,s - options will skip field from being added in form, in index and searchable
*/
$field = new self();
$fieldInputArr = explode(' ', $fieldInput);
$field->name = $fieldInputArr[0];
$field->parseDBType($fieldInputArr[1]);
$field->parseHtmlInput($fieldInputArr[2]);
if (count($fieldInputArr) > 3) {
$field->parseOptions($fieldInputArr[3]);
}
$field->validations = $validations;
if (str_contains($field->validations, 'required')) {
$field->isNotNull = true;
}
return $field;
}
public static function parseFieldFromFile(array $fieldInput): self
{
$field = new self();
$field->name = $fieldInput['name'];
$field->parseDBType($fieldInput['dbType']);
$field->parseHtmlInput($fieldInput['htmlType'] ?? '');
$field->validations = $fieldInput['validations'] ?? '';
$field->isSearchable = $fieldInput['searchable'] ?? false;
$field->isFillable = $fieldInput['fillable'] ?? true;
$field->isPrimary = $fieldInput['primary'] ?? false;
$field->inForm = $fieldInput['inForm'] ?? true;
$field->inIndex = $fieldInput['inIndex'] ?? true;
$field->inView = $fieldInput['inView'] ?? true;
if (str_contains($field->validations, 'required')) {
$field->isNotNull = true;
}
return $field;
}
public function getTitle(): string
{
return Str::title(str_replace('_', ' ', $this->name));
}
public function variables(): array
{
return [
'fieldName' => $this->name,
'fieldTitle' => $this->getTitle(),
];
}
}
<?php
namespace InfyOm\Generator\Common;
use Illuminate\Support\Str;
class GeneratorFieldRelation
{
public $type;
public array $inputs;
public string $relationName;
public static function parseRelation($relationInput): self
{
$inputs = explode(',', $relationInput);
$relation = new self();
$relation->type = array_shift($inputs);
$modelWithRelation = explode(':', array_shift($inputs)); //e.g ModelName:relationName
if (count($modelWithRelation) == 2) {
$relation->relationName = $modelWithRelation[1];
unset($modelWithRelation[1]);
}
$relation->inputs = array_merge($modelWithRelation, $inputs);
return $relation;
}
public function getRelationFunctionText(string $relationText = null): string
{
$singularRelation = (!empty($this->relationName)) ? $this->relationName : Str::camel($relationText);
$pluralRelation = (!empty($this->relationName)) ? $this->relationName : Str::camel(Str::plural($relationText));
switch ($this->type) {
case '1t1':
$functionName = $singularRelation;
$relation = 'hasOne';
$relationClass = 'HasOne';
break;
case '1tm':
$functionName = $pluralRelation;
$relation = 'hasMany';
$relationClass = 'HasMany';
break;
case 'mt1':
if (!empty($this->relationName)) {
$singularRelation = $this->relationName;
} elseif (isset($this->inputs[1])) {
$singularRelation = Str::camel(str_replace('_id', '', strtolower($this->inputs[1])));
}
$functionName = $singularRelation;
$relation = 'belongsTo';
$relationClass = 'BelongsTo';
break;
case 'mtm':
$functionName = $pluralRelation;
$relation = 'belongsToMany';
$relationClass = 'BelongsToMany';
break;
case 'hmt':
$functionName = $pluralRelation;
$relation = 'hasManyThrough';
$relationClass = 'HasManyThrough';
break;
default:
$functionName = '';
$relation = '';
$relationClass = '';
break;
}
if (!empty($functionName) and !empty($relation)) {
return $this->generateRelation($functionName, $relation, $relationClass);
}
return '';
}
protected function generateRelation($functionName, $relation, $relationClass)
{
$inputs = $this->inputs;
$relatedModelName = array_shift($inputs);
if (count($inputs) > 0) {
$inputFields = implode("', '", $inputs);
$inputFields = ", '".$inputFields."'";
} else {
$inputFields = '';
}
return view('laravel-generator::model.relationship', [
'relationClass' => $relationClass,
'functionName' => $functionName,
'relation' => $relation,
'relatedModel' => $relatedModelName,
'fields' => $inputFields,
])->render();
}
}
<?php
namespace InfyOm\Generator\Criteria;
use Illuminate\Http\Request;
use Prettus\Repository\Contracts\CriteriaInterface;
class LimitOffsetCriteria implements CriteriaInterface
{
/**
* @var \Illuminate\Http\Request
*/
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Apply criteria in query repository.
*
* @param $model
* @param \Prettus\Repository\Contracts\RepositoryInterface $repository
*
* @return mixed
*/
public function apply($model, \Prettus\Repository\Contracts\RepositoryInterface $repository)
{
$limit = (int) $this->request->get('limit', null);
$offset = (int) $this->request->get('offset', null);
if ($limit) {
$model = $model->limit($limit);
}
if ($offset && $limit) {
$model = $model->skip($offset);
}
return $model;
}
}
<?php
namespace InfyOm\Generator\DTOs;
class GeneratorNamespaces
{
public string $app;
public string $repository;
public string $model;
public string $dataTables;
public string $livewireTables;
public string $modelExtend;
public string $seeder;
public string $factory;
public string $apiController;
public string $apiResource;
public string $apiRequest;
public string $request;
public string $requestBase;
public string $controller;
public string $baseController;
public string $apiTests;
public string $repositoryTests;
public string $testTraits;
public string $tests;
}
<?php
namespace InfyOm\Generator\DTOs;
class GeneratorOptions
{
public bool $softDelete;
public bool $saveSchemaFile;
public bool $localized;
public bool $repositoryPattern;
public bool $resources;
public bool $factory;
public bool $seeder;
public bool $swagger;
public bool $tests;
public array $excludedFields;
}
<?php
namespace InfyOm\Generator\DTOs;
class GeneratorPaths
{
public string $repository;
public string $model;
public string $dataTables;
public string $livewireTables;
public string $factory;
public string $seeder;
public string $databaseSeeder;
public string $viewProvider;
public string $apiController;
public string $apiResource;
public string $apiRequest;
public string $apiRoutes;
public string $apiTests;
public string $controller;
public string $request;
public string $routes;
public string $views;
}
<?php
namespace InfyOm\Generator\DTOs;
use Illuminate\Support\Str;
class GeneratorPrefixes
{
public string $route = '';
public string $view = '';
public string $namespace = '';
public function getRoutePrefixWith($append)
{
if ($this->route) {
return $this->route.$append;
}
return '';
}
public function getViewPrefixWith($append)
{
if ($this->view) {
return $this->view.$append;
}
return '';
}
public function getViewPrefixForInclude()
{
if ($this->view) {
return Str::replace('/', '.', $this->view).'.';
}
return '';
}
public function mergeRoutePrefix(array $prefixes)
{
foreach ($prefixes as $prefix) {
if (empty($prefix)) {
continue;
}
$this->route .= '.'.Str::camel($prefix);
}
$this->route = ltrim($this->route, '.');
}
public function mergeNamespacePrefix(array $prefixes)
{
foreach ($prefixes as $prefix) {
if (empty($prefix)) {
continue;
}
$this->namespace .= '\\'.Str::title($prefix);
}
$this->namespace = ltrim($this->namespace, '\\');
}
public function mergeViewPrefix(array $prefixes)
{
foreach ($prefixes as $prefix) {
if (empty($prefix)) {
continue;
}
$this->view .= '/'.Str::snake($prefix);
}
$this->view = ltrim($this->view, '/');
}
}
<?php
namespace InfyOm\Generator\DTOs;
class ModelNames
{
public string $name;
public string $plural;
public string $camel;
public string $camelPlural;
public string $snake;
public string $snakePlural;
public string $dashed;
public string $dashedPlural;
public string $human;
public string $humanPlural;
}
<?php
namespace InfyOm\Generator\Events;
use Illuminate\Queue\SerializesModels;
class GeneratorFileCreated
{
use SerializesModels;
public string $type;
public array $data;
public function __construct(string $type, array $data)
{
$this->type = $type;
$this->data = $data;
}
}
<?php
namespace InfyOm\Generator\Events;
use Illuminate\Queue\SerializesModels;
class GeneratorFileCreating
{
use SerializesModels;
public string $type;
public array $data;
public function __construct(string $type, array $data)
{
$this->type = $type;
$this->data = $data;
}
}
<?php
namespace InfyOm\Generator\Events;
use Illuminate\Queue\SerializesModels;
class GeneratorFileDeleted
{
use SerializesModels;
public string $type;
public array $data;
public function __construct(string $type, array $data)
{
$this->type = $type;
$this->data = $data;
}
}
<?php
namespace InfyOm\Generator\Events;
use Illuminate\Queue\SerializesModels;
class GeneratorFileDeleting
{
use SerializesModels;
public string $type;
public array $data;
public function __construct(string $type, array $data)
{
$this->type = $type;
$this->data = $data;
}
}
<?php
namespace InfyOm\Generator\Facades;
use Illuminate\Support\Facades\Facade;
use InfyOm\Generator\Common\FileSystem;
use Mockery;
class FileUtils extends Facade
{
protected static function getFacadeAccessor()
{
return FileSystem::class;
}
public static function fake($allowedMethods = [])
{
if (empty($allowedMethods)) {
$allowedMethods = [
'getFile' => '',
'createFile' => true,
'createDirectoryIfNotExist' => true,
'deleteFile' => true,
];
}
static::swap($fake = Mockery::mock()->allows($allowedMethods));
return $fake;
}
}
<?php
namespace InfyOm\Generator\Generators\API;
use Illuminate\Support\Str;
use InfyOm\Generator\Generators\BaseGenerator;
class APIControllerGenerator extends BaseGenerator
{
private string $fileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->apiController;
$this->fileName = $this->config->modelNames->name.'APIController.php';
}
public function variables(): array
{
return array_merge([], $this->docsVariables());
}
public function getViewName(): string
{
if ($this->config->options->repositoryPattern) {
$templateName = 'repository.controller';
} else {
$templateName = 'model.controller';
}
if ($this->config->options->resources) {
$templateName .= '_resource';
}
return $templateName;
}
public function generate()
{
$viewName = $this->getViewName();
$templateData = view('laravel-generator::api.controller.'.$viewName, $this->variables())->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'API Controller created: ');
$this->config->commandInfo($this->fileName);
}
protected function docsVariables(): array
{
$methods = ['controller', 'index', 'store', 'show', 'update', 'destroy'];
if ($this->config->options->swagger) {
$templatePrefix = 'controller';
$templateType = 'swagger-generator';
} else {
$templatePrefix = 'api.docs.controller';
$templateType = 'laravel-generator';
}
$variables = [];
foreach ($methods as $method) {
$variable = 'doc'.Str::title($method);
$variables[$variable] = view($templateType.'::'.$templatePrefix.'.'.$method)->render();
}
return $variables;
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('API Controller file deleted: '.$this->fileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators\API;
use InfyOm\Generator\Generators\BaseGenerator;
use InfyOm\Generator\Generators\ModelGenerator;
class APIRequestGenerator extends BaseGenerator
{
private string $createFileName;
private string $updateFileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->apiRequest;
$this->createFileName = 'Create'.$this->config->modelNames->name.'APIRequest.php';
$this->updateFileName = 'Update'.$this->config->modelNames->name.'APIRequest.php';
}
public function generate()
{
$this->generateCreateRequest();
$this->generateUpdateRequest();
}
protected function generateCreateRequest()
{
$templateData = view('laravel-generator::api.request.create', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->createFileName, $templateData);
$this->config->commandComment(infy_nl().'Create Request created: ');
$this->config->commandInfo($this->createFileName);
}
protected function generateUpdateRequest()
{
$modelGenerator = app(ModelGenerator::class);
$rules = $modelGenerator->generateUniqueRules();
$templateData = view('laravel-generator::api.request.update', [
'uniqueRules' => $rules,
])->render();
g_filesystem()->createFile($this->path.$this->updateFileName, $templateData);
$this->config->commandComment(infy_nl().'Update Request created: ');
$this->config->commandInfo($this->updateFileName);
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->createFileName)) {
$this->config->commandComment('Create API Request file deleted: '.$this->createFileName);
}
if ($this->rollbackFile($this->path, $this->updateFileName)) {
$this->config->commandComment('Update API Request file deleted: '.$this->updateFileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators\API;
use InfyOm\Generator\Generators\BaseGenerator;
class APIResourceGenerator extends BaseGenerator
{
private string $fileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->apiResource;
$this->fileName = $this->config->modelNames->name.'Resource.php';
}
public function variables(): array
{
return [
'fields' => implode(','.infy_nl_tab(1, 3), $this->generateResourceFields()),
];
}
public function generate()
{
$templateData = view('laravel-generator::api.resource.resource', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'API Resource created: ');
$this->config->commandInfo($this->fileName);
}
protected function generateResourceFields(): array
{
$resourceFields = [];
foreach ($this->config->fields as $field) {
$resourceFields[] = "'".$field->name."' => \$this->".$field->name;
}
return $resourceFields;
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('API Resource file deleted: '.$this->fileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators\API;
use Illuminate\Support\Str;
use InfyOm\Generator\Generators\BaseGenerator;
class APIRoutesGenerator extends BaseGenerator
{
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->apiRoutes;
}
public function generate()
{
$routeContents = g_filesystem()->getFile($this->path);
$routes = view('laravel-generator::api.routes', $this->variables())->render();
if (Str::contains($routeContents, $routes)) {
$this->config->commandInfo(infy_nl().'Menu '.$this->config->modelNames->dashedPlural.' already exists, Skipping Adjustment.');
return;
}
$routeContents .= infy_nls(2).$routes;
g_filesystem()->createFile($this->path, $routeContents);
$this->config->commandComment(infy_nl().$this->config->modelNames->dashedPlural.' api routes added.');
}
public function rollback()
{
$routeContents = g_filesystem()->getFile($this->path);
$routes = view('laravel-generator::api.routes', $this->variables())->render();
if (Str::contains($routeContents, $routes)) {
$routeContents = str_replace($routes, '', $routeContents);
g_filesystem()->createFile($this->path, $routeContents);
$this->config->commandComment('api routes deleted');
}
}
}
<?php
namespace InfyOm\Generator\Generators\API;
use InfyOm\Generator\Generators\BaseGenerator;
class APITestGenerator extends BaseGenerator
{
private string $fileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->apiTests;
$this->fileName = $this->config->modelNames->name.'ApiTest.php';
}
public function generate()
{
$templateData = view('laravel-generator::api.test.api_test', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'ApiTest created: ');
$this->config->commandInfo($this->fileName);
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('API Test file deleted: '.$this->fileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators;
use InfyOm\Generator\Common\GeneratorConfig;
abstract class BaseGenerator
{
public GeneratorConfig $config;
public string $path;
public function __construct()
{
$this->config = app(GeneratorConfig::class);
}
public function rollbackFile($path, $fileName): bool
{
if (file_exists($path.$fileName)) {
return g_filesystem()->deleteFile($path, $fileName);
}
return false;
}
public function variables(): array
{
return [];
}
}
<?php
namespace InfyOm\Generator\Generators;
use Illuminate\Support\Str;
use InfyOm\Generator\Utils\GeneratorFieldsInputUtil;
class FactoryGenerator extends BaseGenerator
{
private string $fileName;
private array $relations = [];
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->factory;
$this->fileName = $this->config->modelNames->name.'Factory.php';
//setup relations if available
//assumes relation fields are tailed with _id if not supplied
if (property_exists($this->config, 'relations')) {
foreach ($this->config->relations as $r) {
if ($r->type == 'mt1') {
$relation = (isset($r->inputs[0])) ? $r->inputs[0] : null;
if (isset($r->inputs[1])) {
$field = $r->inputs[1];
} else {
$field = Str::snake($relation).'_id';
}
if ($field) {
$rel = $relation;
$this->relations[$field] = [
'relation' => $rel,
'model_class' => $this->config->namespaces->model.'\\'.$relation,
];
}
}
}
}
}
public function variables(): array
{
$relations = $this->getRelationsBootstrap();
return [
'fields' => $this->generateFields(),
'relations' => $relations['text'],
'usedRelations' => $relations['uses'],
];
}
public function generate()
{
$templateData = view('laravel-generator::model.factory', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'Factory created: ');
$this->config->commandInfo($this->fileName);
}
protected function generateFields(): string
{
$fields = [];
//get model validation rules
$class = $this->config->namespaces->model.'\\'.$this->config->modelNames->name;
$rules = [];
if (class_exists($class)) {
$rules = $class::$rules;
}
$relations = array_keys($this->relations);
foreach ($this->config->fields as $field) {
if ($field->isPrimary) {
continue;
}
$fieldData = "'".$field->name."' => ".'$this->faker->';
$rule = null;
if (isset($rules[$field->name])) {
$rule = $rules[$field->name];
}
switch (strtolower($field->dbType)) {
case 'integer':
case 'unsignedinteger':
case 'smallinteger':
case 'biginteger':
case 'unsignedbiginteger':
$fakerData = in_array($field->name, $relations) ? ':relation' : $this->getValidNumber($rule, 999);
break;
case 'long':
case 'double':
case 'float':
case 'decimal':
$fakerData = $this->getValidNumber($rule);
break;
case 'string':
case 'char':
$lower = strtolower($field->name);
$firstChar = substr($lower, 0, 1);
if (str_contains($lower, 'email')) {
$fakerData = 'email';
} elseif ($firstChar == 'f' && str_contains($lower, 'name')) {
$fakerData = 'firstName';
} elseif (($firstChar == 's' || $firstChar == 'l') && str_contains($lower, 'name')) {
$fakerData = 'lastName';
} elseif (str_contains($lower, 'phone')) {
$fakerData = "numerify('0##########')";
} elseif (str_contains($lower, 'password')) {
$fakerData = "lexify('1???@???A???')";
} elseif (strpos($lower, 'address')) {
$fakerData = 'address';
} else {
if (!$rule) {
$rule = 'max:255';
}
$fakerData = $this->getValidText($rule);
}
break;
case 'text':
$fakerData = $rule ? $this->getValidText($rule) : 'text(500)';
break;
case 'boolean':
$fakerData = 'boolean';
break;
case 'date':
$fakerData = "date('Y-m-d')";
break;
case 'datetime':
case 'timestamp':
$fakerData = "date('Y-m-d H:i:s')";
break;
case 'time':
$fakerData = "date('H:i:s')";
break;
case 'enum':
$fakerData = 'randomElement('.
GeneratorFieldsInputUtil::prepareValuesArrayStr($field->htmlValues).
')';
break;
default:
$fakerData = 'word';
}
if ($fakerData == ':relation') {
$fieldData = $this->getValidRelation($field->name);
} else {
$fieldData .= $fakerData;
}
$fields[] = $fieldData;
}
return implode(','.infy_nl_tab(1, 3), $fields);
}
/**
* Generates a valid number based on applicable model rule.
*
* @param string $rule The applicable model rule
* @param int $max The maximum number to generate.
*
* @return string
*/
public function getValidNumber($rule = null, $max = PHP_INT_MAX): string
{
if ($rule) {
$max = $this->extractMinMax($rule, 'max') ?? $max;
$min = $this->extractMinMax($rule, 'min') ?? 0;
return "numberBetween($min, $max)";
} else {
return 'randomDigitNotNull';
}
}
/**
* Generates a valid relation if applicable
* This method assumes the related field primary key is id.
*/
public function getValidRelation(string $fieldName): string
{
$relation = $this->relations[$fieldName]['relation'];
$variable = Str::camel($relation);
return "'".$fieldName."' => ".'$'.$variable.'->id';
}
/**
* Generates a valid text based on applicable model rule.
*
* @param string $rule The applicable model rule.
*/
public function getValidText($rule = null): string
{
if ($rule) {
$max = $this->extractMinMax($rule, 'max') ?? 4096;
$min = $this->extractMinMax($rule) ?? 5;
if ($max < 5) {
//faker text requires at least 5 characters
return "lexify('?????')";
}
if ($min < 5) {
//faker text requires at least 5 characters
$min = 5;
}
return 'text('.'$this->faker->numberBetween('.$min.', '.$max.'))';
} else {
return 'text';
}
}
/**
* Extracts min or max rule for a laravel model.
*/
public function extractMinMax($rule, $t = 'min')
{
$i = strpos($rule, $t);
$e = strpos($rule, '|', $i);
if ($e === false) {
$e = strlen($rule);
}
if ($i !== false) {
$len = $e - ($i + 4);
return substr($rule, $i + 4, $len);
}
return null;
}
/**
* Generate valid model so we can use the id where applicable
* This method assumes the model has a factory.
*/
public function getRelationsBootstrap(): array
{
$text = '';
$uses = '';
foreach ($this->relations as $field => $data) {
$relation = $data['relation'];
$qualifier = $data['model_class'];
$variable = Str::camel($relation);
$model = Str::studly($relation);
if (!empty($text)) {
$text = infy_nl_tab(1, 2);
}
$text .= '$'.$variable.' = '.$model.'::first();'.
infy_nl_tab(1, 2).
'if (!$'.$variable.') {'.
infy_nl_tab(1, 3).
'$'.$variable.' = '.$model.'::factory()->create();'.
infy_nl_tab(1, 2).'}'.infy_nl();
$uses .= infy_nl()."use $qualifier;";
}
return [
'text' => $text,
'uses' => $uses,
];
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('Factory file deleted: '.$this->fileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use SplFileInfo;
class MigrationGenerator extends BaseGenerator
{
public function __construct()
{
parent::__construct();
$this->path = config('laravel_generator.path.migration', database_path('migrations/'));
}
public function generate()
{
$templateData = view('laravel-generator::migration', $this->variables())->render();
$fileName = date('Y_m_d_His').'_'.'create_'.strtolower($this->config->tableName).'_table.php';
g_filesystem()->createFile($this->path.$fileName, $templateData);
$this->config->commandComment(infy_nl().'Migration created: ');
$this->config->commandInfo($fileName);
}
public function variables(): array
{
return [
'fields' => $this->generateFields(),
];
}
protected function generateFields(): string
{
$fields = [];
$foreignKeys = [];
$createdAtField = null;
$updatedAtField = null;
if (isset($this->config->fields) && !empty($this->config->fields)) {
foreach ($this->config->fields as $field) {
if ($field->name == 'created_at') {
$createdAtField = $field;
continue;
} else {
if ($field->name == 'updated_at') {
$updatedAtField = $field;
continue;
}
}
$fields[] = $field->migrationText;
if (!empty($field->foreignKeyText)) {
$foreignKeys[] = $field->foreignKeyText;
}
}
}
if ($createdAtField->name ?? '' === 'created_at' and $updatedAtField->name ?? '' === 'updated_at') {
$fields[] = '$table->timestamps();';
} else {
if ($createdAtField) {
$fields[] = $createdAtField->migrationText;
}
if ($updatedAtField) {
$fields[] = $updatedAtField->migrationText;
}
}
if ($this->config->options->softDelete) {
$softDeleteFieldName = config('laravel_generator.timestamps.deleted_at', 'deleted_at');
if ($softDeleteFieldName === 'deleted_at') {
$fields[] = '$table->softDeletes();';
} else {
$fields[] = '$table->softDeletes(\''.$softDeleteFieldName.'\');';
}
}
return implode(infy_nl_tab(1, 3), array_merge($fields, $foreignKeys));
}
public function rollback()
{
$fileName = 'create_'.$this->config->tableName.'_table.php';
/** @var SplFileInfo $allFiles */
$allFiles = File::allFiles($this->path);
$files = [];
if (!empty($allFiles)) {
foreach ($allFiles as $file) {
$files[] = $file->getFilename();
}
$files = array_reverse($files);
foreach ($files as $file) {
if (Str::contains($file, $fileName)) {
if ($this->rollbackFile($this->path, $file)) {
$this->config->commandComment('Migration file deleted: '.$file);
}
break;
}
}
}
}
}
This diff is collapsed.
<?php
namespace InfyOm\Generator\Generators;
class RepositoryGenerator extends BaseGenerator
{
private string $fileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->repository;
$this->fileName = $this->config->modelNames->name.'Repository.php';
}
public function variables(): array
{
return [
'fieldSearchable' => $this->getSearchableFields(),
];
}
public function generate()
{
$templateData = view('laravel-generator::repository.repository', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'Repository created: ');
$this->config->commandInfo($this->fileName);
}
protected function getSearchableFields()
{
$searchables = [];
foreach ($this->config->fields as $field) {
if ($field->isSearchable) {
$searchables[] = "'".$field->name."'";
}
}
return implode(','.infy_nl_tab(1, 2), $searchables);
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('Repository file deleted: '.$this->fileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators;
class RepositoryTestGenerator extends BaseGenerator
{
private string $fileName;
public function __construct()
{
parent::__construct();
$this->path = config('laravel_generator.path.repository_test', base_path('tests/Repositories/'));
$this->fileName = $this->config->modelNames->name.'RepositoryTest.php';
}
public function generate()
{
$templateData = view('laravel-generator::repository.repository_test', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'RepositoryTest created: ');
$this->config->commandInfo($this->fileName);
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('Repository Test file deleted: '.$this->fileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators\Scaffold;
use Exception;
use InfyOm\Generator\Generators\BaseGenerator;
class ControllerGenerator extends BaseGenerator
{
private string $templateType;
private string $fileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->controller;
$this->templateType = config('laravel_generator.templates', 'adminlte-templates');
$this->fileName = $this->config->modelNames->name.'Controller.php';
}
public function generate()
{
$variables = [];
switch ($this->config->tableType) {
case 'blade':
if ($this->config->options->repositoryPattern) {
$indexMethodView = 'index_method_repository';
} else {
$indexMethodView = 'index_method';
}
$variables['renderType'] = 'paginate(10)';
break;
case 'datatables':
$indexMethodView = 'index_method_datatable';
$this->generateDataTable();
break;
case 'livewire':
$indexMethodView = 'index_method_livewire';
$this->generateLivewireTable();
break;
default:
throw new Exception('Invalid Table Type');
}
if ($this->config->options->repositoryPattern) {
$viewName = 'controller_repository';
} else {
$viewName = 'controller';
}
$variables['indexMethod'] = view('laravel-generator::scaffold.controller.'.$indexMethodView, $variables)
->render();
$templateData = view('laravel-generator::scaffold.controller.'.$viewName, $variables)->render();
g_filesystem()->createFile($this->path.$this->fileName, $templateData);
$this->config->commandComment(infy_nl().'Controller created: ');
$this->config->commandInfo($this->fileName);
}
protected function generateDataTable()
{
$templateData = view('laravel-generator::scaffold.table.datatable', [
'columns' => implode(','.infy_nl_tab(1, 3), $this->generateDataTableColumns()),
])->render();
$path = $this->config->paths->dataTables;
$fileName = $this->config->modelNames->name.'DataTable.php';
g_filesystem()->createFile($path.$fileName, $templateData);
$this->config->commandComment(infy_nl().'DataTable created: ');
$this->config->commandInfo($fileName);
}
protected function generateLivewireTable()
{
$templateData = view('laravel-generator::scaffold.table.livewire', [
'columns' => implode(','.infy_nl_tab(1, 3), $this->generateLivewireTableColumns()),
])->render();
$path = $this->config->paths->livewireTables;
$fileName = $this->config->modelNames->plural.'Table.php';
g_filesystem()->createFile($path.$fileName, $templateData);
$this->config->commandComment(infy_nl().'LivewireTable created: ');
$this->config->commandInfo($fileName);
}
protected function generateDataTableColumns(): array
{
$dataTableColumns = [];
foreach ($this->config->fields as $field) {
if (!$field->inIndex) {
continue;
}
$dataTableColumns[] = trim(view(
$this->templateType.'::templates.scaffold.table.datatable.column',
$field->variables()
)->render());
}
return $dataTableColumns;
}
protected function generateLivewireTableColumns(): array
{
$livewireTableColumns = [];
foreach ($this->config->fields as $field) {
if (!$field->inIndex) {
continue;
}
$fieldTemplate = 'Column::make("'.$field->getTitle().'", "'.$field->name.'")'.infy_nl();
$fieldTemplate .= infy_tabs(4).'->sortable()';
if ($field->isSearchable) {
$fieldTemplate .= infy_nl().infy_tabs(4).'->searchable()';
}
$livewireTableColumns[] = $fieldTemplate;
}
return $livewireTableColumns;
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->fileName)) {
$this->config->commandComment('Controller file deleted: '.$this->fileName);
}
if ($this->config->tableType === 'datatables') {
if ($this->rollbackFile(
$this->config->paths->dataTables,
$this->config->modelNames->name.'DataTable.php'
)) {
$this->config->commandComment('DataTable file deleted: '.$this->fileName);
}
}
if ($this->config->tableType === 'livewire') {
if ($this->rollbackFile(
$this->config->paths->livewireTables,
$this->config->modelNames->plural.'Table.php'
)) {
$this->config->commandComment('Livewire Table file deleted: '.$this->fileName);
}
}
}
}
<?php
namespace InfyOm\Generator\Generators\Scaffold;
use Illuminate\Support\Str;
use InfyOm\Generator\Generators\BaseGenerator;
class MenuGenerator extends BaseGenerator
{
private string $templateType;
public function __construct()
{
parent::__construct();
$this->path = config('laravel_generator.path.menu_file', resource_path('views/layouts/menu.blade.php'));
$this->templateType = config('laravel_generator.templates', 'adminlte-templates');
}
public function generate()
{
$menuContents = g_filesystem()->getFile($this->path);
$menu = view($this->templateType.'::templates.layouts.menu_template')->render();
if (Str::contains($menuContents, $menu)) {
$this->config->commandInfo(infy_nl().'Menu '.$this->config->modelNames->humanPlural.' already exists, Skipping Adjustment.');
return;
}
$menuContents .= infy_nl().$menu;
g_filesystem()->createFile($this->path, $menuContents);
$this->config->commandComment(infy_nl().$this->config->modelNames->dashedPlural.' menu added.');
}
public function rollback()
{
$menuContents = g_filesystem()->getFile($this->path);
$menu = view($this->templateType.'::templates.layouts.menu_template')->render();
if (Str::contains($menuContents, $menu)) {
g_filesystem()->createFile($this->path, str_replace($menu, '', $menuContents));
$this->config->commandComment('menu deleted');
}
}
}
<?php
namespace InfyOm\Generator\Generators\Scaffold;
use InfyOm\Generator\Generators\BaseGenerator;
use InfyOm\Generator\Generators\ModelGenerator;
class RequestGenerator extends BaseGenerator
{
private string $createFileName;
private string $updateFileName;
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->request;
$this->createFileName = 'Create'.$this->config->modelNames->name.'Request.php';
$this->updateFileName = 'Update'.$this->config->modelNames->name.'Request.php';
}
public function generate()
{
$this->generateCreateRequest();
$this->generateUpdateRequest();
}
protected function generateCreateRequest()
{
$templateData = view('laravel-generator::scaffold.request.create', $this->variables())->render();
g_filesystem()->createFile($this->path.$this->createFileName, $templateData);
$this->config->commandComment(infy_nl().'Create Request created: ');
$this->config->commandInfo($this->createFileName);
}
protected function generateUpdateRequest()
{
$modelGenerator = new ModelGenerator();
$rules = $modelGenerator->generateUniqueRules();
$templateData = view('laravel-generator::scaffold.request.update', [
'uniqueRules' => $rules,
])->render();
g_filesystem()->createFile($this->path.$this->updateFileName, $templateData);
$this->config->commandComment(infy_nl().'Update Request created: ');
$this->config->commandInfo($this->updateFileName);
}
public function rollback()
{
if ($this->rollbackFile($this->path, $this->createFileName)) {
$this->config->commandComment('Create Request file deleted: '.$this->createFileName);
}
if ($this->rollbackFile($this->path, $this->updateFileName)) {
$this->config->commandComment('Update Request file deleted: '.$this->updateFileName);
}
}
}
<?php
namespace InfyOm\Generator\Generators\Scaffold;
use Illuminate\Support\Str;
use InfyOm\Generator\Generators\BaseGenerator;
class RoutesGenerator extends BaseGenerator
{
public function __construct()
{
parent::__construct();
$this->path = $this->config->paths->routes;
}
public function generate()
{
$routeContents = g_filesystem()->getFile($this->path);
$routes = view('laravel-generator::scaffold.routes')->render();
if (Str::contains($routeContents, $routes)) {
$this->config->commandInfo(infy_nl().'Route '.$this->config->modelNames->dashedPlural.' already exists, Skipping Adjustment.');
return;
}
$routeContents .= infy_nl().$routes;
g_filesystem()->createFile($this->path, $routeContents);
$this->config->commandComment(infy_nl().$this->config->modelNames->dashedPlural.' routes added.');
}
public function rollback()
{
$routeContents = g_filesystem()->getFile($this->path);
$routes = view('laravel-generator::scaffold.routes')->render();
if (Str::contains($routeContents, $routes)) {
$routeContents = str_replace($routes, '', $routeContents);
g_filesystem()->createFile($this->path, $routeContents);
$this->config->commandComment('scaffold routes deleted');
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/**
* Class {{ $config->modelNames->name }}APIController
*/
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment