migrate to gtea from bistbucket

This commit is contained in:
2026-03-15 17:08:23 +07:00
commit 129ca2260c
3716 changed files with 566316 additions and 0 deletions

View File

@@ -0,0 +1,217 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
class GenerateCrudServiceCommand extends GeneratorCommand
{
protected $name = 'make:crud';
protected $description = 'Generate CRUD operations including controller, requests, service, interface, views, and routes for a given model';
public function handle(): bool
{
$model = $this->argument('model');
$path = $this->option('path') ?? '';
// Generate model and migration
// $this->generateModelWithMigration($model, $path);
// Generate controller
$this->generateController($model, $path = 'WEB');
// Generate request classes
$this->generateRequestClass($model, 'Store', $path = $model);
$this->generateRequestClass($model, 'Update', $path = $model);
// Generate service and interface
$this->generateService($model, $path = $model);
$this->generateInterface($model, $path = $model);
$this->generateDataTable($model, $path = $model);
// Generate views
$this->generateView($model, 'index');
$this->generateView($model, 'create');
$this->generateView($model, 'edit');
// Generate route file
$this->generateRouteFile($model);
// Now, add API specific generation
// $this->generateApiController($model);
return true;
}
// protected function generateModelWithMigration($model, $path)
// {
// $namespace = $path ? Str::replace('/', '\\', $path) : '';
// $this->call('make:model', [
// 'name' => ($namespace ? $namespace . '\\' : '') . $model,
// '--migration' => true, // generate migration automatically
// ]);
// }
protected function generateController($model, $path)
{
$controllerName = "{$model}Controller";
$namespace = 'App\\Http\\Controllers\\'.($path ? Str::replace('/', '\\', $path).'\\' : '');
$this->call('make:controller', [
'name' => $namespace.$controllerName,
'--model' => $model,
'--path' => $path,
]);
}
protected function generateApiController($model)
{
$controllerName = "{$model}Controller";
$namespace = 'App\\Http\\Controllers\\API';
$controllerPath = app_path("Http/Controllers/API/{$controllerName}.php");
// Load the custom API controller stub
$stub = file_get_contents(resource_path('stubs/api-controller.stub'));
// Replace placeholder values in the stub
$content = str_replace(
['DummyNamespace', 'DummyFullModelClass', 'DummyClass', 'DummyModel', 'model'],
[
$namespace,
"App\\Models\\{$model}",
"{$model}Controller",
"{$model}",
strtolower($model),
],
$stub
);
// Write the controller file to the existing directory
file_put_contents($controllerPath, $content);
}
protected function generateRequestClass($model, $action, $path)
{
$name = "{$model}{$action}Request";
$namespace = 'App\\Http\\Requests\\'.($path ? Str::replace('/', '\\', $path).'\\' : '');
$this->call('make:request', [
'name' => $namespace.$name,
]);
}
protected function generateInterface($model, $path)
{
$interfaceName = "{$model}Interface";
$namespace = 'App\\Interfaces\\'.($path ? Str::replace('/', '\\', $path).'\\' : '');
$this->call('make:interface-file', [
'name' => $namespace.$interfaceName,
]);
}
protected function generateService($model, $path)
{
$serviceName = "{$model}Service";
$namespace = 'App\\Services\\'.($path ? Str::replace('/', '\\', $path).'\\' : '');
$this->call('make:service-file', [
'name' => $namespace.$serviceName,
'--model' => $model,
]);
}
protected function generateDataTable($model, $path)
{
$dataTableName = "{$model}DataTable";
$namespace = 'App\\DataTables\\'.($path ? Str::replace('/', '\\', $path).'\\' : '');
$this->call('make:datatable-file', [
'name' => $namespace.$dataTableName,
'--model' => $model,
]);
}
protected function generateView($model, $view)
{
$modelLower = strtolower($model);
$viewPath = resource_path("views/backend/{$modelLower}/{$view}.blade.php");
if (! file_exists($viewPath)) {
$this->makeDirectory($viewPath);
file_put_contents($viewPath, $this->getViewStub($view, $model));
}
}
protected function getViewStub($view, $model)
{
$stub = file_get_contents(resource_path("stubs/{$view}.stub"));
// Replace DummyModel with the actual model name
return str_replace(['DummyModel', 'model'], [$model, strtolower($model)], $stub);
}
protected function generateRouteFile($model)
{
$modelLower = strtolower($model);
$webRouteFile = base_path('routes/web.php');
// $apiRouteFile = base_path('routes/api.php');
// Web route content
$webContent = <<<EOL
Route::resource('{$modelLower}s', App\Http\Controllers\\WEB\\{$model}Controller::class);
EOL;
// API route content
// $apiContent = <<<EOL
// Route::get('all-{$modelLower}', [App\Http\Controllers\API\\{$model}Controller::class, 'all']);
// Route::apiResource('{$modelLower}s', App\Http\Controllers\API\\{$model}Controller::class);
// EOL;
// Include in web.php
$this->includeInFile($webRouteFile, $webContent);
// Include in api.php
// $this->includeInFile($apiRouteFile, $apiContent);
}
protected function includeInFile($filePath, $content)
{
$includeStatement = trim($content);
// Ensure the file doesn't already include the content
$currentContent = file_get_contents($filePath);
if (strpos($currentContent, $includeStatement) === false) {
file_put_contents($filePath, PHP_EOL.$includeStatement.PHP_EOL, FILE_APPEND);
}
}
protected function getStub()
{
return '';
}
protected function getDefaultNamespace($rootNamespace)
{
return '';
}
protected function getArguments()
{
return [
['model', InputOption::VALUE_REQUIRED, 'The name of the model'],
];
}
protected function getOptions()
{
return [
['path', null, InputOption::VALUE_OPTIONAL, 'The optional path for the generated files'],
];
}
}

View File

@@ -0,0 +1,377 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class MakeModuleEntity extends Command
{
protected $signature = 'make:module-entity {module} {name}';
protected $description = 'Create module-based model, controller, repository, request, migration, and route';
public function handle()
{
$module = Str::studly($this->argument('module'));
$name = Str::studly($this->argument('name'));
$pluralName = Str::pluralStudly($name);
$snakePlural = Str::snake($pluralName);
$basePath = base_path("Modules/{$module}");
$paths = [
'model' => "{$basePath}/app/Models/{$name}.php",
'controller' => "{$basePath}/app/Http/Controllers/API/{$name}Controller.php",
'storeRequest' => "{$basePath}/app/Http/Requests/{$name}/{$name}StoreRequest.php",
'updateRequest' => "{$basePath}/app/Http/Requests/{$name}/{$name}UpdateRequest.php",
'repository' => "{$basePath}/Repositories/{$name}Repository.php",
'migration' => "{$basePath}/Database/Migrations/".date('Y_m_d_His')."_create_{$snakePlural}_table.php",
'route' => "{$basePath}/routes/api.php",
];
// Make directories
foreach ($paths as $path) {
File::ensureDirectoryExists(dirname($path));
}
// Generate Model with Fillable Template
File::put($paths['model'], "<?php
namespace Modules\\{$module}\\Models;
use Illuminate\Database\Eloquent\Model;
class {$name} extends Model
{
protected \$fillable = [
'restaurant_id',
'name',
'status',
'created_at',
'updated_at',
'deleted_at'
];
public const TABLE_NAME = '".$snakePlural."';
protected \$table = self::TABLE_NAME;
}");
// Controller with extended functionality
File::put($paths['controller'], "<?php
namespace Modules\\{$module}\\Http\\Controllers\\API;
use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\JsonResponse;
use Modules\\{$module}\\Http\\Requests\\{$name}\\{$name}StoreRequest;
use Modules\\{$module}\\Http\\Requests\\{$name}\\{$name}UpdateRequest;
use Modules\\{$module}\\Repositories\\{$name}Repository;
class {$name}Controller extends Controller
{
public function __construct(private {$name}Repository \$repo) {}
public function index(): JsonResponse
{
try {
return \$this->responseSuccess(\$this->repo->getAll(request()->all()),'{$name} has been fetched successfully.');
} catch (Exception \$e) {
return \$this->responseError([], \$e->getMessage());
}
}
public function store({$name}StoreRequest \$request): JsonResponse
{
try {
return \$this->responseSuccess(\$this->repo->create(\$request->all()),'{$name} has been created successfully.');
} catch (\Illuminate\Database\QueryException \$exception) {
return \$this->responseError([], 'Database error: '.\$exception->getMessage());
} catch (Exception \$e) {
return \$this->responseError([], \$e->getMessage());
}
}
public function show(\$id): JsonResponse
{
try {
return \$this->responseSuccess(\$this->repo->getById(\$id), '{$name} has been fetched successfully.');
} catch (Exception \$e) {
return \$this->responseError([], \$e->getMessage());
}
}
public function update({$name}UpdateRequest \$request, \$id): JsonResponse
{
try {
return \$this->responseSuccess(\$this->repo->update(\$id, \$request->all()),'{$name} has been updated successfully.');
} catch (Exception \$e) {
return \$this->responseError([], \$e->getMessage());
}
}
public function destroy(\$id): JsonResponse
{
try {
return \$this->responseSuccess(\$this->repo->delete(\$id),'{$name} has been deleted successfully.');
} catch (Exception \$e) {
return \$this->responseError([], \$e->getMessage());
}
}
}");
// Generate Migration Content
File::put($paths['migration'], "<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('{$snakePlural}', function (Blueprint \$table) {
\$table->id();
\$table->unsignedBigInteger('restaurant_id')->nullable();
\$table->string('name');
\$table->smallInteger('status')->default(1)->comment('1=Active, 2=InActive');
\$table->timestamps();
\$table->softDeletes();
});
}
public function down(): void
{
Schema::dropIfExists('{$snakePlural}');
}
};
");
// Request classes
File::put($paths['storeRequest'], "<?php
namespace Modules\\{$module}\\Http\\Requests\\{$name};
use Illuminate\Foundation\Http\FormRequest;
class {$name}StoreRequest extends FormRequest
{
public function rules(): array
{
return [
// validation rules
];
}
public function authorize(): bool
{
return true;
}
}");
File::put($paths['updateRequest'], "<?php
namespace Modules\\{$module}\\Http\\Requests\\{$name};
use Illuminate\Foundation\Http\FormRequest;
class {$name}UpdateRequest extends FormRequest
{
public function rules(): array
{
return [
// validation rules
];
}
public function authorize(): bool
{
return true;
}
}");
// Repository with custom logic
File::put($paths['repository'], "<?php
namespace Modules\\{$module}\\Repositories;
use App\Abstracts\EntityRepository;
use Modules\\{$module}\\Models\\{$name};
use Exception;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Symfony\Component\HttpFoundation\Response;
class {$name}Repository extends EntityRepository
{
public string \$table = {$name}::TABLE_NAME;
protected array \$fillableColumns = [
'restaurant_id',
'name',
'status',
'created_by',
'created_at',
'updated_at',
'deleted_at'
];
protected function getQuery(): Builder
{
return parent::getQuery();
}
protected function getFilterData(array \$filterData = []): array
{
\$defaultArgs = [
'perPage' => 10,
'search' => '',
'orderBy' => 'id',
'order' => 'desc',
'with_deleted' => false,
];
return array_merge(\$defaultArgs, \$filterData);
}
private function get{$name}Query(): Builder
{
return \$this->getQuery()
->select(
\"{\$this->table}.id\",
\"{\$this->table}.restaurant_id\",
\"{\$this->table}.name\",
\"{\$this->table}.status\",
\"{\$this->table}.created_at\",
\"{\$this->table}.deleted_at\"
);
}
protected function filterSearchQuery(Builder|EloquentBuilder \$query, string \$searchedText): Builder
{
\$searchable = \"%\$searchedText%\";
return \$query->where(\"{\$this->table}.name\", 'LIKE', \$searchable)
->orWhere(\"{\$this->table}.status\", 'LIKE', \$searchable);
}
public function getAll(array \$filterData = []): Paginator
{
\$filter = \$this->getFilterData(\$filterData);
\$query = \$this->get{$name}Query();
if (! \$filter['with_deleted']) {
\$query->whereNull(\"{\$this->table}.deleted_at\");
}
if (!empty(\$filter['search'])) {
\$query = \$this->filterSearchQuery(\$query, \$filter['search']);
}
return \$query
->orderBy(\$filter['orderBy'], \$filter['order'])
->paginate(\$filter['perPage']);
}
public function getCount(array \$filterData = []): int
{
\$filter = \$this->getFilterData(\$filterData);
\$query = \$this->getQuery();
if (! \$filter['with_deleted']) {
\$query->whereNull(\"{\$this->table}.deleted_at\");
}
return \$query->count();
}
/**
* @throws Exception
*/
public function getByColumn(string \$columnName, \$columnValue, array \$selects = ['*']): ?object
{
\$item = \$this->get{$name}Query()
->where(\$columnName, \$columnValue)
->first(\$selects);
if (empty(\$item)) {
throw new Exception(
\$this->getExceptionMessage(static::MESSAGE_ITEM_DOES_NOT_EXIST_MESSAGE),
Response::HTTP_NOT_FOUND
);
}
return \$item;
}
/**
* @throws Exception
*/
public function create(array \$data): object
{
\$data = \$this->prepareForDB(\$data);
\$id = \$this->getQuery()->insertGetId(\$data);
return {$name}::find(\$id);
}
/**
* @throws Exception
*/
public function update(int \$id, array \$data): object
{
\$item = {$name}::findOrFail(\$id);
\$data = \$this->prepareForDB(\$data, \$item);
parent::update(\$id, \$data);
return \$this->getById(\$id);
}
/**
* @throws Exception
*/
public function prepareForDB(array \$data, ?object \$item = null): array
{
\$data = parent::prepareForDB(\$data, \$item);
if (empty(\$item)) {
\$data['created_at'] = now();
\$data['restaurant_id'] = \$this->getCurrentRestaurantId();
\$data['status'] = 1;
if (!empty(\$data['image']) && \$data['image'] instanceof \Illuminate\Http\UploadedFile) {
\$data['image'] = fileUploader('{$module}/', 'png', \$data['image']);
}
} else {
if (!empty(\$data['image']) && \$data['image'] instanceof \Illuminate\Http\UploadedFile) {
\$data['image'] = fileUploader('{$module}/', 'png', \$data['image'], \$item->image);
}
\$data['updated_at'] = now();
}
return \$data;
}
protected function getExceptionMessages(): array
{
return [
static::MESSAGE_ITEM_DOES_NOT_EXIST_MESSAGE => '{$name} does not exist.',
static::MESSAGE_ITEM_COULD_NOT_BE_DELETED => '{$name} could not be deleted.',
];
}
}
");
// Create module route
if (! File::exists($paths['route'])) {
File::put($paths['route'], "<?php\n\nuse Illuminate\Support\Facades\Route;\n\n");
}
File::append($paths['route'], "\nRoute::apiResource('".Str::kebab($snakePlural)."', \\Modules\\{$module}\\Http\\Controllers\\API\\{$name}Controller::class);");
// Add module route loader to RouteServiceProvider (if not already done manually)
$this->info("{$name} entity created under module {$module} with full structure!");
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class NewActionMakeCommand extends GeneratorCommand
{
protected $name = 'make:action';
protected $description = 'Create a new action class';
protected $type = 'Action';
protected function getStub()
{
return resource_path('stubs/action.stub');
}
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\\Actions';
}
protected function buildClass($name)
{
$stub = parent::buildClass($name);
$model = $this->option('model');
$action = $this->option('action');
return str_replace(
['DummyModel', 'DummyAction'],
[$model, $action],
$stub
);
}
protected function getOptions()
{
return [
['model', null, InputOption::VALUE_REQUIRED, 'The name of the model'],
['action', null, InputOption::VALUE_REQUIRED, 'The action type (Create, Read, Update, Delete)'],
];
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class NewControllerMakeCommand extends GeneratorCommand
{
protected $name = 'make:controller';
protected $description = 'Create a new resource controller class';
protected $type = 'Controller';
protected function getStub()
{
return resource_path('stubs/controller.service.stub');
}
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\\Http\\Controllers';
}
protected function buildClass($name)
{
$stub = parent::buildClass($name);
$model = $this->option('model');
$modelLower = strtolower($model);
return str_replace(
['DummyModel', 'model'],
[$model, $modelLower],
$stub
);
}
protected function getOptions()
{
return [
['model', null, InputOption::VALUE_REQUIRED, 'The name of the model'],
['path', null, InputOption::VALUE_OPTIONAL, 'The optional path for the generated files'],
];
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class NewDataTableMakeCommand extends GeneratorCommand
{
protected $name = 'make:datatable-file';
protected $description = 'Create a new yajra DataTables class';
protected $type = 'DataTable';
protected function getStub()
{
return resource_path('stubs/datatable.stub');
}
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\\DataTables';
}
protected function buildClass($name)
{
$stub = parent::buildClass($name);
$model = $this->option('model');
$namespaceModel = 'App\\Models\\'.$model;
return str_replace(
['DummyModel', 'DummyModelNamespace'],
[$model, $namespaceModel],
$stub
);
}
protected function getOptions()
{
return [
['model', null, InputOption::VALUE_REQUIRED, 'The name of the model'],
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class NewInterfaceMakeCommand extends GeneratorCommand
{
protected $name = 'make:interface-file';
protected $description = 'Create a new interface class';
protected $type = 'Interface';
protected function getStub()
{
return resource_path('stubs/interface.stub');
}
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\\Interfaces';
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
class NewRequestMakeCommand extends GeneratorCommand
{
protected $name = 'make:request';
protected $description = 'Create a new form request class';
protected $type = 'Request';
protected function getStub()
{
return resource_path('stubs/request.stub');
}
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\\Http\\Requests';
}
protected function buildClass($name)
{
$stub = parent::buildClass($name);
return $stub;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use App\Jobs\GenerateMonthlyInvoices;
use Illuminate\Console\Command;
class RunInvoiceJobLoop extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'invoice:loop';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run GenerateMonthlyInvoices job every 5 seconds (for testing)';
public function handle()
{
$this->info('Starting job loop... Press Ctrl+C to stop.');
// while (true) {
// dispatch(new GenerateMonthlyInvoices);
// $this->info('Job dispatched at '.now());
// sleep(300); // wait 5 seconds
// }
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class ServiceFileMakeCommand extends GeneratorCommand
{
protected $name = 'make:service-file';
protected $description = 'Create a new service class';
protected $type = 'Service';
protected function getStub()
{
return resource_path('stubs/service.stub');
}
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\\Services';
}
protected function buildClass($name)
{
$stub = parent::buildClass($name);
$model = $this->option('model');
$namespaceModel = 'App\\Models\\'.$model;
return str_replace(
['DummyModel', 'DummyModelNamespace'],
[$model, $namespaceModel],
$stub
);
}
protected function getOptions()
{
return [
['model', null, InputOption::VALUE_REQUIRED, 'The name of the model'],
];
}
}

View File

@@ -0,0 +1,180 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\Authentication\Models\Restaurant;
use Modules\Authentication\Models\Setting;
class SyncAllSettingsCommand extends Command
{
protected $signature = 'settings:sync-all';
// php artisan settings:sync-all
protected $description = 'Sync all setting keys for each restaurant if missing';
protected $defaultKeys = [
'restaurant_name',
'site_title',
'phone',
'email',
'language',
'google_map',
'address',
'on_google_map',
'restaurant_code',
'currency_symbol',
'logo',
'mail_type',
'disabled_website',
'copyright_text',
'facebook_link',
'google_plus_link',
'youtube_link',
'whats_app_link',
'twitter_link',
'eiin_code',
'sms_gateway',
'bulk_sms_api_key',
'bulk_sms_sender_id',
'twilio_sid',
'twilio_token',
'twilio_from_number',
'header_notice',
'app_version',
'app_url',
'tagline',
'favicon',
'theme_color',
'background_image',
'tax_type',
'tax_percentage',
'service_charge',
'default_currency',
'billing_prefix',
'invoice_footer',
'enable_kitchen_print',
'enable_customer_copy',
'enable_online_order',
'delivery_charge',
'minimum_order_amount',
'auto_accept_order',
'estimated_preparation_time',
'slack_webhook_url',
'telegram_bot_token',
'telegram_chat_id',
'twilio_sms_enabled',
'email_notifications',
'whatsapp_notifications',
'auto_backup',
'report_timezone',
'data_retention_days',
'sidebar_collapsed',
'dark_mode',
'default_dashboard',
'razorpay_key',
'razorpay_secret',
'stripe_key',
'stripe_secret',
'cash_on_delivery',
'max_table_capacity',
'default_shift_start',
'default_shift_end',
'auto_logout_idle_minutes',
'primary_color',
'secondary_color',
'primary_container_color',
'dark_primary_color',
'dark_secondary_color',
'dark_container_color',
'text_color',
'dark_text_color',
'sidebar_selected_bg_color',
'sidebar_selected_text_color',
'is_online',
'latitude',
'longitude',
'delivery_radius_km',
'delivery_fee',
'delivery_partner_count',
'delivery_time_avg',
'pickup_enabled',
'opening_time',
'closing_time',
'auto_accept_orders',
'pre_order_enabled',
'max_order_capacity',
'avg_rating',
'review_count',
'total_orders',
'last_order_time',
'last_active_time',
'loyalty_points_enabled',
'offers_enabled',
'social_media_links',
'settings',
'uuid',
'email_smtp_host',
'email_smtp_port',
'email_smtp_username',
'email_smtp_password',
'email_smtp_encryption',
'twilio_api_key',
'twilio_api_secret',
'twilio_sender_id',
'twilio_api_url',
'twilio_is_default',
'nexmo_api_key',
'nexmo_api_secret',
'nexmo_sender_id',
'nexmo_api_url',
'nexmo_is_default',
'muthofun_api_key',
'smsglobal_api_key',
'smsglobal_api_secret',
'smsglobal_sender_id',
'smsglobal_api_url',
'smsglobal_extra_key',
'smsglobal_is_default',
];
public function handle()
{
$restaurants = Restaurant::all();
foreach ($restaurants as $restaurant) {
foreach ($this->defaultKeys as $key) {
$extraValue = [];
$defaultValues = [
'restaurant_name' => $extraValue,
];
$setting = Setting::where('restaurant_id', $restaurant->id)
->where('key', $key)
->first();
if (! $setting) {
// Create if it doesn't exist
Setting::create([
'restaurant_id' => $restaurant->id,
'key' => $key,
'value' => $defaultValues[$key] ?? null,
'type' => 'vendor',
'is_active' => true,
]);
$this->info("Added missing setting '{$key}' for Restaurant ID: {$restaurant->id}");
} elseif (is_null($setting->value)) {
// Update only if value is NULL
if (array_key_exists($key, $defaultValues)) {
$setting->update(['value' => $defaultValues[$key]]);
$this->info("Updated '{$key}' for Restaurant ID: {$restaurant->id} because value was null");
}
} else {
// Skip if already exists with a non-null value
$this->line("Setting '{$key}' already exists for Restaurant ID: {$restaurant->id} with non-null value — skipped.");
}
}
}
$this->info('All settings sync complete.');
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Console\Commands\Traits;
use ReflectionClass;
trait ServiceProviderInjector
{
public function injectCodeToRegisterMethod($appServiceProviderFile, $codeToAdd)
{
$reflectionClass = new ReflectionClass(\App\Providers\AppServiceProvider::class);
$reflectionMethod = $reflectionClass->getMethod('register');
$methodBody = file($appServiceProviderFile);
$startLine = $reflectionMethod->getStartLine() - 1;
$endLine = $reflectionMethod->getEndLine() - 1;
array_splice($methodBody, $endLine, 0, $codeToAdd);
$modifiedCode = implode('', $methodBody);
file_put_contents($appServiceProviderFile, $modifiedCode);
}
}