From ef59839e43d38b74f6d8adee71a63035896132b3 Mon Sep 17 00:00:00 2001 From: Javad Date: Fri, 9 Dec 2022 17:41:01 +0330 Subject: [PATCH 01/86] feature: some modification to support only single version of php(8.0) - Inheritance from parent classes in package - add enum generator --- Readme.md | 2 +- composer.json | 8 +- config/repository.php | 13 +- src/Commands/MakeAll.php | 1 + src/Commands/MakeEntity.php | 5 +- src/Commands/MakeEnum.php | 124 ++++++++ src/Commands/MakeFactory.php | 9 +- src/Commands/MakeInterfaceRepository.php | 8 +- src/Commands/MakeMySqlRepository.php | 13 +- src/Commands/MakeRedisRepository.php | 12 +- src/Commands/MakeRepository.php | 8 +- src/Commands/MakeResource.php | 10 +- src/DatabaseRepositoryServiceProvider.php | 76 +---- .../Models/Entity/Entity.php | 12 +- .../Enum.stub => src/Models/Enums/Enum.php | 4 +- .../Models/Enums/GriewFilterOperator.php | 4 +- .../Models/Factories/Factory.php | 6 +- .../Models/Factories/IFactory.php | 6 +- .../Models/Repositories/MySqlRepository.php | 8 +- .../Models/Repositories/RedisRepository.php | 6 +- .../Models/Resources/IResource.php | 4 +- .../Models/Resources/Resource.php | 4 +- .../entity.accessors.stub} | 0 .../entity.attribute.stub} | 0 .../entity.class.stub} | 4 +- stubs/Enums/enum.attribute.stub | 1 + stubs/Enums/enum.class.stub | 10 + .../factory.class.stub} | 3 +- .../factory.setter.stub} | 0 stubs/Models/PHP7.0/Entity/Entity.stub | 158 ---------- stubs/Models/PHP7.0/Factory/Factory.stub | 26 -- stubs/Models/PHP7.0/Factory/IFactory.stub | 22 -- stubs/Models/PHP7.4/Entity/Entity.stub | 157 ---------- stubs/Models/PHP7.4/Enums/Enum.stub | 44 --- .../PHP7.4/Enums/GriewFilterOperator.stub | 29 -- stubs/Models/PHP7.4/Factory/Factory.stub | 30 -- stubs/Models/PHP7.4/Factory/IFactory.stub | 22 -- .../PHP7.4/Repository/RedisRepository.stub | 20 -- stubs/Models/PHP7.4/Resource/IResource.stub | 13 - .../PHP8.0/Repository/MySqlRepository.stub | 277 ------------------ stubs/Models/PHP8.0/Resource/Resource.stub | 30 -- stubs/PHP7.0/repository.entity.accessors.stub | 16 - stubs/PHP7.0/repository.entity.attribute.stub | 1 - stubs/PHP7.0/repository.entity.class.stub | 7 - stubs/PHP7.0/repository.factory.class.stub | 21 -- stubs/PHP7.0/repository.mysql.getAllBy.stub | 13 - stubs/PHP7.0/repository.mysql.getOneBy.stub | 13 - stubs/PHP7.4/repository.entity.class.stub | 8 - stubs/PHP7.4/repository.factory.setter.stub | 1 - ...epository.interface.deleteAndUndelete.stub | 4 - stubs/PHP7.4/repository.mysql.class.stub | 21 -- stubs/PHP7.4/repository.mysql.create.stub | 15 - .../repository.mysql.deleteAndUndelete.stub | 26 -- stubs/PHP7.4/repository.mysql.getOneBy.stub | 13 - stubs/PHP7.4/repository.mysql.getter.stub | 1 - stubs/PHP7.4/repository.mysql.update.stub | 12 - stubs/PHP8.0/repository.entity.accessors.stub | 16 - stubs/PHP8.0/repository.entity.attribute.stub | 1 - stubs/PHP8.0/repository.factory.class.stub | 21 -- stubs/PHP8.0/repository.factory.setter.stub | 1 - stubs/PHP8.0/repository.interface.class.stub | 9 - stubs/PHP8.0/repository.interface.create.stub | 2 - .../PHP8.0/repository.interface.getAllBy.stub | 2 - .../PHP8.0/repository.interface.getOneBy.stub | 2 - stubs/PHP8.0/repository.interface.update.stub | 2 - stubs/PHP8.0/repository.mysql.getAllBy.stub | 13 - stubs/PHP8.0/repository.mysql.timeField.stub | 1 - stubs/PHP8.0/repository.resource.class.stub | 31 -- .../repository.resource.getter.default.stub | 1 - .../repository.resource.getter.foreign.stub | 1 - .../Base/base.attribute.sql.stub} | 0 .../Base/base.class.stub} | 0 .../Base/base.function.stub} | 0 .../Base/base.setter.sql.stub} | 0 .../Interface/interface.class.stub} | 0 .../Interface/interface.create.stub} | 0 .../interface.deleteAndUndelete.stub} | 0 .../Interface/interface.getAllBy.stub} | 0 .../Interface/interface.getOneBy.stub} | 0 .../Interface/interface.update.stub} | 0 .../Mysql/mysql.class.stub} | 4 +- .../Mysql/mysql.create.stub} | 0 .../Mysql/mysql.deleteAndUndelete.stub} | 0 .../Mysql/mysql.getAllBy.stub} | 0 .../Mysql/mysql.getOneBy.stub} | 0 .../Mysql/mysql.getter.stub} | 0 .../Mysql/mysql.setter.stub} | 0 .../Mysql/mysql.timeField.stub} | 0 .../Mysql/mysql.update.stub} | 0 .../resource.class.stub} | 6 +- .../resource.getter.default.stub} | 0 .../resource.getter.foreign.stub} | 0 92 files changed, 228 insertions(+), 1246 deletions(-) create mode 100644 src/Commands/MakeEnum.php rename stubs/Models/PHP8.0/Entity/Entity.stub => src/Models/Entity/Entity.php (94%) rename stubs/Models/PHP8.0/Enums/Enum.stub => src/Models/Enums/Enum.php (93%) rename stubs/Models/PHP8.0/Enums/GriewFilterOperator.stub => src/Models/Enums/GriewFilterOperator.php (95%) rename stubs/Models/PHP8.0/Factory/Factory.stub => src/Models/Factories/Factory.php (84%) rename stubs/Models/PHP8.0/Factory/IFactory.stub => src/Models/Factories/IFactory.php (77%) rename stubs/Models/PHP7.4/Repository/MySqlRepository.stub => src/Models/Repositories/MySqlRepository.php (97%) rename stubs/Models/PHP8.0/Repository/RedisRepository.stub => src/Models/Repositories/RedisRepository.php (73%) rename stubs/Models/PHP8.0/Resource/IResource.stub => src/Models/Resources/IResource.php (63%) rename stubs/Models/PHP7.4/Resource/Resource.stub => src/Models/Resources/Resource.php (83%) rename stubs/{PHP7.4/repository.entity.accessors.stub => Entities/entity.accessors.stub} (100%) rename stubs/{PHP7.4/repository.entity.attribute.stub => Entities/entity.attribute.stub} (100%) rename stubs/{PHP8.0/repository.entity.class.stub => Entities/entity.class.stub} (68%) create mode 100644 stubs/Enums/enum.attribute.stub create mode 100644 stubs/Enums/enum.class.stub rename stubs/{PHP7.4/repository.factory.class.stub => Factories/factory.class.stub} (88%) rename stubs/{PHP7.0/repository.factory.setter.stub => Factories/factory.setter.stub} (100%) delete mode 100644 stubs/Models/PHP7.0/Entity/Entity.stub delete mode 100644 stubs/Models/PHP7.0/Factory/Factory.stub delete mode 100644 stubs/Models/PHP7.0/Factory/IFactory.stub delete mode 100644 stubs/Models/PHP7.4/Entity/Entity.stub delete mode 100644 stubs/Models/PHP7.4/Enums/Enum.stub delete mode 100644 stubs/Models/PHP7.4/Enums/GriewFilterOperator.stub delete mode 100644 stubs/Models/PHP7.4/Factory/Factory.stub delete mode 100644 stubs/Models/PHP7.4/Factory/IFactory.stub delete mode 100644 stubs/Models/PHP7.4/Repository/RedisRepository.stub delete mode 100644 stubs/Models/PHP7.4/Resource/IResource.stub delete mode 100644 stubs/Models/PHP8.0/Repository/MySqlRepository.stub delete mode 100644 stubs/Models/PHP8.0/Resource/Resource.stub delete mode 100644 stubs/PHP7.0/repository.entity.accessors.stub delete mode 100644 stubs/PHP7.0/repository.entity.attribute.stub delete mode 100644 stubs/PHP7.0/repository.entity.class.stub delete mode 100644 stubs/PHP7.0/repository.factory.class.stub delete mode 100644 stubs/PHP7.0/repository.mysql.getAllBy.stub delete mode 100644 stubs/PHP7.0/repository.mysql.getOneBy.stub delete mode 100644 stubs/PHP7.4/repository.entity.class.stub delete mode 100644 stubs/PHP7.4/repository.factory.setter.stub delete mode 100644 stubs/PHP7.4/repository.interface.deleteAndUndelete.stub delete mode 100644 stubs/PHP7.4/repository.mysql.class.stub delete mode 100644 stubs/PHP7.4/repository.mysql.create.stub delete mode 100644 stubs/PHP7.4/repository.mysql.deleteAndUndelete.stub delete mode 100644 stubs/PHP7.4/repository.mysql.getOneBy.stub delete mode 100644 stubs/PHP7.4/repository.mysql.getter.stub delete mode 100644 stubs/PHP7.4/repository.mysql.update.stub delete mode 100644 stubs/PHP8.0/repository.entity.accessors.stub delete mode 100644 stubs/PHP8.0/repository.entity.attribute.stub delete mode 100644 stubs/PHP8.0/repository.factory.class.stub delete mode 100644 stubs/PHP8.0/repository.factory.setter.stub delete mode 100644 stubs/PHP8.0/repository.interface.class.stub delete mode 100644 stubs/PHP8.0/repository.interface.create.stub delete mode 100644 stubs/PHP8.0/repository.interface.getAllBy.stub delete mode 100644 stubs/PHP8.0/repository.interface.getOneBy.stub delete mode 100644 stubs/PHP8.0/repository.interface.update.stub delete mode 100644 stubs/PHP8.0/repository.mysql.getAllBy.stub delete mode 100644 stubs/PHP8.0/repository.mysql.timeField.stub delete mode 100644 stubs/PHP8.0/repository.resource.class.stub delete mode 100644 stubs/PHP8.0/repository.resource.getter.default.stub delete mode 100644 stubs/PHP8.0/repository.resource.getter.foreign.stub rename stubs/{PHP8.0/repository.base.attribute.sql.stub => Repositories/Base/base.attribute.sql.stub} (100%) rename stubs/{PHP8.0/repository.base.class.stub => Repositories/Base/base.class.stub} (100%) rename stubs/{PHP8.0/repository.base.function.stub => Repositories/Base/base.function.stub} (100%) rename stubs/{PHP8.0/repository.base.setter.sql.stub => Repositories/Base/base.setter.sql.stub} (100%) rename stubs/{PHP7.4/repository.interface.class.stub => Repositories/Interface/interface.class.stub} (100%) rename stubs/{PHP7.4/repository.interface.create.stub => Repositories/Interface/interface.create.stub} (100%) rename stubs/{PHP8.0/repository.interface.deleteAndUndelete.stub => Repositories/Interface/interface.deleteAndUndelete.stub} (100%) rename stubs/{PHP7.4/repository.interface.getAllBy.stub => Repositories/Interface/interface.getAllBy.stub} (100%) rename stubs/{PHP7.4/repository.interface.getOneBy.stub => Repositories/Interface/interface.getOneBy.stub} (100%) rename stubs/{PHP7.4/repository.interface.update.stub => Repositories/Interface/interface.update.stub} (100%) rename stubs/{PHP8.0/repository.mysql.class.stub => Repositories/Mysql/mysql.class.stub} (88%) rename stubs/{PHP8.0/repository.mysql.create.stub => Repositories/Mysql/mysql.create.stub} (100%) rename stubs/{PHP8.0/repository.mysql.deleteAndUndelete.stub => Repositories/Mysql/mysql.deleteAndUndelete.stub} (100%) rename stubs/{PHP7.4/repository.mysql.getAllBy.stub => Repositories/Mysql/mysql.getAllBy.stub} (100%) rename stubs/{PHP8.0/repository.mysql.getOneBy.stub => Repositories/Mysql/mysql.getOneBy.stub} (100%) rename stubs/{PHP8.0/repository.mysql.getter.stub => Repositories/Mysql/mysql.getter.stub} (100%) rename stubs/{PHP8.0/repository.mysql.setter.stub => Repositories/Mysql/mysql.setter.stub} (100%) rename stubs/{PHP7.4/repository.mysql.timeField.stub => Repositories/Mysql/mysql.timeField.stub} (100%) rename stubs/{PHP8.0/repository.mysql.update.stub => Repositories/Mysql/mysql.update.stub} (100%) rename stubs/{PHP7.4/repository.resource.class.stub => Resources/resource.class.stub} (85%) rename stubs/{PHP7.4/repository.resource.getter.default.stub => Resources/resource.getter.default.stub} (100%) rename stubs/{PHP7.4/repository.resource.getter.foreign.stub => Resources/resource.getter.foreign.stub} (100%) diff --git a/Readme.md b/Readme.md index 56ff5bd..b06d58b 100644 --- a/Readme.md +++ b/Readme.md @@ -11,7 +11,7 @@ Before publishing assets, add `REPOSITORY_PHP_VERSION` variable to `.env` and se Then run following command in console to publish necessary assets in your project directory. ```bash -php artisan vendor:publish --provider=Nanvaie\DatabaseRepository\DatabaseRepositoryServiceProvider +php artisan vendor:publish vendor:publish --tag=database-repository-config ``` ### Setup Lumen Repository diff --git a/composer.json b/composer.json index 5684497..89c3b7c 100644 --- a/composer.json +++ b/composer.json @@ -10,12 +10,14 @@ } ], "require": { - "php": "^7.0|^8.0", + "php": "^8.0", "ext-pdo": "*", "ext-json": "*", "laravel/helpers": "^1.5", - "illuminate/console": "~5.8.0|^6.0|^7.0|^8.0|^9.0", - "illuminate/support": "^5.5|^6.0|^7.0|^8.0|^9.0" + "illuminate/console": "^9.0", + "illuminate/support": "^9.0", + "illuminate/cache": "^9.0", + "illuminate/database": "^9.0" }, "autoload": { "psr-4": { diff --git a/config/repository.php b/config/repository.php index 9f5f1be..cf1dd35 100644 --- a/config/repository.php +++ b/config/repository.php @@ -14,13 +14,14 @@ ], 'stub' => [ - 'entities' => 'stubs/PHP' . env('REPOSITORY_PHP_VERSION', '8.0') . '/repository.entity.', - 'factories' => 'stubs/PHP' . env('REPOSITORY_PHP_VERSION', '8.0') . '/repository.factory.', - 'resources' => 'stubs/PHP' . env('REPOSITORY_PHP_VERSION', '8.0') . '/repository.resource.', + 'entities' => 'stubs/Entities/entity.', + 'enums' => 'stubs/Enums/enum.', + 'factories' => 'stubs/Factories/factory.', + 'resources' => 'stubs/Resources/resource.', 'repositories' => [ - 'base' => 'stubs/PHP' . env('REPOSITORY_PHP_VERSION', '8.0') . '/repository.base.', - 'mysql' => 'stubs/PHP' . env('REPOSITORY_PHP_VERSION', '8.0') . '/repository.mysql.', - 'interface' => 'stubs/PHP' . env('REPOSITORY_PHP_VERSION', '8.0') . '/repository.interface.', + 'base' => 'stubs/Repositories/Base/base.', + 'mysql' => 'stubs/Repositories/Mysql/mysql.', + 'interface' => 'stubs/Repositories/Interface/interface.', ] ], diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index b6c2760..3ae5e56 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -45,6 +45,7 @@ public function handle() ]; $this->call('repository:make-entity', $arguments); + $this->call('repository:make-enum', ['table_name' => $_tableName, '--delete' => $delete, '--force' => $force, '--add-to-git' => $addToGit]); $this->call('repository:make-factory', ['table_name' => $_tableName, '--delete' => $delete, '--force' => $force, '--add-to-git' => $addToGit]); $this->call('repository:make-resource', $arguments); $this->call('repository:make-interface-repository', $arguments); diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 868523b..dd991b4 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -67,10 +67,9 @@ public function handle(): int $entityNamespace = config('repository.path.namespace.entities'); $relativeEntitiesPath = config('repository.path.relative.entities'); $entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.entities'); - $phpVersion = config('repository.php_version'); - $filenameWithPath = $relativeEntitiesPath.$entityName.'.php'; + $filenameWithPath = $relativeEntitiesPath . $entityName.'.php'; - if ($this->option('delete')) { + if (file_exists($filenameWithPath) && $this->option('delete')) { unlink($filenameWithPath); $this->info("Entity \"$entityName\" has been deleted."); return 0; diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php new file mode 100644 index 0000000..1081c02 --- /dev/null +++ b/src/Commands/MakeEnum.php @@ -0,0 +1,124 @@ +argument('table_name'); + $enumNamespace = config('repository.path.namespace.enums'); + $relativeEntitiesPath = config('repository.path.relative.enums'); + $entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.enums'); + + + $columns = $this->getAllColumnsInTable($tableName); + + if ($columns->isEmpty()) { + $this->alert("Couldn't retrieve columns from table \"$tableName\"! Perhaps table's name is misspelled."); + die; + } + + $enums = []; + foreach ($columns as $_column) { + if ($_column->DATA_TYPE == 'enum') { + $enumClassName = studly_case(substr_replace($_column->TABLE_NAME, '', -1) . '_' . $_column->COLUMN_NAME); + $enums[$enumClassName] = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE)); + + $filenameWithPath = $relativeEntitiesPath . $enumClassName.'.php'; + + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); + $this->info("Enum \"$enumClassName\" has been deleted."); + return 0; + } + } + } + + // Create Attributes + + $baseContentStub = file_get_contents($entityStubsPath.'class.stub'); + $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); + + foreach ($enums as $enumName => $enum) { + $filenameWithPath = $relativeEntitiesPath . $enumName.'.php'; + + + if ( ! file_exists($relativeEntitiesPath) && ! mkdir($relativeEntitiesPath, 0775, true) && ! is_dir($relativeEntitiesPath)) { + $this->alert("Directory \"$relativeEntitiesPath\" was not created"); + return 0; + } + + if (class_exists($relativeEntitiesPath.'\\'.$enumName) && ! $this->option('force')) { + $this->alert("Enum \"$enumName\" is already exist!"); + return 0; + } + + $attributes = ''; + foreach ($enum as $_enum) { + $attributes .= $this->writeAttribute( + $attributeStub, + strtoupper($_enum), + $_enum + ); + } + + + $baseContent = str_replace(['{{ EnumNamespace }}', '{{ EnumName }}', '{{ Attributes }}',], + [$enumNamespace, $enumName, $attributes,], + $baseContentStub); + + file_put_contents($filenameWithPath, $baseContent); + + if ($this->option('add-to-git')) { + shell_exec('git add '.$filenameWithPath); + } + + $this->info("Enum \"$enumName\" has been created."); + } + + + + return 0; + } +} diff --git a/src/Commands/MakeFactory.php b/src/Commands/MakeFactory.php index 5f5a3c0..b011c61 100644 --- a/src/Commands/MakeFactory.php +++ b/src/Commands/MakeFactory.php @@ -48,11 +48,10 @@ public function handle(): int $factoryNamespace = config('repository.path.namespace.factories'); $relativeFactoriesPath = config('repository.path.relative.factories'); $factoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.factories'); - $phpVersion = config('repository.php_version'); - $filenameWithPath = $relativeFactoriesPath.$factoryName.'.php'; + $filenameWithPath = $relativeFactoriesPath . $factoryName.'.php'; - if ($this->option('delete')) { - unlink("$relativeFactoriesPath/$factoryName.php"); + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); $this->info("Factory \"$factoryName\" has been deleted."); return 0; } @@ -101,4 +100,4 @@ public function handle(): int return 0; } -} \ No newline at end of file +} diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index 1f36379..068813c 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -55,12 +55,12 @@ public function handle(): int $interfaceName = "I$entityName"."Repository"; $entityNamespace = config('repository.path.namespace.entities'); $repositoryNamespace = config('repository.path.namespace.repositories'); - $relativeInterfacePath = config('repository.path.relative.repositories') . "$entityName"; + $relativeInterfacePath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; $interfaceRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.interface'); - $filenameWithPath = $relativeInterfacePath . '/' . $interfaceName.'.php'; + $filenameWithPath = $relativeInterfacePath . $interfaceName.'.php'; - if ($this->option('delete')) { - unlink("$relativeInterfacePath/$interfaceName.php"); + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); $this->info("Interface \"$interfaceName\" has been deleted."); return 0; } diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index 25b40d6..5ffc56a 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -72,13 +72,12 @@ public function handle(): int $entityNamespace = config('repository.path.namespace.entities'); $factoryNamespace = config('repository.path.namespace.factories'); $repositoryNamespace = config('repository.path.namespace.repositories'); - $relativeMysqlRepositoryPath = config('repository.path.relative.repositories')."$entityName"; + $relativeMysqlRepositoryPath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; $mysqlRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.mysql'); - $phpVersion = config('repository.php_version'); - $filenameWithPath = $relativeMysqlRepositoryPath . '/' . $mysqlRepositoryName.'.php'; + $filenameWithPath = $relativeMysqlRepositoryPath . $mysqlRepositoryName.'.php'; - if ($this->option('delete')) { - unlink("$relativeMysqlRepositoryPath/$mysqlRepositoryName.php"); + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); $this->info("MySql Repository \"$mysqlRepositoryName\" has been deleted."); return 0; } @@ -171,8 +170,8 @@ public function handle(): int $baseContent = str_replace('{{ Functions }}', $functions, $baseContent); - $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ FactoryName }}', '{{ FactoryNamespace }}', '{{ EntityVariableName }}', '{{ MySqlRepositoryName }}', '{{ RepositoryNamespace }}', '{{ RepositoryInterfaceName }}', '{{ TableName }}', '{{ HasSoftDelete }}'], - [$entityName, $entityNamespace, $factoryName, $factoryNamespace, $entityVariableName, $mysqlRepositoryName, $repositoryNamespace, $interfaceName, $tableName, $hasSoftDelete ? 'true' : 'false'], + $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ FactoryName }}', '{{ FactoryNamespace }}', '{{ EntityVariableName }}', '{{ MySqlRepositoryName }}', '{{ RepositoryNamespace }}', '{{ RepositoryInterfaceName }}', '{{ TableName }}', '{{ HasSoftDelete }}',], + [$entityName, $entityNamespace, $factoryName, $factoryNamespace, $entityVariableName, $mysqlRepositoryName, $repositoryNamespace, $interfaceName, $tableName, $hasSoftDelete ? 'true' : 'false',], $baseContent); file_put_contents($filenameWithPath, $baseContent); diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index e4a24c1..0732b92 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -37,15 +37,13 @@ public function handle(): int $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); - $factoryName = $entityName."Factory"; - $interfaceName = "I$entityName"."Repository"; $redisRepositoryName = "Redis$entityName"."Repository"; $redisRepositoryNamespace = config('repository.path.namespace.repositories'); - $relativeRedisRepositoryPath = config('repository.path.relative.repositories')."$entityName"; + $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; + $filenameWithPath = $relativeRedisRepositoryPath . $redisRepositoryName . '.php'; - if ($this->option('delete')) { - unlink("$relativeRedisRepositoryPath/$redisRepositoryName.php"); + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); $this->info("Redis Repository \"$redisRepositoryName\" has been deleted."); return 0; } @@ -73,7 +71,7 @@ public function handle(): int // Initialize Redis Repository $redisRepositoryContent = "option('delete')) { - unlink("$relativeRepositoryPath/$repositoryName.php"); + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); $this->info("Repository \"$repositoryName\" has been deleted."); return 0; } diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index 64bab0f..bc3fa5b 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -57,10 +57,10 @@ public function handle(): int $resourceNamespace = config('repository.path.namespace.resources'); $relativeResourcesPath = config('repository.path.relative.resources'); $resourceStubsPath = __DIR__ . '/../../' . config('repository.path.stub.resources'); - $filenameWithPath = $relativeResourcesPath.$resourceName.'.php'; + $filenameWithPath = $relativeResourcesPath . $resourceName.'.php'; - if ($this->option('delete')) { - unlink("$relativeResourcesPath/$resourceName.php"); + if (file_exists($filenameWithPath) && $this->option('delete')) { + unlink($filenameWithPath); $this->info("Resource \"$resourceName\" has been deleted."); return 0; } @@ -102,8 +102,8 @@ public function handle(): int } } - $baseContent = str_replace(['{{ GetterFunctions }}', '{{ ForeignGetterFunctions }}', '{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ ResourceName }}', '{{ ResourceNamespace }}'], - [substr($getterFunctions, 0, -1), substr($foreignGetterFunctions, 0, -1), $entityName, $entityNamespace, $entityVariableName, $resourceName, $resourceNamespace], + $baseContent = str_replace(['{{ GetterFunctions }}', '{{ ForeignGetterFunctions }}', '{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ ResourceName }}', '{{ ResourceNamespace }}',], + [substr($getterFunctions, 0, -1), substr($foreignGetterFunctions, 0, -1), $entityName, $entityNamespace, $entityVariableName, $resourceName, $resourceNamespace,], $baseContent); file_put_contents($filenameWithPath, $baseContent); diff --git a/src/DatabaseRepositoryServiceProvider.php b/src/DatabaseRepositoryServiceProvider.php index 7c9eeee..4382fe7 100644 --- a/src/DatabaseRepositoryServiceProvider.php +++ b/src/DatabaseRepositoryServiceProvider.php @@ -4,6 +4,7 @@ use Nanvaie\DatabaseRepository\Commands\MakeAll; use Nanvaie\DatabaseRepository\Commands\MakeEntity; +use Nanvaie\DatabaseRepository\Commands\MakeEnum; use Nanvaie\DatabaseRepository\Commands\MakeFactory; use Nanvaie\DatabaseRepository\Commands\MakeInterfaceRepository; use Nanvaie\DatabaseRepository\Commands\MakeMySqlRepository; @@ -19,13 +20,10 @@ */ class DatabaseRepositoryServiceProvider extends ServiceProvider { - private $baseModelStubPath; public function __construct($app) { parent::__construct($app); - - $this->baseModelStubPath = __DIR__ . '/../stubs/Models/PHP' .env('REPOSITORY_PHP_VERSION', '8.0'); } /** @@ -46,76 +44,11 @@ public function offerPublishing(): void if ($this->app->runningInConsole()) { $this->publishes([ __DIR__ . '/../config/repository.php' => $this->app->configPath('repository.php'), - ], 'repository-config'); + ], 'database-repository-config'); - $this->publishEnums(); - $this->publishEntities(); - $this->publishFactories(); - $this->publishResources(); - $this->publishRepositories(); } } - private function publishEnums(): void - { - $publishPath = $this->app->basePath(config('repository.path.relative.enums', 'app/Models/Enums/')); - - $this->publishes([ - $this->baseModelStubPath . '/Enums/Enum.stub' => $publishPath . 'Enum.php', - ], ['repository-base-classes', 'repository-base-enum']); - - $this->publishes([ - $this->baseModelStubPath . '/Enums/GriewFilterOperator.stub' => $publishPath . 'GriewFilterOperator.php', - ], ['repository-base-classes', 'repository-griew-enums']); - } - - private function publishEntities(): void - { - $publishPath = $this->app->basePath(config('repository.path.relative.entities', 'app/Models/Entities/')); - - $this->publishes([ - $this->baseModelStubPath . '/Entity/Entity.stub' => $publishPath . 'Entity.php', - ], ['repository-base-classes', 'repository-base-entity']); - } - - private function publishFactories(): void - { - $publishPath = $this->app->basePath(config('repository.path.relative.factories', 'app/Models/Factories/')); - - $this->publishes([ - $this->baseModelStubPath . '/Factory/Factory.stub' => $publishPath . 'Factory.php', - ], ['repository-base-classes', 'repository-base-factory']); - - $this->publishes([ - $this->baseModelStubPath . '/Factory/IFactory.stub' => $publishPath . 'IFactory.php', - ], ['repository-base-classes', 'repository-base-factory']); - } - - private function publishResources(): void - { - $publishPath = $this->app->basePath(config('repository.path.relative.resources', 'app/Models/Resources/')); - - $this->publishes([ - $this->baseModelStubPath . '/Resource/Resource.stub' => $publishPath . 'Resource.php', - ], ['repository-base-classes', 'repository-base-resource']); - - $this->publishes([ - $this->baseModelStubPath . '/Resource/IResource.stub' => $publishPath . 'IResource.php', - ], ['repository-base-classes', 'repository-base-resource']); - } - - private function publishRepositories(): void - { - $publishPath = $this->app->basePath(config('repository.path.relative.repositories', 'app/Models/Repositories/')); - - $this->publishes([ - $this->baseModelStubPath . '/Repository/MySqlRepository.stub' => $publishPath . 'MySqlRepository.php', - ], ['repository-base-classes', 'repository-base-mysql-repository']); - - $this->publishes([ - $this->baseModelStubPath . '/Repository/RedisRepository.stub' => $publishPath . 'RedisRepository.php', - ], ['repository-base-classes', 'repository-base-redis-repository']); - } /** * Register custom commands. @@ -131,6 +64,10 @@ private function registerCommands(): void return new MakeEntity(); }); + $this->app->singleton('repository.make-enum', function () { + return new MakeEnum(); + }); + $this->app->singleton('repository.make-factory', function () { return new MakeFactory(); }); @@ -158,6 +95,7 @@ private function registerCommands(): void $this->commands([ MakeAll::class, MakeEntity::class, + MakeEnum::class, MakeFactory::class, MakeInterfaceRepository::class, MakeMySqlRepository::class, diff --git a/stubs/Models/PHP8.0/Entity/Entity.stub b/src/Models/Entity/Entity.php similarity index 94% rename from stubs/Models/PHP8.0/Entity/Entity.stub rename to src/Models/Entity/Entity.php index 08af3bf..ba7265f 100644 --- a/stubs/Models/PHP8.0/Entity/Entity.stub +++ b/src/Models/Entity/Entity.php @@ -1,6 +1,6 @@ originals = $this->toArray(); } + /** + * empty an array of attributes original value + */ + public function emptyOriginals() + { + $this->originals = []; + } + /** * get an Array of Changed Attributes * @return array @@ -150,4 +158,4 @@ public function jsonSerialize() { return $this->toArray(); } -} \ No newline at end of file +} diff --git a/stubs/Models/PHP8.0/Enums/Enum.stub b/src/Models/Enums/Enum.php similarity index 93% rename from stubs/Models/PHP8.0/Enums/Enum.stub rename to src/Models/Enums/Enum.php index 291fe58..1bf3753 100644 --- a/stubs/Models/PHP8.0/Enums/Enum.stub +++ b/src/Models/Enums/Enum.php @@ -1,6 +1,6 @@ cache; } -} \ No newline at end of file +} diff --git a/stubs/Models/PHP8.0/Resource/IResource.stub b/src/Models/Resources/IResource.php similarity index 63% rename from stubs/Models/PHP8.0/Resource/IResource.stub rename to src/Models/Resources/IResource.php index a44a374..6f48e6e 100644 --- a/stubs/Models/PHP8.0/Resource/IResource.stub +++ b/src/Models/Resources/IResource.php @@ -1,9 +1,9 @@ $function($value); - } - } - - public function __get($name) - { - if (property_exists($this, $name)) { - $function = camel_case('get_' . snake_case($name)); - return $this->$function(); - } - } - - public function __isset($name) - { - return property_exists($this, $name); - } - - /** - * Make all variables of the object as null - * @return $this - */ - public function clearVariables() - { - $attributes = get_object_vars($this); - foreach ($attributes as $attributeName => $attributeValue) { - $this->$attributeName = null; - } - return $this; - } - - /** - * @return int - */ - public function getPrimaryKey(): int - { - return $this->getId(); - } - - /** - * Fill the model - */ - public function fill() - { - - } - - /** - * get an Array of current Attributes value - * @return array - */ - public function toArray(): array - { - $attributes = get_object_vars($this); - - unset($attributes['originals']); - - return $attributes; - } - - /** - * store an array of attributes original value - */ - public function storeOriginals() - { - $this->originals = $this->toArray(); - } - - /** - * get an Array of Changed Attributes - * @return array - */ - public function changedAttributesName() - { - $changedAttributes = []; - $attributes = $this->toArray(); - foreach ($attributes as $key => $value) { - if (isset($this->originals[$key])) { - if ($value != $this->originals[$key] && !((is_array($this->originals[$key]) || is_object($this->originals[$key])))) { - $changedAttributes[] = $key; - } - } - } - return $changedAttributes; - } - - /** - * get an Array of Changed Attributes with new values - * @return array - */ - public function getDirty() - { - $dirty = []; - $attributes = $this->toArray(); - - foreach ($this->changedAttributesName() as $key) { - $dirty[$key] = $attributes[$key]; - } - - return $dirty; - } - - /** - * get an Array of Changed Attributes with original values - * @return array - */ - public function getChanges() - { - $changes = []; - - foreach ($this->changedAttributesName() as $key) { - $changes[$key] = $this->originals[$key]; - } - - return $changes; - } - - /** - * is any attribute changed? - * @return bool - */ - public function isDirty() - { - if (count($this->changedAttributesName()) > 0) return true; - - return false; - } - - public function jsonSerialize(): array - { - return $this->toArray(); - } -} \ No newline at end of file diff --git a/stubs/Models/PHP7.0/Factory/Factory.stub b/stubs/Models/PHP7.0/Factory/Factory.stub deleted file mode 100644 index 8f9e681..0000000 --- a/stubs/Models/PHP7.0/Factory/Factory.stub +++ /dev/null @@ -1,26 +0,0 @@ -push($this->makeEntityFromStdClass($_entity)); - } - - return $entityCollection; - } -} \ No newline at end of file diff --git a/stubs/Models/PHP7.0/Factory/IFactory.stub b/stubs/Models/PHP7.0/Factory/IFactory.stub deleted file mode 100644 index 923cd1b..0000000 --- a/stubs/Models/PHP7.0/Factory/IFactory.stub +++ /dev/null @@ -1,22 +0,0 @@ -$function($value); - } - } - - public function __get($name) - { - if (property_exists($this, $name)) { - $function = camel_case('get_' . snake_case($name)); - return $this->$function(); - } - } - - public function __isset($name) - { - return property_exists($this, $name); - } - - /** - * Make all variables of the object as null - * @return $this - */ - public function clearVariables() - { - $attributes = get_object_vars($this); - foreach ($attributes as $attributeName => $attributeValue) { - $this->$attributeName = null; - } - return $this; - } - - /** - * @return int - */ - public function getPrimaryKey() - { - return $this->getId(); - } - - /** - * Fill the model - */ - public function fill() - { - - } - - /** - * get an Array of current Attributes value - */ - public function toArray(): array - { - $attributes = get_object_vars($this); - - unset($attributes['originals']); - - return $attributes; - } - - /** - * store an array of attributes original value - */ - public function storeOriginals() - { - $this->originals = $this->toArray(); - } - - /** - * get an Array of Changed Attributes - * @return array - */ - public function changedAttributesName() - { - $changedAttributes = []; - $attributes = $this->toArray(); - foreach ($attributes as $key => $value) { - if (isset($this->originals[$key])) { - if ($value != $this->originals[$key] && !((is_array($this->originals[$key]) || is_object($this->originals[$key])))) { - $changedAttributes[] = $key; - } - } - } - return $changedAttributes; - } - - /** - * get an Array of Changed Attributes with new values - * @return array - */ - public function getDirty() - { - $dirty = []; - $attributes = $this->toArray(); - - foreach ($this->changedAttributesName() as $key) { - $dirty[$key] = $attributes[$key]; - } - - return $dirty; - } - - /** - * get an Array of Changed Attributes with original values - * @return array - */ - public function getChanges() - { - $changes = []; - - foreach ($this->changedAttributesName() as $key) { - $changes[$key] = $this->originals[$key]; - } - - return $changes; - } - - /** - * is any attribute changed? - * @return bool - */ - public function isDirty() - { - if (count($this->changedAttributesName()) > 0) return true; - - return false; - } - - public function jsonSerialize() - { - return $this->toArray(); - } -} \ No newline at end of file diff --git a/stubs/Models/PHP7.4/Enums/Enum.stub b/stubs/Models/PHP7.4/Enums/Enum.stub deleted file mode 100644 index 8a27bf7..0000000 --- a/stubs/Models/PHP7.4/Enums/Enum.stub +++ /dev/null @@ -1,44 +0,0 @@ -getConstants(); - } - - /** - * @param int|string $key - * @return string|null - */ - public function getValue($key): ?string - { - $list = $this->getList(); - $keys = array_keys($list); - $key = is_numeric($key) ? (int)$key : $key; - - if (is_int($key) && $key < count($keys)) { - $value = $list[$keys[$key]]; - } else { - $value = $list[strtoupper($key)]; - } - - return $value; - } - - /** - * @param int|string $value - * @return false|int|string - */ - public function indexOf($value) - { - $list = $this->getList(); - $values = array_values($list); - - return array_search($value, $values, true); - } -} \ No newline at end of file diff --git a/stubs/Models/PHP7.4/Enums/GriewFilterOperator.stub b/stubs/Models/PHP7.4/Enums/GriewFilterOperator.stub deleted file mode 100644 index a9c5439..0000000 --- a/stubs/Models/PHP7.4/Enums/GriewFilterOperator.stub +++ /dev/null @@ -1,29 +0,0 @@ -push($this->makeEntityFromStdClass($_entity)); - } - - return $entityCollection; - } -} \ No newline at end of file diff --git a/stubs/Models/PHP7.4/Factory/IFactory.stub b/stubs/Models/PHP7.4/Factory/IFactory.stub deleted file mode 100644 index 923cd1b..0000000 --- a/stubs/Models/PHP7.4/Factory/IFactory.stub +++ /dev/null @@ -1,22 +0,0 @@ -alternativeDbConnection = null; - } - - /** - * Notice: this function cannot be used in async jobs because the connection is not serializable! - * @param ConnectionInterface $connection - */ - public function changeDatabaseConnection($connection) - { - $this->alternativeDbConnection = $connection; - } - - public function newQuery(): Builder - { - if (is_null($this->alternativeDbConnection)) { - $query = app('db')->table($this->table); - } else { - $query = $this->alternativeDbConnection->table($this->table); - } - -// if ($this->softDelete) { -// if (!$this->withTrashed) { -// $query = $query->whereNull('deleted_at'); -// } else { -// $this->withTrashed = false; -// } -// } - - return $query; - } - -// public function withTrashed(): MySqlRepository -// { -// $this->withTrashed = true; -// -// return $this; -// } - - /** - * @param int|null $total - * @param int $offset - * @param int $count - * @param array $orders - * @param array $filters - * @return Collection - */ - public function getAllForGridView(?int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Collection - { - $query = $this->newQuery(); - - $result = $this->processGridViewQuery($query, $total, $offset, $count, $orders, $filters)->get(); - - return $this->factory->makeCollectionOfEntities($result); - } - - public function raw($str) - { - if (is_null($this->alternativeDbConnection)) { - return app('db')->raw($str); - } - return $this->alternativeDbConnection->raw($str); - } - - public function exists($columnValue, $columnName = null) - { - if (is_null($columnName)) { - $columnName = $this->primaryKey; - } - return $this->newQuery()->where($columnName, $columnValue)->exists(); - } - - /** - * this is for validation purpose look at AppServiceProvider - * @param $attribute - * @param $value - * @param null $ignoredPrimaryKey - * @return bool - */ - public function valueExists($attribute, $value, $ignoredPrimaryKey = null) - { - $query = $this->newQuery(); - - if ($this->softDelete) { - $query->whereNull('deleted_at'); - } - - $query->where($attribute, $value); - - if (!is_null($ignoredPrimaryKey)) { - $query->where($this->primaryKey, '<>', $ignoredPrimaryKey); - } - - return $query->exists(); - } - - /** - * @param Entity $model - */ - public function updateOrCreate($model) - { - if ($this->exists($model->getPrimaryKey())) { - $this->update($model); - } else { - $this->create($model); - } - } - - /** - * @param Entity $model - */ - public function createIfNotExists($model) - { - if (!$this->exists($model->getPrimaryKey())) { - $this->create($model); - } - } - - /** - * It returns maximum row Id - * @return int|mixed - */ - public function getMaxId() - { - $entity = $this->newQuery()->orderByDesc($this->primaryKey)->first(); - if ($entity) { - return $entity->id; - } else { - return 0; - } - } - - /** - * @param Builder $query - * @param int $offset - * @param int $count - * @param int|null $total - * @param array $orders - * @param array $filters - * @return Builder - */ - protected function processGridViewQuery(Builder $query, ?int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Builder - { - if ($orders) { - $query = $this->processOrder($query, $orders); - } - - if ($filters) { - $query = $this->processFilter($query, $filters); - } - - $total = $query->count(); - - if ($count) { - $query->offset($offset); - $query->limit($count); - } - - return $query; - } - - /** - * @param Builder $query - * @param array $orders - * @return Builder - */ - protected function processOrder(Builder $query, array $orders): Builder - { - foreach ($orders as $order) { - $query->orderBy($order->name, $order->type); - } - return $query; - } - - /** - * @param Builder $query - * @param array $filters - * @return Builder - */ - protected function processFilter(Builder $query, array $filters): Builder - { - foreach ($filters as $filter) { - switch (strtolower(snake_case($filter->operator))) { - case GriewFilterOperator::IS_NULL: - $query->whereNull($filter->name); - break; - case GriewFilterOperator::IS_NOT_NULL: - $query->whereNotNull($filter->name); - break; - case GriewFilterOperator::IS_EQUAL_TO: - if (is_string($filter->operand1) && Str::contains($filter->operand1, '|')) { - // create in functionality with equal string - $arr = array_filter(explode('|', $filter->operand1)); - $query->whereIn($filter->name, $arr); - } else { - $query->where($filter->name, '=', $filter->operand1); - } - break; - case GriewFilterOperator::IS_NOT_EQUAL_TO: - if (is_string($filter->operand1) && Str::contains($filter->operand1, '|')) { - // create in functionality with equal string - $arr = array_filter(explode('|', $filter->operand1)); - $query->whereNotIn($filter->name, $arr); - } else { - $query->where($filter->name, '<>', $filter->operand1); - } - break; - case GriewFilterOperator::START_WITH: - $query->where($filter->name, 'LIKE', $filter->operand1 . '%'); - break; - case GriewFilterOperator::DOES_NOT_CONTAINS: - $query->where($filter->name, 'NOT LIKE', '%' . $filter->operand1 . '%'); - break; - case GriewFilterOperator::CONTAINS: - $query->where($filter->name, 'LIKE', '%' . $filter->operand1 . '%'); - break; - case GriewFilterOperator::ENDS_WITH: - $query->where($filter->name, 'LIKE', '%' . $filter->operand1); - break; - case GriewFilterOperator::IN: - $query->whereIn($filter->name, $filter->operand1); - break; - case GriewFilterOperator::NOT_IN: - $query->whereNotIn($filter->name, $filter->operand1); - break; - case GriewFilterOperator::BETWEEN: - $query->whereBetween($filter->name, array($filter->operand1, $filter->operand2)); - break; - case GriewFilterOperator::IS_AFTER_THAN_OR_EQUAL_TO: - case GriewFilterOperator::IS_GREATER_THAN_OR_EQUAL_TO: - $query->where($filter->name, '>=', $filter->operand1); - break; - case GriewFilterOperator::IS_AFTER_THAN: - case GriewFilterOperator::IS_GREATER_THAN: - $query->where($filter->name, '>', $filter->operand1); - break; - case GriewFilterOperator::IS_LESS_THAN_OR_EQUAL_TO: - case GriewFilterOperator::IS_BEFORE_THAN_OR_EQUAL_TO: - $query->where($filter->name, '<=', $filter->operand1); - break; - case GriewFilterOperator::IS_LESS_THAN: - case GriewFilterOperator::IS_BEFORE_THAN: - $query->where($filter->name, '<', $filter->operand1); - break; - } - } - - return $query; - } -} diff --git a/stubs/Models/PHP8.0/Resource/Resource.stub b/stubs/Models/PHP8.0/Resource/Resource.stub deleted file mode 100644 index 87bf3b0..0000000 --- a/stubs/Models/PHP8.0/Resource/Resource.stub +++ /dev/null @@ -1,30 +0,0 @@ -toArray($_entity); - } - - return $entityArray; - } -} diff --git a/stubs/PHP7.0/repository.entity.accessors.stub b/stubs/PHP7.0/repository.entity.accessors.stub deleted file mode 100644 index 936ae81..0000000 --- a/stubs/PHP7.0/repository.entity.accessors.stub +++ /dev/null @@ -1,16 +0,0 @@ - - /** - * @return {{ AttributeType }} - */ - public function get{{ GetterName }}() - { - return $this->{{ AttributeName }}; - } - - /** - * @param {{ AttributeType }} ${{ AttributeName }} - */ - public function set{{ SetterName }}(${{ AttributeName }}) - { - $this->{{ AttributeName }} = ${{ AttributeName }}; - } diff --git a/stubs/PHP7.0/repository.entity.attribute.stub b/stubs/PHP7.0/repository.entity.attribute.stub deleted file mode 100644 index 19c5df3..0000000 --- a/stubs/PHP7.0/repository.entity.attribute.stub +++ /dev/null @@ -1 +0,0 @@ - protected ${{ AttributeName }}; diff --git a/stubs/PHP7.0/repository.entity.class.stub b/stubs/PHP7.0/repository.entity.class.stub deleted file mode 100644 index 375e887..0000000 --- a/stubs/PHP7.0/repository.entity.class.stub +++ /dev/null @@ -1,7 +0,0 @@ -newQuery() - ->whereIn('{{ AttributeName }}', ${{ AttributeNamePlural }}) - ->get(); - - return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); - } diff --git a/stubs/PHP7.0/repository.mysql.getOneBy.stub b/stubs/PHP7.0/repository.mysql.getOneBy.stub deleted file mode 100644 index 38e18bb..0000000 --- a/stubs/PHP7.0/repository.mysql.getOneBy.stub +++ /dev/null @@ -1,13 +0,0 @@ - - /** - * @param {{ AttributeType }} ${{ AttributeName }} - * @return {{ EntityName }}|null - */ - public function getOneBy{{ FunctionName }}(${{ AttributeName }}) - { - ${{ EntityVariableName }} = $this->newQuery() - ->where('{{ AttributeName }}', ${{ AttributeName }}) - ->first(); - - return ${{ EntityVariableName }} ? $this->factory->makeEntityFromStdClass(${{ EntityVariableName }}) : null; - } diff --git a/stubs/PHP7.4/repository.entity.class.stub b/stubs/PHP7.4/repository.entity.class.stub deleted file mode 100644 index f01693a..0000000 --- a/stubs/PHP7.4/repository.entity.class.stub +++ /dev/null @@ -1,8 +0,0 @@ -set{{ SetterName }}($entity->{{ AttributeName }}); diff --git a/stubs/PHP7.4/repository.interface.deleteAndUndelete.stub b/stubs/PHP7.4/repository.interface.deleteAndUndelete.stub deleted file mode 100644 index 6ab2f28..0000000 --- a/stubs/PHP7.4/repository.interface.deleteAndUndelete.stub +++ /dev/null @@ -1,4 +0,0 @@ - - public function delete({{ EntityName }} ${{ EntityVariableName }}): int; - - public function undelete({{ EntityName }} ${{ EntityVariableName }}): int; diff --git a/stubs/PHP7.4/repository.mysql.class.stub b/stubs/PHP7.4/repository.mysql.class.stub deleted file mode 100644 index 3a48556..0000000 --- a/stubs/PHP7.4/repository.mysql.class.stub +++ /dev/null @@ -1,21 +0,0 @@ -table = '{{ TableName }}'; - $this->primaryKey = 'id'; - $this->softDelete = {{ HasSoftDelete }}; - $this->factory = new {{ FactoryName }}(); - - parent::__construct(); - } -} \ No newline at end of file diff --git a/stubs/PHP7.4/repository.mysql.create.stub b/stubs/PHP7.4/repository.mysql.create.stub deleted file mode 100644 index c164a23..0000000 --- a/stubs/PHP7.4/repository.mysql.create.stub +++ /dev/null @@ -1,15 +0,0 @@ - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return {{ EntityName }} - */ - public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} - { - $id = $this->newQuery() - ->insertGetId([ - ]); - - ${{ EntityVariableName }}->setId($id); - - return ${{ EntityVariableName }}; - } diff --git a/stubs/PHP7.4/repository.mysql.deleteAndUndelete.stub b/stubs/PHP7.4/repository.mysql.deleteAndUndelete.stub deleted file mode 100644 index 4bafb41..0000000 --- a/stubs/PHP7.4/repository.mysql.deleteAndUndelete.stub +++ /dev/null @@ -1,26 +0,0 @@ - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ - public function delete({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => date('Y-m-d H:i:s'), - ]); - } - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ - public function undelete({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => null, - ]); - } diff --git a/stubs/PHP7.4/repository.mysql.getOneBy.stub b/stubs/PHP7.4/repository.mysql.getOneBy.stub deleted file mode 100644 index ca63bee..0000000 --- a/stubs/PHP7.4/repository.mysql.getOneBy.stub +++ /dev/null @@ -1,13 +0,0 @@ - - /** - * @param {{ AttributeType }} ${{ AttributeName }} - * @return {{ EntityName }}|null - */ - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): ?{{ EntityName }} - { - ${{ EntityVariableName }} = $this->newQuery() - ->where('{{ ColumnName }}', ${{ AttributeName }}) - ->first(); - - return ${{ EntityVariableName }} ? $this->factory->makeEntityFromStdClass(${{ EntityVariableName }}) : null; - } diff --git a/stubs/PHP7.4/repository.mysql.getter.stub b/stubs/PHP7.4/repository.mysql.getter.stub deleted file mode 100644 index 01985b3..0000000 --- a/stubs/PHP7.4/repository.mysql.getter.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), diff --git a/stubs/PHP7.4/repository.mysql.update.stub b/stubs/PHP7.4/repository.mysql.update.stub deleted file mode 100644 index 048c88d..0000000 --- a/stubs/PHP7.4/repository.mysql.update.stub +++ /dev/null @@ -1,12 +0,0 @@ - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ - public function update({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - ]); - } diff --git a/stubs/PHP8.0/repository.entity.accessors.stub b/stubs/PHP8.0/repository.entity.accessors.stub deleted file mode 100644 index 91814b6..0000000 --- a/stubs/PHP8.0/repository.entity.accessors.stub +++ /dev/null @@ -1,16 +0,0 @@ - - /** - * @return {{ AttributeType }} - */ - public function get{{ GetterName }}(): {{ AttributeType }} - { - return $this->{{ AttributeName }}; - } - - /** - * @param {{ AttributeType }} ${{ AttributeName }} - */ - public function set{{ SetterName }}({{ AttributeType }} ${{ AttributeName }}): void - { - $this->{{ AttributeName }} = ${{ AttributeName }}; - } diff --git a/stubs/PHP8.0/repository.entity.attribute.stub b/stubs/PHP8.0/repository.entity.attribute.stub deleted file mode 100644 index 6df2dec..0000000 --- a/stubs/PHP8.0/repository.entity.attribute.stub +++ /dev/null @@ -1 +0,0 @@ - protected {{ AttributeType }} ${{ AttributeName }}; diff --git a/stubs/PHP8.0/repository.factory.class.stub b/stubs/PHP8.0/repository.factory.class.stub deleted file mode 100644 index 71000fb..0000000 --- a/stubs/PHP8.0/repository.factory.class.stub +++ /dev/null @@ -1,21 +0,0 @@ -set{{ SetterName }}($entity->{{ AttributeName }}); diff --git a/stubs/PHP8.0/repository.interface.class.stub b/stubs/PHP8.0/repository.interface.class.stub deleted file mode 100644 index cb9a94d..0000000 --- a/stubs/PHP8.0/repository.interface.class.stub +++ /dev/null @@ -1,9 +0,0 @@ -newQuery() - ->whereIn('{{ ColumnName }}', ${{ AttributeNamePlural }}) - ->get(); - - return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); - } diff --git a/stubs/PHP8.0/repository.mysql.timeField.stub b/stubs/PHP8.0/repository.mysql.timeField.stub deleted file mode 100644 index 1f24763..0000000 --- a/stubs/PHP8.0/repository.mysql.timeField.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ ColumnName }}' => date('Y-m-d H:i:s'), diff --git a/stubs/PHP8.0/repository.resource.class.stub b/stubs/PHP8.0/repository.resource.class.stub deleted file mode 100644 index 02ebe56..0000000 --- a/stubs/PHP8.0/repository.resource.class.stub +++ /dev/null @@ -1,31 +0,0 @@ -toArray(${{ EntityVariableName }}) + [ -{{ ForeignGetterFunctions }} - ]; - } -} \ No newline at end of file diff --git a/stubs/PHP8.0/repository.resource.getter.default.stub b/stubs/PHP8.0/repository.resource.getter.default.stub deleted file mode 100644 index 7c12036..0000000 --- a/stubs/PHP8.0/repository.resource.getter.default.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), diff --git a/stubs/PHP8.0/repository.resource.getter.foreign.stub b/stubs/PHP8.0/repository.resource.getter.foreign.stub deleted file mode 100644 index 42c3769..0000000 --- a/stubs/PHP8.0/repository.resource.getter.foreign.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ AttributeName }}' => ${{ EntityVariableName }}->get{{ GetterName }}() ? (new {{ AttributeType }}Resource())->toArray(${{ EntityVariableName }}->get{{ GetterName }}()) : null, diff --git a/stubs/PHP8.0/repository.base.attribute.sql.stub b/stubs/Repositories/Base/base.attribute.sql.stub similarity index 100% rename from stubs/PHP8.0/repository.base.attribute.sql.stub rename to stubs/Repositories/Base/base.attribute.sql.stub diff --git a/stubs/PHP8.0/repository.base.class.stub b/stubs/Repositories/Base/base.class.stub similarity index 100% rename from stubs/PHP8.0/repository.base.class.stub rename to stubs/Repositories/Base/base.class.stub diff --git a/stubs/PHP8.0/repository.base.function.stub b/stubs/Repositories/Base/base.function.stub similarity index 100% rename from stubs/PHP8.0/repository.base.function.stub rename to stubs/Repositories/Base/base.function.stub diff --git a/stubs/PHP8.0/repository.base.setter.sql.stub b/stubs/Repositories/Base/base.setter.sql.stub similarity index 100% rename from stubs/PHP8.0/repository.base.setter.sql.stub rename to stubs/Repositories/Base/base.setter.sql.stub diff --git a/stubs/PHP7.4/repository.interface.class.stub b/stubs/Repositories/Interface/interface.class.stub similarity index 100% rename from stubs/PHP7.4/repository.interface.class.stub rename to stubs/Repositories/Interface/interface.class.stub diff --git a/stubs/PHP7.4/repository.interface.create.stub b/stubs/Repositories/Interface/interface.create.stub similarity index 100% rename from stubs/PHP7.4/repository.interface.create.stub rename to stubs/Repositories/Interface/interface.create.stub diff --git a/stubs/PHP8.0/repository.interface.deleteAndUndelete.stub b/stubs/Repositories/Interface/interface.deleteAndUndelete.stub similarity index 100% rename from stubs/PHP8.0/repository.interface.deleteAndUndelete.stub rename to stubs/Repositories/Interface/interface.deleteAndUndelete.stub diff --git a/stubs/PHP7.4/repository.interface.getAllBy.stub b/stubs/Repositories/Interface/interface.getAllBy.stub similarity index 100% rename from stubs/PHP7.4/repository.interface.getAllBy.stub rename to stubs/Repositories/Interface/interface.getAllBy.stub diff --git a/stubs/PHP7.4/repository.interface.getOneBy.stub b/stubs/Repositories/Interface/interface.getOneBy.stub similarity index 100% rename from stubs/PHP7.4/repository.interface.getOneBy.stub rename to stubs/Repositories/Interface/interface.getOneBy.stub diff --git a/stubs/PHP7.4/repository.interface.update.stub b/stubs/Repositories/Interface/interface.update.stub similarity index 100% rename from stubs/PHP7.4/repository.interface.update.stub rename to stubs/Repositories/Interface/interface.update.stub diff --git a/stubs/PHP8.0/repository.mysql.class.stub b/stubs/Repositories/Mysql/mysql.class.stub similarity index 88% rename from stubs/PHP8.0/repository.mysql.class.stub rename to stubs/Repositories/Mysql/mysql.class.stub index cd2cb91..9b92ecd 100644 --- a/stubs/PHP8.0/repository.mysql.class.stub +++ b/stubs/Repositories/Mysql/mysql.class.stub @@ -4,8 +4,8 @@ namespace {{ RepositoryNamespace }}\{{ EntityName }}; use {{ EntityNamespace }}\{{ EntityName }}; use {{ FactoryNamespace }}\{{ FactoryName }}; -use {{ RepositoryNamespace }}\MySqlRepository; use Illuminate\Support\Collection; +use Nanvaie\DatabaseRepository\Models\Repositories\MySqlRepository; class {{ MySqlRepositoryName }} extends MySqlRepository implements {{ RepositoryInterfaceName }} { @@ -19,4 +19,4 @@ class {{ MySqlRepositoryName }} extends MySqlRepository implements {{ Repository parent::__construct(); } {{ Functions }} -} \ No newline at end of file +} diff --git a/stubs/PHP8.0/repository.mysql.create.stub b/stubs/Repositories/Mysql/mysql.create.stub similarity index 100% rename from stubs/PHP8.0/repository.mysql.create.stub rename to stubs/Repositories/Mysql/mysql.create.stub diff --git a/stubs/PHP8.0/repository.mysql.deleteAndUndelete.stub b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub similarity index 100% rename from stubs/PHP8.0/repository.mysql.deleteAndUndelete.stub rename to stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub diff --git a/stubs/PHP7.4/repository.mysql.getAllBy.stub b/stubs/Repositories/Mysql/mysql.getAllBy.stub similarity index 100% rename from stubs/PHP7.4/repository.mysql.getAllBy.stub rename to stubs/Repositories/Mysql/mysql.getAllBy.stub diff --git a/stubs/PHP8.0/repository.mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub similarity index 100% rename from stubs/PHP8.0/repository.mysql.getOneBy.stub rename to stubs/Repositories/Mysql/mysql.getOneBy.stub diff --git a/stubs/PHP8.0/repository.mysql.getter.stub b/stubs/Repositories/Mysql/mysql.getter.stub similarity index 100% rename from stubs/PHP8.0/repository.mysql.getter.stub rename to stubs/Repositories/Mysql/mysql.getter.stub diff --git a/stubs/PHP8.0/repository.mysql.setter.stub b/stubs/Repositories/Mysql/mysql.setter.stub similarity index 100% rename from stubs/PHP8.0/repository.mysql.setter.stub rename to stubs/Repositories/Mysql/mysql.setter.stub diff --git a/stubs/PHP7.4/repository.mysql.timeField.stub b/stubs/Repositories/Mysql/mysql.timeField.stub similarity index 100% rename from stubs/PHP7.4/repository.mysql.timeField.stub rename to stubs/Repositories/Mysql/mysql.timeField.stub diff --git a/stubs/PHP8.0/repository.mysql.update.stub b/stubs/Repositories/Mysql/mysql.update.stub similarity index 100% rename from stubs/PHP8.0/repository.mysql.update.stub rename to stubs/Repositories/Mysql/mysql.update.stub diff --git a/stubs/PHP7.4/repository.resource.class.stub b/stubs/Resources/resource.class.stub similarity index 85% rename from stubs/PHP7.4/repository.resource.class.stub rename to stubs/Resources/resource.class.stub index 02ebe56..dcbf063 100644 --- a/stubs/PHP7.4/repository.resource.class.stub +++ b/stubs/Resources/resource.class.stub @@ -2,8 +2,10 @@ namespace {{ ResourceNamespace }}; -use {{ EntityNamespace }}\Entity; use {{ EntityNamespace }}\{{ EntityName }}; +use Nanvaie\DatabaseRepository\Models\Entity\Entity; +use Nanvaie\DatabaseRepository\Models\Resources\Resource; + class {{ ResourceName }} extends Resource { @@ -28,4 +30,4 @@ class {{ ResourceName }} extends Resource {{ ForeignGetterFunctions }} ]; } -} \ No newline at end of file +} diff --git a/stubs/PHP7.4/repository.resource.getter.default.stub b/stubs/Resources/resource.getter.default.stub similarity index 100% rename from stubs/PHP7.4/repository.resource.getter.default.stub rename to stubs/Resources/resource.getter.default.stub diff --git a/stubs/PHP7.4/repository.resource.getter.foreign.stub b/stubs/Resources/resource.getter.foreign.stub similarity index 100% rename from stubs/PHP7.4/repository.resource.getter.foreign.stub rename to stubs/Resources/resource.getter.foreign.stub From 3912339fd3c5392a6e4a1b3528b7412686b5c85f Mon Sep 17 00:00:00 2001 From: Javad Date: Fri, 9 Dec 2022 17:56:41 +0330 Subject: [PATCH 02/86] fix: make public const in enum's stub --- stubs/Enums/enum.attribute.stub | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stubs/Enums/enum.attribute.stub b/stubs/Enums/enum.attribute.stub index cf32ca8..9bb6678 100644 --- a/stubs/Enums/enum.attribute.stub +++ b/stubs/Enums/enum.attribute.stub @@ -1 +1 @@ - const {{ AttributeName }} = '{{ AttributeString }}'; + public const {{ AttributeName }} = '{{ AttributeString }}'; From 13138238f290605f13af44c122427511f0243b6a Mon Sep 17 00:00:00 2001 From: Javad Date: Fri, 9 Dec 2022 18:45:46 +0330 Subject: [PATCH 03/86] feature: add option to add all tables by '-a' or '--all-tables' --- src/Commands/MakeAll.php | 20 +++++++++++++++++--- src/CustomMySqlQueries.php | 13 +++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 3ae5e56..245ab45 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -3,19 +3,25 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Console\Command; +use Nanvaie\DatabaseRepository\CustomMySqlQueries; +use phpDocumentor\Reflection\PseudoTypes\NonEmptyLowercaseString; class MakeAll extends Command { + use CustomMySqlQueries; + /** * The name and signature of the console command. * * @var string */ - protected $signature = 'repository:make-all {table_names*} + protected $signature = 'repository:make-all + {--table_names= : Table names, separate names with comma} {--k|foreign-keys : Detect foreign keys} {--d|delete : Delete resource} {--f|force : Override/Delete existing classes} - {--g|add-to-git : Add created file to git repository}'; + {--g|add-to-git : Add created file to git repository} + {--a|all-tables : Add created file to git repository}'; /** * The console command description. @@ -29,12 +35,20 @@ class MakeAll extends Command */ public function handle() { - $tableNames = $this->argument('table_names'); $force = $this->option('force'); $delete = $this->option('delete'); $detectForeignKeys = $this->option('foreign-keys'); $addToGit = $this->option('add-to-git'); + if ($this->option('all-tables')) { + $tableNames = $this->getAllTableNames()->pluck('TABLE_NAME'); + } else if ($this->option('table_names')) { + $tableNames = explode(',', $this->option('table_names')); + } else { + $this->alert("Please choose one of two options '--all-tables' or '--table_names=' "); + die; + } + foreach ($tableNames as $_tableName) { $arguments = [ 'table_name' => $_tableName, diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index 5f8ebe5..eafe1cd 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -53,6 +53,19 @@ public function getAllColumnsInTable(string $tableName): Collection ->get(); } + /** + * Extract all table names. + * @return Collection + */ + public function getAllTableNames(): Collection + { + return DB::table('INFORMATION_SCHEMA.TABLES') + ->select('TABLE_NAME') + ->where('TABLE_SCHEMA', config('database.connections.mysql.database')) + ->where('TABLE_NAME', '<>', 'migrations') + ->get(); + } + /** * Extract all foreign keys from a given table. Foreign key's relations must define in MySql! * @param string $tableName From 2b78b7fed7291ad980031fe018bc1f25ec646d54 Mon Sep 17 00:00:00 2001 From: Javad Date: Fri, 9 Dec 2022 18:56:13 +0330 Subject: [PATCH 04/86] fix: singularity of some names --- src/Commands/MakeEnum.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 1081c02..84679a6 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -62,7 +62,7 @@ public function handle(): int $enums = []; foreach ($columns as $_column) { if ($_column->DATA_TYPE == 'enum') { - $enumClassName = studly_case(substr_replace($_column->TABLE_NAME, '', -1) . '_' . $_column->COLUMN_NAME); + $enumClassName = studly_case(str_singular(ucfirst(camel_case($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME); $enums[$enumClassName] = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE)); $filenameWithPath = $relativeEntitiesPath . $enumClassName.'.php'; From ad3504f5d8680bfc7e63d264f3ac0a0e822ac293 Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 29 Dec 2022 11:33:52 +0330 Subject: [PATCH 05/86] fix: update Readme.md for new options --- Readme.md | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/Readme.md b/Readme.md index b06d58b..bf41aeb 100644 --- a/Readme.md +++ b/Readme.md @@ -30,22 +30,25 @@ Note: Make sure to run `composer dump-autoload` after these changes. ## Usage List of artisan commands: -| Command | Inputs | Options | Description | -|----------------------------------------|-------------|----------------|-----------------------------------| -| `repository:make-entity` | table_name | -f, -d, -k, -g | Create new Entity | -| `repository:make-factory` | table_name | -f, -d, -g | Create new Factory | -| `repository:make-resource` | table_name | -f, -d, -k, -g | Create new Resource | -| `repository:make-interface-repository` | table_name | -f, -d, -k, -g | Create new Repository Interface | -| `repository:make-repository` | table_name | -f, -d, -k, -g | Create new Base Repository | -| `repository:make-mysql-repository` | table_name | -f, -d, -k, -g | Create new MySql Repository class | -| `repository:make-redis-repository` | table_name | -f, -d, -k, -g | Create new Redis Repository class | -| `repository:make-all` | table_names | -f, -d, -k, -g | Run all of the above commands | +| Command | Inputs | Options | Description | +|----------------------------------------|-------------------------------------|--------------------|-----------------------------------| +| `repository:make-entity` | table_name | -f, -d, -k, -g | Create new Entity | +| `repository:make-enum` | table_name | -f, -d, -g | Create new Enum | +| `repository:make-factory` | table_name | -f, -d, -g | Create new Factory | +| `repository:make-resource` | table_name | -f, -d, -k, -g | Create new Resource | +| `repository:make-interface-repository` | table_name | -f, -d, -k, -g | Create new Repository Interface | +| `repository:make-repository` | table_name | -f, -d, -k, -g | Create new Base Repository | +| `repository:make-mysql-repository` | table_name | -f, -d, -k, -g | Create new MySql Repository class | +| `repository:make-redis-repository` | table_name | -f, -d, -k, -g | Create new Redis Repository class | +| `repository:make-all` | --table_names=table_names(optional) | -a, -f, -d, -k, -g | Run all of the above commands | ### Options Explanation - `-f|--force`: Force commands to override existing files. - `-d|--delete`: Delete already created files. - `-k|--foreign-keys`: Try to detect foreign keys of table. - `-g|--add-to-git`: Add created files to git repository. +- `-a|--all-tables`: Use all existing tables. +- `--table_names=`: Add table names, separate names with comma. Example 1. Create new Entity for a table named 'users'. ```bash @@ -54,5 +57,10 @@ php artisan repository:make-entity users Example 2. Create all necessary classes for two tables named 'users' and 'customers' with enabled foreign key option. ```bash -php artisan repository:make-all users customers -k +php artisan repository:make-all --table_names=users,customers -k +``` + +Example 3. Create all necessary classes for all tables with enabled foreign key option(this may be used for new projects). +```bash +php artisan repository:make-all -a -k ``` From 3f5edfd43344172851a7be6b1a16e5d3f55455ae Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 29 Dec 2022 13:52:26 +0330 Subject: [PATCH 06/86] fix: add old illuminate dependencies --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 89c3b7c..48508a2 100644 --- a/composer.json +++ b/composer.json @@ -14,10 +14,10 @@ "ext-pdo": "*", "ext-json": "*", "laravel/helpers": "^1.5", - "illuminate/console": "^9.0", - "illuminate/support": "^9.0", - "illuminate/cache": "^9.0", - "illuminate/database": "^9.0" + "illuminate/console": "^6.0|^7.0|^8.0|^9.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0", + "illuminate/cache": "^6.0|^7.0|^8.0|^9.0", + "illuminate/database": "^6.0|^7.0|^8.0|^9.0" }, "autoload": { "psr-4": { From 435252a1148c8c6d75ef73a24ae1177ff2b90b80 Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 29 Dec 2022 15:40:03 +0330 Subject: [PATCH 07/86] fix: - add POINT datatype as string - remove laravel/helpers package --- composer.json | 1 - src/Commands/MakeEntity.php | 5 +++-- src/Commands/MakeEnum.php | 3 ++- src/Commands/MakeFactory.php | 9 +++++---- src/Commands/MakeInterfaceRepository.php | 9 +++++---- src/Commands/MakeMySqlRepository.php | 13 +++++++------ src/Commands/MakeRedisRepository.php | 3 ++- src/Commands/MakeRepository.php | 15 ++++++++------- src/Commands/MakeResource.php | 9 +++++---- src/CustomMySqlQueries.php | 6 ++++-- src/Models/Entity/Entity.php | 5 +++-- src/Models/Repositories/MySqlRepository.php | 2 +- 12 files changed, 45 insertions(+), 35 deletions(-) diff --git a/composer.json b/composer.json index 48508a2..2571f73 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,6 @@ "php": "^8.0", "ext-pdo": "*", "ext-json": "*", - "laravel/helpers": "^1.5", "illuminate/console": "^6.0|^7.0|^8.0|^9.0", "illuminate/support": "^6.0|^7.0|^8.0|^9.0", "illuminate/cache": "^6.0|^7.0|^8.0|^9.0", diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index dd991b4..67e4406 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; @@ -63,7 +64,7 @@ public function handle(): int { $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); $entityNamespace = config('repository.path.namespace.entities'); $relativeEntitiesPath = config('repository.path.relative.entities'); $entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.entities'); @@ -93,7 +94,7 @@ public function handle(): int } foreach ($columns as $_column) { - $_column->COLUMN_NAME = camel_case($_column->COLUMN_NAME); + $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } $baseContent = file_get_contents($entityStubsPath.'class.stub'); diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 84679a6..43f6fe0 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; @@ -62,7 +63,7 @@ public function handle(): int $enums = []; foreach ($columns as $_column) { if ($_column->DATA_TYPE == 'enum') { - $enumClassName = studly_case(str_singular(ucfirst(camel_case($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME); + $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME); $enums[$enumClassName] = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE)); $filenameWithPath = $relativeEntitiesPath . $enumClassName.'.php'; diff --git a/src/Commands/MakeFactory.php b/src/Commands/MakeFactory.php index b011c61..6c2be17 100644 --- a/src/Commands/MakeFactory.php +++ b/src/Commands/MakeFactory.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; @@ -29,7 +30,7 @@ class MakeFactory extends Command public function writeSetter(string $setterStub, string $columnName): string { return str_replace(['{{ SetterName }}', '{{ AttributeName }}'], - [ucfirst($columnName), snake_case($columnName)], + [ucfirst($columnName), Str::snake($columnName)], $setterStub); } @@ -41,8 +42,8 @@ public function writeSetter(string $setterStub, string $columnName): string public function handle(): int { $tableName = $this->argument('table_name'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); + $entityVariableName = Str::camel($entityName); $factoryName = $entityName.'Factory'; $entityNamespace = config('repository.path.namespace.entities'); $factoryNamespace = config('repository.path.namespace.factories'); @@ -74,7 +75,7 @@ public function handle(): int } foreach ($columns as $_column) { - $_column->COLUMN_NAME = camel_case($_column->COLUMN_NAME); + $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } $baseContent = file_get_contents($factoryStubsPath.'class.stub'); diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index 068813c..38b0374 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; @@ -30,14 +31,14 @@ class MakeInterfaceRepository extends Command private function writeGetOneFunction(string $getOneStub, string $columnName, string $attributeType): string { return str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}'], - [ucfirst(camel_case($columnName)), $columnName, $attributeType, camel_case($columnName)], + [ucfirst(Str::camel($columnName)), $columnName, $attributeType, Str::camel($columnName)], $getOneStub); } private function writeGetAllFunction(string $getOneStub, string $columnName, string $attributeType): string { return str_replace(['{{ FunctionNamePlural }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}'], - [ucfirst(str_plural(camel_case($columnName))), $attributeType, str_plural(camel_case($columnName))], + [ucfirst(Str::plural(Str::camel($columnName))), $attributeType, Str::plural(Str::camel($columnName))], $getOneStub); } @@ -50,8 +51,8 @@ public function handle(): int { $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); + $entityVariableName = Str::camel($entityName); $interfaceName = "I$entityName"."Repository"; $entityNamespace = config('repository.path.namespace.entities'); $repositoryNamespace = config('repository.path.namespace.repositories'); diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index 5ffc56a..b54c61c 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; @@ -30,28 +31,28 @@ class MakeMySqlRepository extends Command private function writeGetOneFunction(string $getOneStub, string $columnName, string $attributeType): string { return str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}'], - [ucfirst(camel_case($columnName)), $columnName, $attributeType, camel_case($columnName)], + [ucfirst(Str::camel($columnName)), $columnName, $attributeType, Str::camel($columnName)], $getOneStub); } private function writeGetAllFunction(string $getOneStub, string $columnName, string $attributeType): string { return str_replace(['{{ FunctionNamePlural }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}'], - [ucfirst(str_plural(camel_case($columnName))), $columnName, $attributeType, str_plural(camel_case($columnName))], + [ucfirst(Str::plural(Str::camel($columnName))), $columnName, $attributeType, Str::plural(Str::camel($columnName))], $getOneStub); } private function writeGetterFunction(string $getterStub, string $columnName): string { return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], - [$columnName, ucfirst(camel_case($columnName))], + [$columnName, ucfirst(Str::camel($columnName))], $getterStub); } private function writeSetterFunction(string $setterStub, string $columnName): string { return str_replace('{{ SetterName }}', - ucfirst(camel_case($columnName)), + ucfirst(Str::camel($columnName)), $setterStub); } @@ -64,8 +65,8 @@ public function handle(): int { $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); + $entityVariableName = Str::camel($entityName); $factoryName = $entityName.'Factory'; $interfaceName = 'I'.$entityName.'Repository'; $mysqlRepositoryName = 'MySql'.$entityName.'Repository'; diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index 0732b92..a65d325 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; @@ -36,7 +37,7 @@ public function handle(): int { $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); $redisRepositoryName = "Redis$entityName"."Repository"; $redisRepositoryNamespace = config('repository.path.namespace.repositories'); $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 4d1aa7a..6b3e8c1 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -3,6 +3,7 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Console\Command; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; class MakeRepository extends Command @@ -31,12 +32,12 @@ private function writeFunction(string $functionStub, string $functionName, strin { if ($functionName === 'getOneBy') { $functionReturnType = '?{{ EntityName }}'; - $functionName .= ucfirst(camel_case($columnName)); - $columnName = camel_case($columnName); + $functionName .= ucfirst(Str::camel($columnName)); + $columnName = Str::camel($columnName); } elseif ($functionName === 'getAllBy') { $functionReturnType = 'Collection'; - $functionName .= ucfirst(str_plural(camel_case($columnName))); - $columnName = str_plural(camel_case($columnName)); + $functionName .= ucfirst(Str::plural(Str::camel($columnName))); + $columnName = Str::plural(Str::camel($columnName)); } elseif ($functionName === 'create') { $functionReturnType = $attributeType; } elseif (in_array($functionName, ['update', 'remove', 'restore'])) { @@ -44,7 +45,7 @@ private function writeFunction(string $functionStub, string $functionName, strin } return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}'], - [$functionName, $attributeType, camel_case($columnName), $functionReturnType], + [$functionName, $attributeType, Str::camel($columnName), $functionReturnType], $functionStub); } @@ -64,8 +65,8 @@ public function handle(): int { $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); + $entityVariableName = Str::camel($entityName); $factoryName = $entityName.'Factory'; $interfaceName = 'I'.$entityName.'Repository'; $repositoryName = $entityName.'Repository'; diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index bc3fa5b..0eca8b6 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -3,6 +3,7 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Console\Command; +use Illuminate\Support\Str; use Nanvaie\DatabaseRepository\CustomMySqlQueries; class MakeResource extends Command @@ -37,7 +38,7 @@ public function writeGetter(string $getterStub, string $columnName, string $attr public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName) { return str_replace(['{{ AttributeName }}', '{{ GetterName }}', '{{ AttributeType }}'], - [snake_case($columnName), ucfirst($columnName), ucfirst($attributeName)], + [Str::snake($columnName), ucfirst($columnName), ucfirst($attributeName)], $foreignGetterStub); } @@ -50,8 +51,8 @@ public function handle(): int { $tableName = $this->argument('table_name'); $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); + $entityName = Str::singular(ucfirst(Str::camel($tableName))); + $entityVariableName = Str::camel($entityName); $entityNamespace = config('repository.path.namespace.entities'); $resourceName = $entityName."Resource"; $resourceNamespace = config('repository.path.namespace.resources'); @@ -92,7 +93,7 @@ public function handle(): int $getterFunctions = ''; foreach ($columns as $_column) { - $getterFunctions .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, camel_case($_column->COLUMN_NAME)); + $getterFunctions .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)); } $foreignGetterFunctions = ''; diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index eafe1cd..6f9597b 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -4,6 +4,7 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Str; trait CustomMySqlQueries { @@ -37,6 +38,7 @@ trait CustomMySqlQueries 'time' => 'string', 'datetime' => 'string', 'timestamp' => 'string', + 'point' => 'string', ]; /** @@ -81,8 +83,8 @@ public function extractForeignKeys(string $tableName): Collection ->get(); $foreignKeys->each(function ($foreignKey) { - $foreignKey->VARIABLE_NAME = camel_case(str_replace('_id', '', $foreignKey->COLUMN_NAME)); - $foreignKey->ENTITY_DATA_TYPE = ucfirst(camel_case(str_singular($foreignKey->REFERENCED_TABLE_NAME))); + $foreignKey->VARIABLE_NAME = Str::camel(str_replace('_id', '', $foreignKey->COLUMN_NAME)); + $foreignKey->ENTITY_DATA_TYPE = ucfirst(Str::camel(Str::singular($foreignKey->REFERENCED_TABLE_NAME))); }); return $foreignKeys; diff --git a/src/Models/Entity/Entity.php b/src/Models/Entity/Entity.php index ba7265f..23ccf37 100644 --- a/src/Models/Entity/Entity.php +++ b/src/Models/Entity/Entity.php @@ -3,6 +3,7 @@ namespace Nanvaie\DatabaseRepository\Models\Entity; use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Support\Str; use JsonSerializable; abstract class Entity implements JsonSerializable, Arrayable @@ -23,7 +24,7 @@ public function __construct() public function __set($name, $value) { if (property_exists($this, $name)) { - $function = camel_case('set_' . snake_case($name)); + $function = Str::camel('set_' . Str::snake($name)); $this->$function($value); } } @@ -31,7 +32,7 @@ public function __set($name, $value) public function __get($name) { if (property_exists($this, $name)) { - $function = camel_case('get_' . snake_case($name)); + $function = Str::camel('get_' . Str::snake($name)); return $this->$function(); } } diff --git a/src/Models/Repositories/MySqlRepository.php b/src/Models/Repositories/MySqlRepository.php index a7601b6..a9f2ed1 100644 --- a/src/Models/Repositories/MySqlRepository.php +++ b/src/Models/Repositories/MySqlRepository.php @@ -207,7 +207,7 @@ protected function processOrder(Builder $query, array $orders): Builder protected function processFilter(Builder $query, array $filters): Builder { foreach ($filters as $filter) { - switch (strtolower(snake_case($filter->operator))) { + switch (strtolower(Str::snake($filter->operator))) { case GriewFilterOperator::IS_NULL: $query->whereNull($filter->name); break; From 0d7c8c04564dd266293ab4e5d5af363771df3e52 Mon Sep 17 00:00:00 2001 From: sama20 Date: Tue, 3 Jan 2023 12:46:27 +0330 Subject: [PATCH 08/86] change syntax sugar ?type to null|type --- src/Commands/MakeEntity.php | 4 ++-- src/Commands/MakeRepository.php | 2 +- src/Models/Enums/Enum.php | 2 +- src/Models/Repositories/MySqlRepository.php | 6 +++--- stubs/Repositories/Interface/interface.getOneBy.stub | 2 +- stubs/Repositories/Mysql/mysql.getOneBy.stub | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 67e4406..b28d2d1 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -107,7 +107,7 @@ public function handle(): int $attributes .= $this->writeAttribute( $attributeStub, $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? '?' : '') . $this->dataTypes[$_column->DATA_TYPE] + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] ); } @@ -117,7 +117,7 @@ public function handle(): int $settersAndGetters .= $this->writeAccessors( $accessorsStub, $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? '?' : '') . $this->dataTypes[$_column->DATA_TYPE] + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] ); } diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 6b3e8c1..23433ab 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -31,7 +31,7 @@ class MakeRepository extends Command private function writeFunction(string $functionStub, string $functionName, string $columnName, string $attributeType): string { if ($functionName === 'getOneBy') { - $functionReturnType = '?{{ EntityName }}'; + $functionReturnType = 'null|{{ EntityName }}'; $functionName .= ucfirst(Str::camel($columnName)); $columnName = Str::camel($columnName); } elseif ($functionName === 'getAllBy') { diff --git a/src/Models/Enums/Enum.php b/src/Models/Enums/Enum.php index 1bf3753..523caf8 100644 --- a/src/Models/Enums/Enum.php +++ b/src/Models/Enums/Enum.php @@ -11,7 +11,7 @@ public function getList(): array return (new ReflectionClass($this))->getConstants(); } - public function getValue(int|string $key): ?string + public function getValue(int|string $key): null|string { $list = $this->getList(); $keys = array_keys($list); diff --git a/src/Models/Repositories/MySqlRepository.php b/src/Models/Repositories/MySqlRepository.php index a9f2ed1..25f1b7b 100644 --- a/src/Models/Repositories/MySqlRepository.php +++ b/src/Models/Repositories/MySqlRepository.php @@ -12,7 +12,7 @@ abstract class MySqlRepository { - private ?ConnectionInterface $alternativeDbConnection; + private null|ConnectionInterface $alternativeDbConnection; protected string $primaryKey = 'id'; @@ -72,7 +72,7 @@ public function newQuery(): Builder * @param array $filters * @return Collection */ - public function getAllForGridView(?int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Collection + public function getAllForGridView(null|int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Collection { $query = $this->newQuery(); @@ -166,7 +166,7 @@ public function getMaxId() * @param array $filters * @return Builder */ - protected function processGridViewQuery(Builder $query, ?int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Builder + protected function processGridViewQuery(Builder $query, null|int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Builder { if ($orders) { $query = $this->processOrder($query, $orders); diff --git a/stubs/Repositories/Interface/interface.getOneBy.stub b/stubs/Repositories/Interface/interface.getOneBy.stub index b0ffcfa..7e755c7 100644 --- a/stubs/Repositories/Interface/interface.getOneBy.stub +++ b/stubs/Repositories/Interface/interface.getOneBy.stub @@ -1,2 +1,2 @@ - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): ?{{ EntityName }}; + public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }}; diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub index 1091972..6a54716 100644 --- a/stubs/Repositories/Mysql/mysql.getOneBy.stub +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -3,7 +3,7 @@ * @param int ${{ AttributeName }} * @return {{ EntityName }}|null */ - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): ?{{ EntityName }} + public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} { ${{ EntityVariableName }} = $this->newQuery() ->where('{{ ColumnName }}', ${{ AttributeName }}) From d0e497ec21661add3039168d382b783c0e459558 Mon Sep 17 00:00:00 2001 From: sama20 Date: Tue, 3 Jan 2023 13:26:39 +0330 Subject: [PATCH 09/86] fix: set default value for fields based on mysql default --- src/Commands/MakeEntity.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index b28d2d1..7520d56 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -104,9 +104,10 @@ public function handle(): int // Create Attributes $attributes = ''; foreach ($columns as $_column) { + $defaultValue = ($_column->COLUMN_DEFAULT ?? 'null') ? ($_column->COLUMN_DEFAULT ?? 'null') : "''"; $attributes .= $this->writeAttribute( $attributeStub, - $_column->COLUMN_NAME, + $_column->COLUMN_NAME.($_column->IS_NULLABLE === 'YES' ? ' = '.$defaultValue : ''), ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] ); } From e7c8117314b3bc2ac053b9a27f2b911fe533922d Mon Sep 17 00:00:00 2001 From: sama20 Date: Tue, 3 Jan 2023 13:34:10 +0330 Subject: [PATCH 10/86] Remove unnecessary doc blocks --- stubs/Entities/entity.accessors.stub | 6 ------ stubs/Factories/factory.class.stub | 6 +----- stubs/Repositories/Mysql/mysql.create.stub | 4 ---- stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub | 10 +--------- stubs/Repositories/Mysql/mysql.getAllBy.stub | 4 ---- stubs/Repositories/Mysql/mysql.getOneBy.stub | 4 ---- stubs/Repositories/Mysql/mysql.update.stub | 4 ---- stubs/Resources/resource.class.stub | 8 -------- 8 files changed, 2 insertions(+), 44 deletions(-) diff --git a/stubs/Entities/entity.accessors.stub b/stubs/Entities/entity.accessors.stub index 91814b6..2e18d12 100644 --- a/stubs/Entities/entity.accessors.stub +++ b/stubs/Entities/entity.accessors.stub @@ -1,15 +1,9 @@ - /** - * @return {{ AttributeType }} - */ public function get{{ GetterName }}(): {{ AttributeType }} { return $this->{{ AttributeName }}; } - /** - * @param {{ AttributeType }} ${{ AttributeName }} - */ public function set{{ SetterName }}({{ AttributeType }} ${{ AttributeName }}): void { $this->{{ AttributeName }} = ${{ AttributeName }}; diff --git a/stubs/Factories/factory.class.stub b/stubs/Factories/factory.class.stub index 2ad09d4..99c189d 100644 --- a/stubs/Factories/factory.class.stub +++ b/stubs/Factories/factory.class.stub @@ -7,11 +7,7 @@ use Nanvaie\DatabaseRepository\Models\Factories\Factory; use stdClass; class {{ FactoryName }} extends Factory -{ - /** - * @param stdClass $entity - * @return {{ EntityName }} - */ +{ public function makeEntityFromStdClass(stdClass $entity): {{ EntityName }} { ${{ EntityVariableName }} = new {{ EntityName }}(); diff --git a/stubs/Repositories/Mysql/mysql.create.stub b/stubs/Repositories/Mysql/mysql.create.stub index e9ffbc4..79693d2 100644 --- a/stubs/Repositories/Mysql/mysql.create.stub +++ b/stubs/Repositories/Mysql/mysql.create.stub @@ -1,8 +1,4 @@ - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return {{ EntityName }} - */ public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} { {{ SetterFunctions }} diff --git a/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub index bdfdff8..a0da20b 100644 --- a/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub +++ b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub @@ -1,8 +1,4 @@ - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ public function remove({{ EntityName }} ${{ EntityVariableName }}): int { return $this->newQuery() @@ -11,11 +7,7 @@ 'deleted_at' => date('Y-m-d H:i:s'), ]); } - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ + public function restore({{ EntityName }} ${{ EntityVariableName }}): int { return $this->newQuery() diff --git a/stubs/Repositories/Mysql/mysql.getAllBy.stub b/stubs/Repositories/Mysql/mysql.getAllBy.stub index c63e3da..6c31d38 100644 --- a/stubs/Repositories/Mysql/mysql.getAllBy.stub +++ b/stubs/Repositories/Mysql/mysql.getAllBy.stub @@ -1,8 +1,4 @@ - /** - * @param array ${{ AttributeNamePlural }} - * @return Collection - */ public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection { ${{ EntityVariableName }} = $this->newQuery() diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub index 6a54716..68b5556 100644 --- a/stubs/Repositories/Mysql/mysql.getOneBy.stub +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -1,8 +1,4 @@ - /** - * @param int ${{ AttributeName }} - * @return {{ EntityName }}|null - */ public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} { ${{ EntityVariableName }} = $this->newQuery() diff --git a/stubs/Repositories/Mysql/mysql.update.stub b/stubs/Repositories/Mysql/mysql.update.stub index 1a694fe..11da133 100644 --- a/stubs/Repositories/Mysql/mysql.update.stub +++ b/stubs/Repositories/Mysql/mysql.update.stub @@ -1,8 +1,4 @@ - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ public function update({{ EntityName }} ${{ EntityVariableName }}): int { {{ UpdateFieldSetter }} diff --git a/stubs/Resources/resource.class.stub b/stubs/Resources/resource.class.stub index dcbf063..f460446 100644 --- a/stubs/Resources/resource.class.stub +++ b/stubs/Resources/resource.class.stub @@ -9,10 +9,6 @@ use Nanvaie\DatabaseRepository\Models\Resources\Resource; class {{ ResourceName }} extends Resource { - /** - * @param Entity|{{ EntityName }} ${{ EntityVariableName }} - * @return array - */ public function toArray(${{ EntityVariableName }}): array { return [ @@ -20,10 +16,6 @@ class {{ ResourceName }} extends Resource ]; } - /** - * @param Entity|{{ EntityName }} ${{ EntityVariableName }} - * @return array - */ public function toArrayWithForeignKeys(${{ EntityVariableName }}): array { return $this->toArray(${{ EntityVariableName }}) + [ From 03c776dd2f6302cf576d21db828ae48d63e41041 Mon Sep 17 00:00:00 2001 From: sama20 Date: Thu, 5 Jan 2023 14:40:00 +0330 Subject: [PATCH 11/86] Some refactoring: Add BaseCommand.php to do some basic commands. Create a dependency injection for creating classes.(Now It is just on Entity. but it sould used in other makers). --- src/Commands/BaseCommand.php | 44 ++++++++++++ src/Commands/MakeEntity.php | 121 +++++---------------------------- src/Creators/BaseCreator.php | 53 +++++++++++++++ src/Creators/CreatorEntity.php | 110 ++++++++++++++++++++++++++++++ src/Creators/IClassCreator.php | 18 +++++ 5 files changed, 241 insertions(+), 105 deletions(-) create mode 100644 src/Commands/BaseCommand.php create mode 100644 src/Creators/BaseCreator.php create mode 100644 src/Creators/CreatorEntity.php create mode 100644 src/Creators/IClassCreator.php diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php new file mode 100644 index 0000000..36d0357 --- /dev/null +++ b/src/Commands/BaseCommand.php @@ -0,0 +1,44 @@ +option('delete')) { + unlink($filenameWithPath); + $this->info("Entity \"$entityName\" has been deleted."); + return 0; + } + } + public function checkDirectory(string $relativeEntitiesPath,string $entityName){ + if ( ! file_exists($relativeEntitiesPath) && ! mkdir($relativeEntitiesPath, 0775, true) && ! is_dir($relativeEntitiesPath)) { + $this->alert("Directory \"$relativeEntitiesPath\" was not created"); + return 0; + } + } + public function checkClassExist(string $relativeEntitiesPath, string $entityName){ + if (class_exists($relativeEntitiesPath.'\\'.$entityName) && ! $this->option('force')) { + $this->alert("Entity \"$entityName\" is already exist!"); + return 0; + } + } + + public function finalized(string $filenameWithPath,string $entityName, string $baseContent){ + file_put_contents($filenameWithPath, $baseContent); + if ($this->option('add-to-git')) { + shell_exec('git add '.$filenameWithPath); + } + + $this->info("Entity \"$entityName\" has been created."); + } + + public function checkEmpty(Collection $columns,string $tableName){ + if ($columns->isEmpty()) { + $this->alert("Couldn't retrieve columns from table \"$tableName\"! Perhaps table's name is misspelled."); + die; + } + } +} diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 7520d56..e00d4a1 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -3,11 +3,15 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\CreateEntity; use Nanvaie\DatabaseRepository\CustomMySqlQueries; -use Illuminate\Console\Command; +use Nanvaie\DatabaseRepository\Creators\CreatorEntity; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Illuminate\Support\Collection; -class MakeEntity extends Command +class MakeEntity extends BaseCommand { + use CustomMySqlQueries; /** * The name and signature of the console command. * @@ -26,39 +30,10 @@ class MakeEntity extends Command */ protected $description = 'Create a new entity.'; - use CustomMySqlQueries; - /** - * @param string $attributeStub - * @param string $attributeName - * @param string $attributeType - * @return string - */ - private function writeAttribute(string $attributeStub, string $attributeName, string $attributeType): string - { - return str_replace(['{{ AttributeType }}', '{{ AttributeName }}'], - [$attributeType, $attributeName], - $attributeStub); - } - - /** - * Generate getter and setter for given attribute. - * @param string $accessorStub - * @param string $attributeName - * @param string $attributeType - * @return string - */ - private function writeAccessors(string $accessorStub, string $attributeName, string $attributeType): string - { - return str_replace(['{{ AttributeType }}', '{{ AttributeName }}', '{{ GetterName }}', '{{ SetterName }}'], - [$attributeType, $attributeName, ucfirst($attributeName), ucfirst($attributeName)], - $accessorStub); - } /** * Execute the console command. - * - * @return int */ public function handle(): int { @@ -70,28 +45,12 @@ public function handle(): int $entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.entities'); $filenameWithPath = $relativeEntitiesPath . $entityName.'.php'; - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Entity \"$entityName\" has been deleted."); - return 0; - } - - if ( ! file_exists($relativeEntitiesPath) && ! mkdir($relativeEntitiesPath, 0775, true) && ! is_dir($relativeEntitiesPath)) { - $this->alert("Directory \"$relativeEntitiesPath\" was not created"); - return 0; - } - - if (class_exists($relativeEntitiesPath.'\\'.$entityName) && ! $this->option('force')) { - $this->alert("Entity \"$entityName\" is already exist!"); - return 0; - } + $this->checkDelete($filenameWithPath,$entityName); + $this->checkDirectory($relativeEntitiesPath,$entityName); + $this->checkClassExist($relativeEntitiesPath,$entityName); $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table \"$tableName\"! Perhaps table's name is misspelled."); - die; - } + $this->checkEmpty($columns,$tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); @@ -101,61 +60,13 @@ public function handle(): int $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); $accessorsStub = file_get_contents($entityStubsPath.'accessors.stub'); - // Create Attributes - $attributes = ''; - foreach ($columns as $_column) { - $defaultValue = ($_column->COLUMN_DEFAULT ?? 'null') ? ($_column->COLUMN_DEFAULT ?? 'null') : "''"; - $attributes .= $this->writeAttribute( - $attributeStub, - $_column->COLUMN_NAME.($_column->IS_NULLABLE === 'YES' ? ' = '.$defaultValue : ''), - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] - ); - } - - // Create Setters and Getters - $settersAndGetters = ''; - foreach ($columns as $_column) { - $settersAndGetters .= $this->writeAccessors( - $accessorsStub, - $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] - ); - } - - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); - - // Create Additional Attributes from Foreign Keys - foreach ($foreignKeys as $_foreignKey) { - $attributes .= $this->writeAttribute( - $attributeStub, - $_foreignKey->VARIABLE_NAME, - $_foreignKey->ENTITY_DATA_TYPE - ); - } - - // Create Additional Setters and Getters from Foreign keys - foreach ($foreignKeys as $_foreignKey) { - $settersAndGetters .= $this->writeAccessors( - $accessorsStub, - $_foreignKey->VARIABLE_NAME, - $_foreignKey->ENTITY_DATA_TYPE - ); - } - } - - $baseContent = str_replace(['{{ EntityNamespace }}', '{{ EntityName }}', '{{ Attributes }}', '{{ SettersAndGetters }}'], - [$entityNamespace, $entityName, $attributes, $settersAndGetters], - $baseContent); - - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec('git add '.$filenameWithPath); - } - - $this->info("Entity \"$entityName\" has been created."); + $entityCreator = new CreatorEntity($columns,$attributeStub, $detectForeignKeys,$tableName,$entityName,$entityNamespace,$accessorsStub,$baseContent); + $creator = new BaseCreator($entityCreator); + $baseContent = $creator->createClass(); + $this->finalized($filenameWithPath, $entityName, $baseContent); return 0; } + + } diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php new file mode 100644 index 0000000..36308d3 --- /dev/null +++ b/src/Creators/BaseCreator.php @@ -0,0 +1,53 @@ +creator = $creator; + } + + public function createClass():string + { +// Create Attributes + $attributesArray = $this->creator->createAttributs( + $this->creator->columns, + $this->creator->attributeStub, + $this->creator->detectForeignKeys, + $this->creator->tableName); + $attributes = implode('',array_column($attributesArray, '1')); + + +// Create Setters and Getters + $settersAndGettersArray = $this->creator->createFunctions( + $this->creator->columns, + $this->creator->accessorsStub, + $this->creator->detectForeignKeys, + $this->creator->tableName); + $settersAndGetters = implode('',array_column($settersAndGettersArray, '1')); + + $this->creator->baseContent = str_replace(['{{ EntityNamespace }}', '{{ EntityName }}', '{{ Attributes }}', '{{ SettersAndGetters }}'], + [ + $this->creator->entityNamespace, + $this->creator->entityName, + $attributes, + $settersAndGetters + ], + $this->creator->baseContent); + + return $this->creator->baseContent; + } + + + + + +} diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php new file mode 100644 index 0000000..0711fce --- /dev/null +++ b/src/Creators/CreatorEntity.php @@ -0,0 +1,110 @@ +COLUMN_DEFAULT ?? 'null') ? ($_column->COLUMN_DEFAULT ?? 'null') : "''"; + $attributes[] = [ + $_column->COLUMN_NAME, + $this->writeAttribute( + $attributeStub, + $_column->COLUMN_NAME.($_column->IS_NULLABLE === 'YES' ? ' = '.$defaultValue : ''), + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] + ) + ]; + } + + if ($detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($tableName); + + // Create Additional Attributes from Foreign Keys + foreach ($foreignKeys as $_foreignKey) { + $attributes[] = [ + $_column->COLUMN_NAME, + $this->writeAttribute( + $attributeStub, + $_foreignKey->VARIABLE_NAME, + $_foreignKey->ENTITY_DATA_TYPE + ) + ]; + } + } + + return $attributes; + } + + + public function createFunctions(Collection $columns, bool|string $accessorsStub,$detectForeignKeys,$tableName):array + { + $settersAndGetters = []; + foreach ($columns as $_column) { + $settersAndGetters[] = + [ + $_column->COLUMN_NAME, + $this->writeAccessors( + $accessorsStub, + $_column->COLUMN_NAME, + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] + ) + ]; + } + if ($detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($tableName); + + // Create Additional Setters and Getters from Foreign keys + foreach ($foreignKeys as $_foreignKey) { + $settersAndGetters[] = + [ + $_column->COLUMN_NAME, + $this->writeAccessors( + $accessorsStub, + $_foreignKey->VARIABLE_NAME, + $_foreignKey->ENTITY_DATA_TYPE + ) + ]; + } + } + return $settersAndGetters; + } + + + private function writeAttribute(string $attributeStub, string $attributeName, string $attributeType): string + { + return str_replace(['{{ AttributeType }}', '{{ AttributeName }}'], + [$attributeType, $attributeName], + $attributeStub); + } + + /** + * Generate getter and setter for given attribute. + */ + private function writeAccessors(string $accessorStub, string $attributeName, string $attributeType): string + { + return str_replace(['{{ AttributeType }}', '{{ AttributeName }}', '{{ GetterName }}', '{{ SetterName }}'], + [$attributeType, $attributeName, ucfirst($attributeName), ucfirst($attributeName)], + $accessorStub); + } + +} diff --git a/src/Creators/IClassCreator.php b/src/Creators/IClassCreator.php new file mode 100644 index 0000000..79a5471 --- /dev/null +++ b/src/Creators/IClassCreator.php @@ -0,0 +1,18 @@ + Date: Tue, 10 Jan 2023 14:02:48 +0330 Subject: [PATCH 12/86] Completed refactoring and added different code checking --- src/Commands/BaseCommand.php | 106 +++++++++-- src/Commands/MakeEntity.php | 43 ++--- src/Commands/MakeEnum.php | 94 ++-------- src/Commands/MakeFactory.php | 74 +++----- src/Commands/MakeInterfaceRepository.php | 90 +++------ src/Commands/MakeMySqlRepository.php | 177 +++--------------- src/Commands/MakeRedisRepository.php | 61 ++---- src/Commands/MakeRepository.php | 138 ++++---------- src/Commands/MakeResource.php | 102 +++------- src/Creators/BaseCreator.php | 100 +++++++--- src/Creators/CreatorEntity.php | 103 ++++++---- src/Creators/CreatorEnum.php | 65 +++++++ src/Creators/CreatorFactory.php | 75 ++++++++ src/Creators/CreatorMySqlRepository.php | 172 +++++++++++++++++ src/Creators/CreatorRedisRepository.php | 39 ++++ src/Creators/CreatorRepository.php | 138 ++++++++++++++ src/Creators/CreatorResource.php | 95 ++++++++++ src/Creators/IClassCreator.php | 15 +- src/DatabaseRepositoryServiceProvider.php | 2 - stubs/Entities/entity.attribute.stub | 2 +- stubs/Entities/entity.class.stub | 10 - stubs/Entities/entity.getter.stub | 5 + ...tity.accessors.stub => entity.setter.stub} | 5 - stubs/Enums/enum.attribute.stub | 2 +- stubs/Enums/enum.class.stub | 10 - stubs/Factories/factory.class.stub | 13 +- .../Repositories/Base/base.attribute.sql.stub | 2 +- stubs/Repositories/Base/base.class.stub | 16 -- stubs/Repositories/Base/base.construct.stub | 5 + stubs/Repositories/Mysql/mysql.construct.stub | 9 + stubs/Repositories/Mysql/mysql.create.stub | 3 +- stubs/Repositories/Mysql/mysql.delete.stub | 8 + stubs/Repositories/Mysql/mysql.undelete.stub | 8 + stubs/Resources/resource.class.stub | 1 - .../Resources/resource.function.foreign.stub | 6 + stubs/Resources/resource.function.getter.stub | 6 + stubs/base.class.stub | 10 + 37 files changed, 1074 insertions(+), 736 deletions(-) create mode 100644 src/Creators/CreatorEnum.php create mode 100644 src/Creators/CreatorFactory.php create mode 100644 src/Creators/CreatorMySqlRepository.php create mode 100644 src/Creators/CreatorRedisRepository.php create mode 100644 src/Creators/CreatorRepository.php create mode 100644 src/Creators/CreatorResource.php delete mode 100644 stubs/Entities/entity.class.stub create mode 100644 stubs/Entities/entity.getter.stub rename stubs/Entities/{entity.accessors.stub => entity.setter.stub} (57%) delete mode 100644 stubs/Enums/enum.class.stub delete mode 100644 stubs/Repositories/Base/base.class.stub create mode 100644 stubs/Repositories/Base/base.construct.stub create mode 100644 stubs/Repositories/Mysql/mysql.construct.stub create mode 100644 stubs/Repositories/Mysql/mysql.delete.stub create mode 100644 stubs/Repositories/Mysql/mysql.undelete.stub create mode 100644 stubs/Resources/resource.function.foreign.stub create mode 100644 stubs/Resources/resource.function.getter.stub create mode 100644 stubs/base.class.stub diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 36d0357..ade9807 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -1,44 +1,120 @@ tableName = $this->argument('table_name'); + if ($this->hasOption('foreign-keys')) $this->detectForeignKeys = $this->option('foreign-keys'); + $this->entityName = Str::singular(ucfirst(Str::camel($this->tableName))); + $this->entityNamespace = config('repository.path.namespace.entities'); + $this->relativeEntitiesPath = config('repository.path.relative.entities'); + $this->entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.entities'); + + $this->enumNamespace = config('repository.path.namespace.enums'); + $this->relativeEnumsPath = config('repository.path.relative.enums'); + $this->enumStubPath = __DIR__ . '/../../' . config('repository.path.stub.enums'); + + $this->entityVariableName = Str::camel($this->entityName); + $this->factoryName = $this->entityName . 'Factory'; + $this->factoryNamespace = config('repository.path.namespace.factories'); + $this->relativeFactoriesPath = config('repository.path.relative.factories'); + $this->factoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.factories'); + + $this->interfaceName = "I$this->entityName" . "Repository"; + $this->repositoryNamespace = config('repository.path.namespace.repositories'); + $this->relativeInterfacePath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; + $this->interfaceRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.interface'); + + $this->mysqlRepositoryName = 'MySql' . $this->entityName . 'Repository'; + $this->relativeMysqlRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; + $this->mysqlRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.mysql'); - public function checkDelete(string $filenameWithPath,string $entityName){ + } + + public function checkDelete(string $filenameWithPath, string $entityName, string $objectName): void + { if (file_exists($filenameWithPath) && $this->option('delete')) { unlink($filenameWithPath); - $this->info("Entity \"$entityName\" has been deleted."); - return 0; + $this->info("$objectName '$entityName' has been deleted."); + exit; } } - public function checkDirectory(string $relativeEntitiesPath,string $entityName){ - if ( ! file_exists($relativeEntitiesPath) && ! mkdir($relativeEntitiesPath, 0775, true) && ! is_dir($relativeEntitiesPath)) { + + public function checkDirectory(string $relativeEntitiesPath): void + { + if (!file_exists($relativeEntitiesPath) && !mkdir($relativeEntitiesPath, 0775, true) && !is_dir($relativeEntitiesPath)) { $this->alert("Directory \"$relativeEntitiesPath\" was not created"); - return 0; + exit; } } - public function checkClassExist(string $relativeEntitiesPath, string $entityName){ - if (class_exists($relativeEntitiesPath.'\\'.$entityName) && ! $this->option('force')) { - $this->alert("Entity \"$entityName\" is already exist!"); - return 0; + + public function checkClassExist(string $nameSpace, string $entityName, string $objectName): void + { + if (class_exists($nameSpace . '\\' . $entityName) && !$this->option('force')) { + $this->alert("$objectName \"$entityName\" is already exist!"); + exit; } } - public function finalized(string $filenameWithPath,string $entityName, string $baseContent){ + public function finalized(string $filenameWithPath, string $entityName, string $baseContent): void + { file_put_contents($filenameWithPath, $baseContent); if ($this->option('add-to-git')) { - shell_exec('git add '.$filenameWithPath); + shell_exec('git add ' . $filenameWithPath); } - $this->info("Entity \"$entityName\" has been created."); + $this->info("\"$entityName\" has been created."); + exit; } - public function checkEmpty(Collection $columns,string $tableName){ + public function checkEmpty(Collection $columns, string $tableName): void + { if ($columns->isEmpty()) { $this->alert("Couldn't retrieve columns from table \"$tableName\"! Perhaps table's name is misspelled."); - die; + exit; } } + + public function setChoice($choice): void + { + \config(['replacement.choice' => $choice]); + } + + public function getChoice(): null|string + { + return \config('replacement.choice'); + } } diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index e00d4a1..5f23327 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -30,43 +30,36 @@ class MakeEntity extends BaseCommand */ protected $description = 'Create a new entity.'; - - /** * Execute the console command. */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $entityNamespace = config('repository.path.namespace.entities'); - $relativeEntitiesPath = config('repository.path.relative.entities'); - $entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.entities'); - $filenameWithPath = $relativeEntitiesPath . $entityName.'.php'; + $this->setArguments(); + $filenameWithPath = $this->relativeEntitiesPath . $this->entityName.'.php'; - $this->checkDelete($filenameWithPath,$entityName); - $this->checkDirectory($relativeEntitiesPath,$entityName); - $this->checkClassExist($relativeEntitiesPath,$entityName); + $this->checkDelete($filenameWithPath,$this->entityName,"Entity"); + $this->checkDirectory($this->relativeEntitiesPath); + $this->checkClassExist($this->entityNamespace,$this->entityName,"Entity"); - $columns = $this->getAllColumnsInTable($tableName); - $this->checkEmpty($columns,$tableName); + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns,$this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } - $baseContent = file_get_contents($entityStubsPath.'class.stub'); - $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); - $accessorsStub = file_get_contents($entityStubsPath.'accessors.stub'); - - $entityCreator = new CreatorEntity($columns,$attributeStub, $detectForeignKeys,$tableName,$entityName,$entityNamespace,$accessorsStub,$baseContent); + $entityCreator = new CreatorEntity($columns, + $this->detectForeignKeys, + $this->tableName, + $this->entityName, + $this->entityNamespace, + $this->entityStubsPath + ); $creator = new BaseCreator($entityCreator); - $baseContent = $creator->createClass(); - - $this->finalized($filenameWithPath, $entityName, $baseContent); - return 0; - } + $baseContent = $creator->createClass($filenameWithPath,$this); + $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } } diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 43f6fe0..7a0d391 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -3,10 +3,12 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Nanvaie\DatabaseRepository\Creators\CreatorEnum; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; -class MakeEnum extends Command +class MakeEnum extends BaseCommand { /** * The name and signature of the console command. @@ -27,38 +29,12 @@ class MakeEnum extends Command use CustomMySqlQueries; - /** - * @param string $attributeStub - * @param string $attributeName - * @param string $attributeType - * @return string - */ - private function writeAttribute(string $attributeStub, string $attributeName, string $attributeString): string + public function handle(): void { - return str_replace(['{{ AttributeName }}', '{{ AttributeString }}'], - [$attributeName, $attributeString], - $attributeStub); - } + $this->setArguments(); + $columns = $this->getAllColumnsInTable($this->tableName); - /** - * Execute the console command. - * - * @return int - */ - public function handle(): int - { - $tableName = $this->argument('table_name'); - $enumNamespace = config('repository.path.namespace.enums'); - $relativeEntitiesPath = config('repository.path.relative.enums'); - $entityStubsPath = __DIR__ . '/../../' . config('repository.path.stub.enums'); - - - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table \"$tableName\"! Perhaps table's name is misspelled."); - die; - } + $this->checkEmpty($columns,$this->tableName); $enums = []; foreach ($columns as $_column) { @@ -66,60 +42,24 @@ public function handle(): int $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME); $enums[$enumClassName] = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE)); - $filenameWithPath = $relativeEntitiesPath . $enumClassName.'.php'; - - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Enum \"$enumClassName\" has been deleted."); - return 0; - } + $filenameWithPath = $this->relativeEnumsPath . $enumClassName.'.php'; + $this->checkDelete($filenameWithPath,$enumClassName,"Enum"); } } - // Create Attributes - - $baseContentStub = file_get_contents($entityStubsPath.'class.stub'); - $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); + $attributeStub = file_get_contents($this->enumStubPath.'attribute.stub'); foreach ($enums as $enumName => $enum) { - $filenameWithPath = $relativeEntitiesPath . $enumName.'.php'; + $filenameWithPath = $this->relativeEnumsPath . $enumName.'.php'; + $this->checkDirectory($this->enumNamespace); + $this->checkClassExist($this->relativeEnumsPath,$enumName,"Enum"); - if ( ! file_exists($relativeEntitiesPath) && ! mkdir($relativeEntitiesPath, 0775, true) && ! is_dir($relativeEntitiesPath)) { - $this->alert("Directory \"$relativeEntitiesPath\" was not created"); - return 0; - } - - if (class_exists($relativeEntitiesPath.'\\'.$enumName) && ! $this->option('force')) { - $this->alert("Enum \"$enumName\" is already exist!"); - return 0; - } - - $attributes = ''; - foreach ($enum as $_enum) { - $attributes .= $this->writeAttribute( - $attributeStub, - strtoupper($_enum), - $_enum - ); - } - - - $baseContent = str_replace(['{{ EnumNamespace }}', '{{ EnumName }}', '{{ Attributes }}',], - [$enumNamespace, $enumName, $attributes,], - $baseContentStub); + $enumCreator = new CreatorEnum($columns,$attributeStub,$enum,$enumName,$this->enumNamespace); + $creator = new BaseCreator($enumCreator); + $baseContent = $creator->createClass($filenameWithPath,$this); - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec('git add '.$filenameWithPath); - } - - $this->info("Enum \"$enumName\" has been created."); + $this->finalized($filenameWithPath, $enumName, $baseContent); } - - - - return 0; } } diff --git a/src/Commands/MakeFactory.php b/src/Commands/MakeFactory.php index 6c2be17..c19f03f 100644 --- a/src/Commands/MakeFactory.php +++ b/src/Commands/MakeFactory.php @@ -3,10 +3,11 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Nanvaie\DatabaseRepository\Creators\CreatorFactory; use Nanvaie\DatabaseRepository\CustomMySqlQueries; -use Illuminate\Console\Command; -class MakeFactory extends Command +class MakeFactory extends BaseCommand { /** * The name and signature of the console command. @@ -39,66 +40,37 @@ public function writeSetter(string $setterStub, string $columnName): string * * @return int */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $entityVariableName = Str::camel($entityName); - $factoryName = $entityName.'Factory'; - $entityNamespace = config('repository.path.namespace.entities'); - $factoryNamespace = config('repository.path.namespace.factories'); - $relativeFactoriesPath = config('repository.path.relative.factories'); - $factoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.factories'); - $filenameWithPath = $relativeFactoriesPath . $factoryName.'.php'; + $this->setArguments(); - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Factory \"$factoryName\" has been deleted."); - return 0; - } - - if ( ! file_exists($relativeFactoriesPath) && ! mkdir($relativeFactoriesPath, 0775, true) && ! is_dir($relativeFactoriesPath)) { - $this->alert("Directory \"$relativeFactoriesPath\" was not created"); - return 0; - } + $filenameWithPath = $this->relativeFactoriesPath . $this->factoryName.'.php'; - if (class_exists("$relativeFactoriesPath\\$factoryName") && ! $this->option('force')) { - $this->alert("Factory $factoryName is already exist!"); - return 0; - } + $this->checkDelete($filenameWithPath,$this->entityName,"Factory"); + $this->checkDirectory($this->relativeFactoriesPath); + $this->checkClassExist($this->factoryNamespace,$this->entityName,"Factory"); - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; - } + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns,$this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } - $baseContent = file_get_contents($factoryStubsPath.'class.stub'); - $setterStub = file_get_contents($factoryStubsPath.'setter.stub'); + $baseContent = file_get_contents($this->factoryStubsPath.'class.stub'); - // Initialize Class - $setterFunctions = ''; - foreach ($columns as $_column) { - $setterFunctions .= $this->writeSetter($setterStub, $_column->COLUMN_NAME); - } - - $baseContent = str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityNamespace }}', '{{ FactoryName }}', '{{ FactoryNamespace }}', '{{ EntityVariableName }}'], - [$setterFunctions, $entityName, $entityNamespace, $factoryName, $factoryNamespace, $entityVariableName], + $factoryCreator = new CreatorFactory( + $columns, + $this->entityName, + $this->entityNamespace, + $this->factoryStubsPath, + $this->factoryNamespace, + $this->entityVariableName, + $this->factoryName, $baseContent); + $creator = new BaseCreator($factoryCreator); + $baseContent = $creator->createClass($filenameWithPath,$this); - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } - - $this->info("Factory \"$factoryName\" has been created."); - - return 0; + $this->finalized($filenameWithPath, $this->factoryName, $baseContent); } } diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index 38b0374..fbe4b77 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -6,7 +6,7 @@ use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; -class MakeInterfaceRepository extends Command +class MakeInterfaceRepository extends BaseCommand { /** * The name and signature of the console command. @@ -47,68 +47,36 @@ private function writeGetAllFunction(string $getOneStub, string $columnName, str * * @return int */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $entityVariableName = Str::camel($entityName); - $interfaceName = "I$entityName"."Repository"; - $entityNamespace = config('repository.path.namespace.entities'); - $repositoryNamespace = config('repository.path.namespace.repositories'); - $relativeInterfacePath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; - $interfaceRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.interface'); - $filenameWithPath = $relativeInterfacePath . $interfaceName.'.php'; - - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Interface \"$interfaceName\" has been deleted."); - return 0; - } + $this->setArguments(); + $filenameWithPath = $this->relativeInterfacePath . $this->interfaceName . '.php'; - if ( ! file_exists($relativeInterfacePath) && ! mkdir($relativeInterfacePath, 0775, true) && ! is_dir($relativeInterfacePath)) { - $this->alert("Directory \"$relativeInterfacePath\" was not created"); - return 0; - } + $this->checkDelete($filenameWithPath, $this->interfaceName, "Interface"); + $this->checkDirectory($this->relativeInterfacePath); + $this->checkClassExist($this->repositoryNamespace, $this->interfaceName, "Interface"); - if (class_exists("$relativeInterfacePath\\$interfaceName") && ! $this->option('force')) { - $this->alert("Interface $interfaceName is already exist!"); - return 0; - } + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns, $this->tableName); - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); } - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); - } + $baseContent = file_get_contents($this->interfaceRepositoryStubsPath . 'class.stub'); + $getOneStub = file_get_contents($this->interfaceRepositoryStubsPath . 'getOneBy.stub'); + $getAllStub = file_get_contents($this->interfaceRepositoryStubsPath . 'getAllBy.stub'); + $createFunctionStub = file_get_contents($this->interfaceRepositoryStubsPath . 'create.stub'); + $updateFunctionStub = file_get_contents($this->interfaceRepositoryStubsPath . 'update.stub'); + $deleteAndUndeleteStub = file_get_contents($this->interfaceRepositoryStubsPath . 'deleteAndUndelete.stub'); - $baseContent = file_get_contents($interfaceRepositoryStubsPath.'class.stub'); - $getOneStub = file_get_contents($interfaceRepositoryStubsPath.'getOneBy.stub'); - $getAllStub = file_get_contents($interfaceRepositoryStubsPath.'getAllBy.stub'); - $createFunctionStub = file_get_contents($interfaceRepositoryStubsPath.'create.stub'); - $updateFunctionStub = file_get_contents($interfaceRepositoryStubsPath.'update.stub'); - $deleteAndUndeleteStub = file_get_contents($interfaceRepositoryStubsPath.'deleteAndUndelete.stub'); - - $baseContent = substr_replace($baseContent, - $this->writeGetOneFunction($getOneStub, 'id', 'int'), - -1, 0); - $baseContent = substr_replace($baseContent, - $this->writeGetAllFunction($getAllStub, 'id', 'int'), - -1, 0); - - if ($detectForeignKeys) { + $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, 'id', 'int'), -1, 0); + $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, 'id', 'int'), -1, 0); + + if ($this->detectForeignKeys) { foreach ($foreignKeys as $_foreignKey) { - $baseContent = substr_replace($baseContent, - $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $entityName), - -1, 0); - $baseContent = substr_replace($baseContent, - $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $entityName), - -1, 0); + $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName), -1, 0); + $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName), -1, 0); } } @@ -127,17 +95,9 @@ public function handle(): int } $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ InterfaceRepositoryName }}', '{{ RepositoryNamespace }}'], - [$entityName, $entityNamespace, $entityVariableName, $interfaceName, $repositoryNamespace], + [$this->entityName, $this->entityNamespace, $this->entityVariableName, $this->interfaceName, $this->repositoryNamespace], $baseContent); - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } - - $this->info("Interface \"$interfaceName\" has been created."); - - return 0; + $this->finalized($filenameWithPath, $this->entityName, $baseContent); } } diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index b54c61c..2fdf75c 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -3,10 +3,13 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Nanvaie\DatabaseRepository\Creators\CreatorEntity; +use Nanvaie\DatabaseRepository\Creators\CreatorMySqlRepository; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; -class MakeMySqlRepository extends Command +class MakeMySqlRepository extends BaseCommand { /** * The name and signature of the console command. @@ -28,161 +31,37 @@ class MakeMySqlRepository extends Command use CustomMySqlQueries; - private function writeGetOneFunction(string $getOneStub, string $columnName, string $attributeType): string - { - return str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}'], - [ucfirst(Str::camel($columnName)), $columnName, $attributeType, Str::camel($columnName)], - $getOneStub); - } - - private function writeGetAllFunction(string $getOneStub, string $columnName, string $attributeType): string - { - return str_replace(['{{ FunctionNamePlural }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}'], - [ucfirst(Str::plural(Str::camel($columnName))), $columnName, $attributeType, Str::plural(Str::camel($columnName))], - $getOneStub); - } - - private function writeGetterFunction(string $getterStub, string $columnName): string - { - return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], - [$columnName, ucfirst(Str::camel($columnName))], - $getterStub); - } - - private function writeSetterFunction(string $setterStub, string $columnName): string - { - return str_replace('{{ SetterName }}', - ucfirst(Str::camel($columnName)), - $setterStub); - } - /** * Execute the console command. * * @return int */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $entityVariableName = Str::camel($entityName); - $factoryName = $entityName.'Factory'; - $interfaceName = 'I'.$entityName.'Repository'; - $mysqlRepositoryName = 'MySql'.$entityName.'Repository'; - $entityNamespace = config('repository.path.namespace.entities'); - $factoryNamespace = config('repository.path.namespace.factories'); - $repositoryNamespace = config('repository.path.namespace.repositories'); - $relativeMysqlRepositoryPath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; - $mysqlRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.mysql'); - $filenameWithPath = $relativeMysqlRepositoryPath . $mysqlRepositoryName.'.php'; - - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("MySql Repository \"$mysqlRepositoryName\" has been deleted."); - return 0; - } - - if ( ! file_exists($relativeMysqlRepositoryPath) && ! mkdir($relativeMysqlRepositoryPath, 0775, true) && ! is_dir($relativeMysqlRepositoryPath)) { - $this->alert("Directory \"$relativeMysqlRepositoryPath\" was not created"); - return 0; - } - - if (class_exists("$relativeMysqlRepositoryPath\\$mysqlRepositoryName") && ! $this->option('force')) { - $this->alert("Repository $mysqlRepositoryName is already exist!"); - return 0; - } - - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; - } - - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); - } - - $baseContent = file_get_contents($mysqlRepositoryStubsPath.'class.stub'); - $getOneStub = file_get_contents($mysqlRepositoryStubsPath.'getOneBy.stub'); - $getAllStub = file_get_contents($mysqlRepositoryStubsPath.'getAllBy.stub'); - $createFunctionStub = file_get_contents($mysqlRepositoryStubsPath.'create.stub'); - $updateFunctionStub = file_get_contents($mysqlRepositoryStubsPath.'update.stub'); - $deleteAndUndeleteStub = file_get_contents($mysqlRepositoryStubsPath.'deleteAndUndelete.stub'); - $getterStub = file_get_contents($mysqlRepositoryStubsPath.'getter.stub'); - $setterStub = file_get_contents($mysqlRepositoryStubsPath.'setter.stub'); - $timeFieldStub = file_get_contents($mysqlRepositoryStubsPath.'timeField.stub'); - $functions = ''; - - // Initialize MySql Repository - $functions .= $this->writeGetOneFunction($getOneStub, 'id', 'int'); - $functions .= $this->writeGetAllFunction($getAllStub, 'id', 'int'); - - if ($detectForeignKeys) { - foreach ($foreignKeys as $_foreignKey) { - $functions .= $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $entityName); - $functions .= $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $entityName); - } - } - - $getterFunctions = ''; - $setterFunctions = ''; - // Create "create" function - foreach ($columns as $_column) { - if ( ! in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { - $getterFunctions .= $this->writeGetterFunction($getterStub, $_column->COLUMN_NAME); - } - if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { - $setterFunctions .= $this->writeSetterFunction($setterStub, $_column->COLUMN_NAME); - } - } - $createFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ SetterFunctions }}"], - [substr($getterFunctions, 0, -1), substr($setterFunctions, 0, -1)], - $createFunctionStub - ); - - $functions .= $createFunctionStub; - - $getterFunctions = ''; - $setterFunctions = ''; - // Create "update" function - foreach ($columns as $_column) { - if ( ! in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { - $getterFunctions .= $this->writeGetterFunction($getterStub, $_column->COLUMN_NAME); - } - if ($_column->COLUMN_NAME === 'updated_at') { - $setterFunctions .= $this->writeSetterFunction($setterStub, $_column->COLUMN_NAME); - } - } - $updateFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ UpdateFieldSetter }}"], - [substr($getterFunctions, 0, -1), substr($setterFunctions, 0, -1)], - $updateFunctionStub + $this->setArguments(); + $filenameWithPath = $this->relativeMysqlRepositoryPath . $this->mysqlRepositoryName.'.php'; + $this->checkDelete($filenameWithPath,$this->mysqlRepositoryName,"MySql Repository"); + $this->checkDirectory($this->relativeMysqlRepositoryPath); + $this->checkClassExist($this->repositoryNamespace,$this->mysqlRepositoryName,"MySql Repository"); + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns,$this->tableName); + + $mysqlRepoCreator = new CreatorMySqlRepository($columns, + $this->tableName, + $this->entityName, + $this->entityVariableName, + $this->factoryName, + $this->entityNamespace, + $this->factoryNamespace, + $this->mysqlRepositoryName, + $this->repositoryNamespace, + $this->interfaceName, + $this->mysqlRepositoryStubsPath, + $this->detectForeignKeys ); + $creator = new BaseCreator($mysqlRepoCreator); + $baseContent = $creator->createClass($filenameWithPath,$this); - $functions .= $updateFunctionStub; - - // Create "delete" and "undelete" functions if necessary - $hasSoftDelete = in_array('deleted_at', $columns->pluck('COLUMN_NAME')->toArray(), true); - if ($hasSoftDelete) { - $functions .= $deleteAndUndeleteStub; - } - - $baseContent = str_replace('{{ Functions }}', - $functions, $baseContent); - - $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ FactoryName }}', '{{ FactoryNamespace }}', '{{ EntityVariableName }}', '{{ MySqlRepositoryName }}', '{{ RepositoryNamespace }}', '{{ RepositoryInterfaceName }}', '{{ TableName }}', '{{ HasSoftDelete }}',], - [$entityName, $entityNamespace, $factoryName, $factoryNamespace, $entityVariableName, $mysqlRepositoryName, $repositoryNamespace, $interfaceName, $tableName, $hasSoftDelete ? 'true' : 'false',], - $baseContent); - - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } - - $this->info("MySql Repository \"$mysqlRepositoryName\" has been created."); - - return 0; + $this->finalized($filenameWithPath, $this->mysqlRepositoryName, $baseContent); } } diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index a65d325..d4bb78f 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -3,10 +3,12 @@ namespace Nanvaie\DatabaseRepository\Commands; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Nanvaie\DatabaseRepository\Creators\CreatorRedisRepository; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Console\Command; -class MakeRedisRepository extends Command +class MakeRedisRepository extends BaseCommand { /** * The name and signature of the console command. @@ -33,57 +35,30 @@ class MakeRedisRepository extends Command * * @return int */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $redisRepositoryName = "Redis$entityName"."Repository"; + $this->setArguments(); + $redisRepositoryName = "Redis$this->entityName"."Repository"; $redisRepositoryNamespace = config('repository.path.namespace.repositories'); - $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; + $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $filenameWithPath = $relativeRedisRepositoryPath . $redisRepositoryName . '.php'; - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Redis Repository \"$redisRepositoryName\" has been deleted."); - return 0; - } - - if ( ! file_exists($relativeRedisRepositoryPath) && ! mkdir($relativeRedisRepositoryPath, 0775, true) && ! is_dir($relativeRedisRepositoryPath)) { - $this->alert("Directory \"$relativeRedisRepositoryPath\" was not created"); - return 0; - } - - if (class_exists("$relativeRedisRepositoryPath\\$redisRepositoryName") && ! $this->option('force')) { - $this->alert("Repository $redisRepositoryName is already exist!"); - return 0; - } + $this->checkDelete($filenameWithPath,$redisRepositoryName,"Redis Repository"); + $this->checkDirectory($relativeRedisRepositoryPath); + $this->checkClassExist($this->repositoryNamespace,$redisRepositoryName,"Redis Repository"); - $columns = $this->getAllColumnsInTable($tableName); + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns,$this->tableName); - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); } - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); - } - - // Initialize Redis Repository - $redisRepositoryContent = "option('add-to-git')) { - shell_exec("git add $relativeRedisRepositoryPath/$redisRepositoryName.php"); - } + $mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName,$redisRepositoryNamespace, $this->entityName); + $creator = new BaseCreator($mysqlRepoCreator); + $baseContent = $creator->createClass($filenameWithPath,$this); - $this->info("Redis Repository \"$redisRepositoryName\" has been created."); + $this->finalized($filenameWithPath, $redisRepositoryName, $baseContent); - return 0; } } diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 23433ab..3eb6190 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -2,11 +2,13 @@ namespace Nanvaie\DatabaseRepository\Commands; -use Illuminate\Console\Command; +//use Illuminate\Console\Command; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Nanvaie\DatabaseRepository\Creators\CreatorRepository; use Nanvaie\DatabaseRepository\CustomMySqlQueries; -class MakeRepository extends Command +class MakeRepository extends BaseCommand { /** * The name and signature of the console command. @@ -61,112 +63,40 @@ private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryV * * @return int */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $entityVariableName = Str::camel($entityName); - $factoryName = $entityName.'Factory'; - $interfaceName = 'I'.$entityName.'Repository'; - $repositoryName = $entityName.'Repository'; - $sqlRepositoryName = 'MySql'.$entityName.'Repository'; + $this->setArguments(); + $repositoryName = $this->entityName.'Repository'; + $sqlRepositoryName = 'MySql'.$this->entityName.'Repository'; $sqlRepositoryVariable = 'mysqlRepository'; - $entityNamespace = config('repository.path.namespace.entities'); - $factoryNamespace = config('repository.path.namespace.factories'); - $repositoryNamespace = config('repository.path.namespace.repositories'); - $relativeRepositoryPath = config('repository.path.relative.repositories') . "$entityName" . DIRECTORY_SEPARATOR; + $relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); $filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php'; - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Repository \"$repositoryName\" has been deleted."); - return 0; - } - - if ( ! file_exists($relativeRepositoryPath) && ! mkdir($relativeRepositoryPath, 0775, true) && ! is_dir($relativeRepositoryPath)) { - $this->alert("Directory \"$relativeRepositoryPath\" was not created"); - return 0; - } - - if (class_exists("$relativeRepositoryPath\\$repositoryName") && ! $this->option('force')) { - $this->alert("Repository $repositoryName is already exist!"); - return 0; - } - - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; - } - - $baseContent = file_get_contents($repositoryStubsPath.'class.stub'); - $functionStub = file_get_contents($repositoryStubsPath.'function.stub'); - $attributeSqlStub = file_get_contents($repositoryStubsPath.'attribute.sql.stub'); - $setterSqlStub = file_get_contents($repositoryStubsPath.'setter.sql.stub'); - - // Initialize Repository - $attributes = ''; - $attributes = substr_replace($attributes, - $this->writeSqlAttribute($attributeSqlStub, $sqlRepositoryVariable), - -1, 0); - - $setters = ''; - $setters = substr_replace($setters, - $this->writeSqlAttribute($setterSqlStub, $sqlRepositoryVariable), - -1, 0); - - $functions = ''; - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'getOneBy', 'id', 'int'), - -1, 0); - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'getAllBy', 'id', 'array'), - -1, 0); - - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); - - foreach ($foreignKeys as $_foreignKey) { - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'getOneBy', $_foreignKey->COLUMN_NAME, 'int'), - -1, 0); - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'getAllBy', $_foreignKey->COLUMN_NAME, 'array'), - -1, 0); - } - } - - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'create', $entityVariableName, $entityName), - -1, 0); - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'update', $entityVariableName, $entityName), - -1, 0); - - if (in_array('deleted_at', $columns->pluck('COLUMN_NAME')->toArray(), true)) { - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'remove', $entityVariableName, $entityName), - -1, 0); - $functions = substr_replace($functions, - $this->writeFunction($functionStub, 'restore', $entityVariableName, $entityName), - -1, 0); - } - - $baseContent = str_replace(['{{ Attributes }}', '{{ Setters }}', '{{ Functions }}', '{{ EntityName }}', '{{ EntityNamespace }}', '{{ FactoryName }}', '{{ FactoryNamespace }}', '{{ EntityVariableName }}', '{{ RepositoryName }}', '{{ SqlRepositoryName }}', '{{ SqlRepositoryVariable }}', '{{ RepositoryNamespace }}', '{{ RepositoryInterfaceName }}', '{{ TableName }}'], - [$attributes, $setters, $functions, $entityName, $entityNamespace, $factoryName, $factoryNamespace, $entityVariableName, $repositoryName, $sqlRepositoryName, $sqlRepositoryVariable, $repositoryNamespace, $interfaceName, $tableName], - $baseContent); - - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } - - $this->info("Repository \"$repositoryName\" has been created."); - - return 0; + $this->checkDelete($filenameWithPath,$repositoryName,"Repository"); + $this->checkDirectory($relativeRepositoryPath); + $this->checkClassExist($this->repositoryNamespace,$repositoryName,"Repository"); + + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns,$this->tableName); + + $RepoCreator = new CreatorRepository( + $columns, + $sqlRepositoryVariable, + $sqlRepositoryName, + $repositoryStubsPath, + $this->detectForeignKeys, + $this->tableName, + $this->entityVariableName, + $this->entityName, + $this->entityNamespace, + $repositoryName, + $this->interfaceName, + $this->repositoryNamespace + ); + $creator = new BaseCreator($RepoCreator); + $baseContent = $creator->createClass($filenameWithPath,$this); + + $this->finalized($filenameWithPath, $repositoryName, $baseContent); } } diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index 0eca8b6..8aaf2de 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -4,9 +4,11 @@ use Illuminate\Console\Command; use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\Creators\BaseCreator; +use Nanvaie\DatabaseRepository\Creators\CreatorResource; use Nanvaie\DatabaseRepository\CustomMySqlQueries; -class MakeResource extends Command +class MakeResource extends BaseCommand { /** * The name and signature of the console command. @@ -28,93 +30,39 @@ class MakeResource extends Command use CustomMySqlQueries; - public function writeGetter(string $getterStub, string $columnName, string $attributeName) - { - return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], - [$columnName, ucfirst($attributeName)], - $getterStub); - } - - public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName) - { - return str_replace(['{{ AttributeName }}', '{{ GetterName }}', '{{ AttributeType }}'], - [Str::snake($columnName), ucfirst($columnName), ucfirst($attributeName)], - $foreignGetterStub); - } - /** * Execute the console command. * * @return int */ - public function handle(): int + public function handle(): void { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = Str::singular(ucfirst(Str::camel($tableName))); - $entityVariableName = Str::camel($entityName); - $entityNamespace = config('repository.path.namespace.entities'); - $resourceName = $entityName."Resource"; + $this->setArguments(); + $resourceName = $this->entityName."Resource"; $resourceNamespace = config('repository.path.namespace.resources'); $relativeResourcesPath = config('repository.path.relative.resources'); $resourceStubsPath = __DIR__ . '/../../' . config('repository.path.stub.resources'); $filenameWithPath = $relativeResourcesPath . $resourceName.'.php'; - if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); - $this->info("Resource \"$resourceName\" has been deleted."); - return 0; - } - - if ( ! file_exists($relativeResourcesPath) && ! mkdir($relativeResourcesPath, 0775, true) && ! is_dir($relativeResourcesPath)) { - $this->alert("Directory \"$relativeResourcesPath\" was not created"); - return 0; - } - - if (class_exists("$relativeResourcesPath\\$resourceName") && ! $this->option('force')) { - $this->alert("Resource $resourceName is already exist!"); - return 0; - } - - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; - } - - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); - } - - $baseContent = file_get_contents($resourceStubsPath.'class.stub'); - $getterStub = file_get_contents($resourceStubsPath.'getter.default.stub'); - $foreignGetterStub = file_get_contents($resourceStubsPath.'getter.foreign.stub'); - - $getterFunctions = ''; - foreach ($columns as $_column) { - $getterFunctions .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)); - } - - $foreignGetterFunctions = ''; - if ($detectForeignKeys) { - foreach ($foreignKeys as $_foreignKey) { - $foreignGetterFunctions .= $this->writeForeignGetter($foreignGetterStub, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE); - } - } - - $baseContent = str_replace(['{{ GetterFunctions }}', '{{ ForeignGetterFunctions }}', '{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ ResourceName }}', '{{ ResourceNamespace }}',], - [substr($getterFunctions, 0, -1), substr($foreignGetterFunctions, 0, -1), $entityName, $entityNamespace, $entityVariableName, $resourceName, $resourceNamespace,], - $baseContent); - - file_put_contents($filenameWithPath, $baseContent); - - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } - - $this->info("Resource \"$resourceName\" has been created."); + $this->checkDelete($filenameWithPath,$resourceName,"Resource"); + $this->checkDirectory($relativeResourcesPath); + $this->checkClassExist($resourceNamespace,$resourceName,"Resource"); + + $columns = $this->getAllColumnsInTable($this->tableName); + $this->checkEmpty($columns,$this->tableName); + + $RepoCreator = new CreatorResource($columns, + $this->tableName, + $this->entityName, + $this->entityNamespace, + $resourceNamespace, + $resourceName, + $resourceStubsPath, + $this->detectForeignKeys, + $this->entityVariableName); + $creator = new BaseCreator($RepoCreator); + $baseContent = $creator->createClass($filenameWithPath,$this); + $this->finalized($filenameWithPath,$resourceName,$baseContent); - return 0; } } diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 36308d3..17dd3af 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -4,50 +4,96 @@ use Illuminate\Support\Str; use Illuminate\Console\Command; +use Nanvaie\DatabaseRepository\Commands\BaseCommand; +use Nanvaie\DatabaseRepository\Utility; use function Nanvaie\DatabaseRepository\Commands\config; -class BaseCreator +class BaseCreator extends BaseCommand { + use Utility; private $creator; + private null|string $choice=null; + const ALL_OPTIONS = ['Current','New','Always keep current','Always replace with new']; public function __construct(IClassCreator $creator) { $this->creator = $creator; } - public function createClass():string + public function createClass(string $filenameWithPath,BaseCommand $command):string { -// Create Attributes - $attributesArray = $this->creator->createAttributs( - $this->creator->columns, - $this->creator->attributeStub, - $this->creator->detectForeignKeys, - $this->creator->tableName); - $attributes = implode('',array_column($attributesArray, '1')); - - -// Create Setters and Getters - $settersAndGettersArray = $this->creator->createFunctions( - $this->creator->columns, - $this->creator->accessorsStub, - $this->creator->detectForeignKeys, - $this->creator->tableName); - $settersAndGetters = implode('',array_column($settersAndGettersArray, '1')); - - $this->creator->baseContent = str_replace(['{{ EntityNamespace }}', '{{ EntityName }}', '{{ Attributes }}', '{{ SettersAndGetters }}'], + $attributesArray = $this->creator->createAttributs(); + $functionsArray = $this->creator->createFunctions(); + $usesArray = $this->creator->createUses(); + + $specificPattern = "/(?public|private|protected)\sfunction\s+(?\w+)\s*\((?[^\)]*)\)\s*:?\s*(?.{0,100})\s*(?\{(?:[^{}]+|(?&body))*\})/"; + $functionsArray = $this->checkDiffrence($filenameWithPath,$functionsArray,$command,$specificPattern); + $generalPattern = "/class\s*[^$]*\{(?[^}]*)((public|protected|private) function |})/isU"; + $specificPattern = '/(public|protected|private) [^\s]* \$*(?[^\s;\=]*)\s*[^;]*;/is'; + $attributesArray = $this->checkDiffrence($filenameWithPath,$attributesArray,$command,$specificPattern,$generalPattern); + + $attributes = implode(' ',$attributesArray); + $functions = implode(' ',$functionsArray); + $uses = implode(PHP_EOL,$usesArray); + + $basePath = __DIR__ . '/../../stubs/base.class.stub' ; + $this->creator->baseContent = str_replace(['{{ Namespace }}', '{{ UseSection }}', '{{ ClassName }}', '{{ ExtendSection }}', '{{ Parameters }}', '{{ Functions }}'], [ - $this->creator->entityNamespace, - $this->creator->entityName, + $this->creator->getNameSpace(), + $uses, + $this->creator->getClassName(), + $this->creator->getExtendSection(), $attributes, - $settersAndGetters + $functions ], - $this->creator->baseContent); + file_get_contents($basePath)); return $this->creator->baseContent; } + public function checkDiffrence(string $filenameWithPath,array $newParamsArray,BaseCommand $command,string $specificPattern,string $generalPattern='/(?.*)/is'): array + { + if (file_exists($filenameWithPath)) { + $file = file_get_contents($filenameWithPath); + if(preg_match($generalPattern, $file, $matches)){ + if(preg_match_all($specificPattern,$matches['main_part'],$attributMatches)){ + for ($i=0; $igetChoice(),self::ALL_OPTIONS)<2) + $this->setChoice(null); + if(!isset($newParamsArray[$attributMatches['name'][$i]])){ + $newParamsArray[$attributMatches['name'][$i]] = ''; + } + $attr = $newParamsArray[$attributMatches['name'][$i]]; - - - + if(preg_replace('/\s+/', '', $attr)===preg_replace('/\s+/', '', $attributMatches[0][$i])){ + $command->info("There is no diffrence between '". $attributMatches['name'][$i] ."' "); + }else{ + $command->warn("WARN: '". $attributMatches['name'][$i]."'s are not the same"); + if(is_null($this->getChoice()) && array_search($this->getChoice(),self::ALL_OPTIONS)<2){ + // $command->table( ['Current','new'], [['Current'=>trim($attributMatches[0][$i]),'New'=>trim($attr)]],'default'); + $command->line("######################## CURRENT #########################",'fg=magenta'); + $command->line(trim($attributMatches[0][$i]),'fg=magenta'); + $command->line("##########################################################",'fg=magenta'); + $command->line(" ",'fg=magenta'); + $command->line("########################## NEW ###########################",'fg=cyan'); + $command->line(trim($attr),'fg=cyan'); + $command->line("##########################################################",'fg=cyan'); + $this->setChoice($command->choice('Choose one version',self::ALL_OPTIONS,0)); + if(array_search($this->getChoice(),self::ALL_OPTIONS)%2==0 ){ + $newParamsArray[$attributMatches['name'][$i]]=trim($attributMatches[0][$i]).PHP_EOL; + $command->info("Current version selected for '". $attributMatches['name'][$i] ."', "); + } + }elseif (array_search($this->getChoice(),self::ALL_OPTIONS)==2){ + $newParamsArray[$attributMatches['name'][$i]]=trim($attributMatches[0][$i]).PHP_EOL; + $command->info("Current version selected for '". $attributMatches['name'][$i] ."', "); + }else{ + $command->info("New version replaced for '". $attributMatches['name'][$i] ."', "); + } + } + } + } + } + } + return $newParamsArray; + } } diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index 0711fce..01e0e30 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -8,32 +8,38 @@ class CreatorEntity implements IClassCreator { use CustomMySqlQueries; -// protected $columns= + protected const PARENT_NAME = 'Entity'; + public function __construct( public Collection $columns, - public string $attributeStub, public string $detectForeignKeys, public string $tableName, public string $entityName, public string $entityNamespace, - public string $accessorsStub, - public string $baseContent) + public string $entityStubsPath) { } - public function createAttributs(Collection $columns, string $attributeStub,string $detectForeignKeys,string $tableName):array{ + public function getExtendSection(): string + { + return 'extends '.self::PARENT_NAME; + } + + public function createAttributs():array{ + $columns = $this->columns; + $entityStubsPath = $this->entityStubsPath; + $detectForeignKeys = $this->detectForeignKeys; + $tableName = $this->tableName; $attributes = []; foreach ($columns as $_column) { $defaultValue = ($_column->COLUMN_DEFAULT ?? 'null') ? ($_column->COLUMN_DEFAULT ?? 'null') : "''"; - $attributes[] = [ - $_column->COLUMN_NAME, + $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( - $attributeStub, + $entityStubsPath, $_column->COLUMN_NAME.($_column->IS_NULLABLE === 'YES' ? ' = '.$defaultValue : ''), ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] - ) - ]; + ); } if ($detectForeignKeys) { @@ -41,57 +47,76 @@ public function createAttributs(Collection $columns, string $attributeStub,strin // Create Additional Attributes from Foreign Keys foreach ($foreignKeys as $_foreignKey) { - $attributes[] = [ - $_column->COLUMN_NAME, + $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( - $attributeStub, + $entityStubsPath, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE - ) - ]; + ); } } return $attributes; } + public function createUses(): array + { + return ["use Nanvaie\DatabaseRepository\Models\Entity\Entity;"]; + } - public function createFunctions(Collection $columns, bool|string $accessorsStub,$detectForeignKeys,$tableName):array + public function createFunctions():array { + + $columns = $this->columns; + $entityStubsPath = $this->entityStubsPath; + $detectForeignKeys = $this->detectForeignKeys; + $tableName = $this->tableName; $settersAndGetters = []; foreach ($columns as $_column) { - $settersAndGetters[] = - [ + $settersAndGetters['get'.ucwords($_column->COLUMN_NAME)] = + $this->writeAccessors( + $entityStubsPath, $_column->COLUMN_NAME, - $this->writeAccessors( - $accessorsStub, - $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] - ) - ]; + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE], + 'getter' + ); + $settersAndGetters['set'.ucwords($_column->COLUMN_NAME)] = + $this->writeAccessors( + $entityStubsPath, + $_column->COLUMN_NAME, + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE], + 'setter' + ); + } if ($detectForeignKeys) { $foreignKeys = $this->extractForeignKeys($tableName); // Create Additional Setters and Getters from Foreign keys foreach ($foreignKeys as $_foreignKey) { - $settersAndGetters[] = - [ - $_column->COLUMN_NAME, + $settersAndGetters['get'.ucwords($_column->COLUMN_NAME)] = + $this->writeAccessors( + $entityStubsPath, + $_foreignKey->VARIABLE_NAME, + $_foreignKey->ENTITY_DATA_TYPE, + 'getter' + ); + $settersAndGetters['set'.ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( - $accessorsStub, + $entityStubsPath, $_foreignKey->VARIABLE_NAME, - $_foreignKey->ENTITY_DATA_TYPE - ) - ]; + $_foreignKey->ENTITY_DATA_TYPE, + 'setter' + ); } } return $settersAndGetters; } - - private function writeAttribute(string $attributeStub, string $attributeName, string $attributeType): string + private function writeAttribute(string $entityStubsPath, string $attributeName, string $attributeType): string { + + $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); return str_replace(['{{ AttributeType }}', '{{ AttributeName }}'], [$attributeType, $attributeName], $attributeStub); @@ -100,11 +125,21 @@ private function writeAttribute(string $attributeStub, string $attributeName, st /** * Generate getter and setter for given attribute. */ - private function writeAccessors(string $accessorStub, string $attributeName, string $attributeType): string + private function writeAccessors(string $entityStubsPath, string $attributeName, string $attributeType,string $type): string { + $accessorStub = file_get_contents($entityStubsPath.$type.'.stub'); return str_replace(['{{ AttributeType }}', '{{ AttributeName }}', '{{ GetterName }}', '{{ SetterName }}'], [$attributeType, $attributeName, ucfirst($attributeName), ucfirst($attributeName)], $accessorStub); } + public function getNameSpace(): string + { + return $this->entityNamespace; + } + + public function getClassName(): string + { + return $this->entityName; + } } diff --git a/src/Creators/CreatorEnum.php b/src/Creators/CreatorEnum.php new file mode 100644 index 0000000..bb828c4 --- /dev/null +++ b/src/Creators/CreatorEnum.php @@ -0,0 +1,65 @@ +enum as $_enum) { + $attributes[strtoupper($_enum)] = $this->writeAttribute( + $this->attributeStub, + strtoupper($_enum), + $_enum + ); + } + return $attributes; + } + + public function createFunctions(): array + { + return []; + } + + public function createUses(): array + { + return ['use Nanvaie\DatabaseRepository\Models\Enums\Enum;']; + } + + public function getExtendSection(): string + { + return 'extends Enum'; + } + + public function getNameSpace(): string + { + return $this->enumNamespace; + } + + public function getClassName(): string + { + return $this->enumName; + } + + private function writeAttribute(string $attributeStub, string $attributeName, string $attributeString): string + { + return str_replace(['{{ AttributeName }}', '{{ AttributeString }}'], + [$attributeName, $attributeString], + $attributeStub); + } +} diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php new file mode 100644 index 0000000..ed5c2fa --- /dev/null +++ b/src/Creators/CreatorFactory.php @@ -0,0 +1,75 @@ +factoryNamespace; + } + + public function createAttributs(): array + { + // TODO: Implement createAttributs() method. + return []; + } + + public function createFunctions(): array + { + $setterStub = file_get_contents($this->factoryStubsPath . 'setter.stub'); + $setterFunctions = ''; + foreach ($this->columns as $_column) { + $setterFunctions .= $this->writeSetter($setterStub, $_column->COLUMN_NAME); + } + return ['makeEntityFromStdClass' => + str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityVariableName }}'], + [$setterFunctions, $this->entityName, $this->entityVariableName], + $this->baseContent) + ]; + } + + public function createUses(): array + { + return [ + "use $this->entityNamespace\\$this->entityName;", + "use Nanvaie\DatabaseRepository\Models\Factories\Factory;", + "use stdClass;" + ]; + + } + + public function getExtendSection(): string + { + return 'extends ' . self::PARENT_NAME; + } + + public function writeSetter(string $setterStub, string $columnName): string + { + return str_replace(['{{ SetterName }}', '{{ AttributeName }}'], + [ucfirst($columnName), Str::snake($columnName)], + $setterStub); + } + + public function getClassName(): string + { + return $this->factoryName; + } +} diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php new file mode 100644 index 0000000..b3f756d --- /dev/null +++ b/src/Creators/CreatorMySqlRepository.php @@ -0,0 +1,172 @@ +repositoryNamespace . '\\' . $this->entityName; + } + public function createUses(): array + { + return [ + "use $this->entityNamespace\\$this->entityName;", + "use $this->factoryNamespace\\$this->factoryName;", + "use Illuminate\Support\Collection;", + "use Nanvaie\DatabaseRepository\Models\Repositories\MySqlRepository;" + ]; + } + public function getClassName(): string + { + return $this->mysqlRepositoryName; + } + public function getExtendSection(): string + { + return "extends MySqlRepository implements " . $this->interfaceName; + } + public function createAttributs(): array + { + return []; + } + public function createFunctions(): array + { + + $baseContent = file_get_contents($this->mysqlRepositoryStubsPath . 'class.stub'); + $constructContent = file_get_contents($this->mysqlRepositoryStubsPath . 'construct.stub'); + $getOneStub = file_get_contents($this->mysqlRepositoryStubsPath . 'getOneBy.stub'); + $getAllStub = file_get_contents($this->mysqlRepositoryStubsPath . 'getAllBy.stub'); + $createFunctionStub = file_get_contents($this->mysqlRepositoryStubsPath . 'create.stub'); + $updateFunctionStub = file_get_contents($this->mysqlRepositoryStubsPath . 'update.stub'); + $deleteStub = file_get_contents($this->mysqlRepositoryStubsPath . 'delete.stub'); + $undeleteStub = file_get_contents($this->mysqlRepositoryStubsPath . 'undelete.stub'); + $getterStub = file_get_contents($this->mysqlRepositoryStubsPath . 'getter.stub'); + $setterStub = file_get_contents($this->mysqlRepositoryStubsPath . 'setter.stub'); + $timeFieldStub = file_get_contents($this->mysqlRepositoryStubsPath . 'timeField.stub'); + + $functions = []; + // Initialize MySql Repository + $hasSoftDelete = in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true); + $functions['__construct'] = $this->getConstruct($this->tableName, $this->factoryName, $hasSoftDelete, $constructContent); + $functions['getOneById'] = $this->writeGetOneFunction($getOneStub, 'id', 'int'); + $functions['getAllByIds'] = $this->writeGetAllFunction($getAllStub, 'id', 'int'); + + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); + foreach ($foreignKeys as $_foreignKey) { + $indx = 'getAllBy' . ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); + $functions[$indx] = $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName); + $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($_foreignKey->COLUMN_NAME))); + $functions[$indx] = $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName); + } + } + + $getterFunctions = ''; + $setterFunctions = ''; + // Create "create" function + foreach ($this->columns as $_column) { + if (!in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { + $getterFunctions .= $this->writeGetterFunction($getterStub, $_column->COLUMN_NAME); + } + if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { + $setterFunctions .= $this->writeSetterFunction($setterStub, $_column->COLUMN_NAME); + } + } + $createFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ SetterFunctions }}"], + [substr($getterFunctions, 0, -1), substr($setterFunctions, 0, -1)], + $createFunctionStub + ); + + $functions['create'] = $createFunctionStub; + + $getterFunctions = ''; + $setterFunctions = ''; + // Create "update" function + foreach ($this->columns as $_column) { + if (!in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { + $getterFunctions .= $this->writeGetterFunction($getterStub, $_column->COLUMN_NAME); + } + if ($_column->COLUMN_NAME === 'updated_at') { + $setterFunctions .= $this->writeSetterFunction($setterStub, $_column->COLUMN_NAME); + } + } + $updateFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ UpdateFieldSetter }}"], + [substr($getterFunctions, 0, -1), substr($setterFunctions, 0, -1)], + $updateFunctionStub + ); + + $functions['update'] = $updateFunctionStub; + + // Create "delete" and "undelete" functions if necessary + if ($hasSoftDelete) { + $functions['remove'] = $deleteStub; + $functions['restore'] = $undeleteStub; + } + foreach ($functions as &$func) { + $func = str_replace(["{{ EntityName }}", "{{ EntityVariableName }}"], + [$this->entityName, $this->entityVariableName], + $func + ); + } + return $functions; + } + + private function writeGetOneFunction(string $getOneStub, string $columnName, string $attributeType): string + { + return str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}'], + [ucfirst(Str::camel($columnName)), $columnName, $attributeType, Str::camel($columnName)], + $getOneStub); + } + + private function writeGetAllFunction(string $getOneStub, string $columnName, string $attributeType): string + { + return str_replace(['{{ FunctionNamePlural }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}'], + [ucfirst(Str::plural(Str::camel($columnName))), $columnName, $attributeType, Str::plural(Str::camel($columnName))], + $getOneStub); + } + + private function writeGetterFunction(string $getterStub, string $columnName): string + { + return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], + [$columnName, ucfirst(Str::camel($columnName))], + $getterStub); + } + + private function writeSetterFunction(string $setterStub, string $columnName): string + { + return str_replace('{{ SetterName }}', + ucfirst(Str::camel($columnName)), + $setterStub); + } + + private function getConstruct(string $tableName, string $factoryName, bool $hasSoftDelete, string $constructContent) + { + return str_replace( + ['{{ TableName }}', '{{ FactoryName }}', '{{ HasSoftDelete }}'], + [$tableName, $factoryName, $hasSoftDelete ? 'true' : 'false'], + $constructContent); + } +} diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php new file mode 100644 index 0000000..6733666 --- /dev/null +++ b/src/Creators/CreatorRedisRepository.php @@ -0,0 +1,39 @@ +redisRepositoryNamespace . '\\' . $this->entityName; + } + public function createUses(): array + { + return ["use Nanvaie\DatabaseRepository\Models\Repositories\RedisRepository;"]; + } + public function getClassName(): string + { + return $this->redisRepositoryName; + } + public function getExtendSection(): string + { + return "extends RedisRepository"; + } + public function createAttributs(): array + { + return []; + } + public function createFunctions(): array + { + return []; + } +} diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php new file mode 100644 index 0000000..73f6a0f --- /dev/null +++ b/src/Creators/CreatorRepository.php @@ -0,0 +1,138 @@ +repositoryNamespace.'\\'.$this->entityName; + } + + public function createUses(): array + { + return [ + "use $this->entityNamespace\\$this->entityName;", + "use Illuminate\Support\Collection;" + ]; + } + + public function getClassName(): string + { + return $this->repositoryName; + } + + public function getExtendSection(): string + { + return 'implements '.$this->interfaceName; + } + + public function createAttributs(): array + { + $attributeSqlStub = file_get_contents($this->repositoryStubsPath.'attribute.sql.stub'); + // Initialize Repository + $attributes = []; + $attributes[$this->sqlRepositoryVariable] = $this->writeSqlAttribute($attributeSqlStub, $this->sqlRepositoryVariable,$this->sqlRepositoryName); +// dd($attributes); + return $attributes; + } + + public function createFunctions(): array + { + $constructStub = file_get_contents($this->repositoryStubsPath.'construct.stub'); + $functionStub = file_get_contents($this->repositoryStubsPath.'function.stub'); + $setterSqlStub = file_get_contents($this->repositoryStubsPath.'setter.sql.stub'); + + $functions = []; + $functions['__construct'] = $this->getConstruct($setterSqlStub,$constructStub); + $functions['getOneById'] = $this->writeFunction($functionStub, 'getOneBy', 'id', 'int'); + $functions['getAllByIds'] = $this->writeFunction($functionStub, 'getAllBy', 'id', 'array'); + + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); + + foreach ($foreignKeys as $_foreignKey) { + $fun_name = ucfirst(Str::plural(Str::camel($_foreignKey->COLUMN_NAME))); + $functions[$fun_name] = $this->writeFunction($functionStub, 'getOneBy', $_foreignKey->COLUMN_NAME, 'int'); + + $fun_name = ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); + $functions[$fun_name] = $this->writeFunction($functionStub, 'getAllBy', $_foreignKey->COLUMN_NAME, 'array'); + } + } + + $functions['create'] = $this->writeFunction($functionStub, 'create', $this->entityVariableName, $this->entityName); + $functions['update'] = $this->writeFunction($functionStub, 'update', $this->entityVariableName, $this->entityName); + if (in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true)) { + $functions['remove'] = $this->writeFunction($functionStub, 'remove', $this->entityVariableName, $this->entityName); + $functions['restore'] = $this->writeFunction($functionStub, 'restore', $this->entityVariableName, $this->entityName); + } + + foreach ($functions as &$func) { + $func=str_replace(["{{ SqlRepositoryVariable }}",'{{ SqlRepositoryName }}','{{ EntityName }}'], + [$this->sqlRepositoryVariable,$this->sqlRepositoryName,$this->entityName], + $func + ); + } + return $functions; + } + + public function getConstruct(string $setterSqlStub,string $constructStub){ + $setters = ''; + $setters = substr_replace($setters, + $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable,$this->sqlRepositoryName), + -1, 0); + + return str_replace("{{ Setters }}",$setters,$constructStub); + + } +} diff --git a/src/Creators/CreatorResource.php b/src/Creators/CreatorResource.php new file mode 100644 index 0000000..5aed0e4 --- /dev/null +++ b/src/Creators/CreatorResource.php @@ -0,0 +1,95 @@ +resourceNamespace; + } + + public function createUses(): array + { + return ["use $this->entityNamespace\\$this->entityName;", + "use Nanvaie\DatabaseRepository\Models\Entity\Entity;", + "use Nanvaie\DatabaseRepository\Models\Resources\Resource;"]; + } + + public function getClassName(): string + { + return $this->resourceName; + } + + public function getExtendSection(): string + { + return 'extends Resource'; + } + + public function createAttributs(): array + { + return []; + } + + public function createFunctions(): array + { + + $getterStub = file_get_contents($this->resourceStubsPath . 'getter.default.stub'); + $foreignGetterStub = file_get_contents($this->resourceStubsPath . 'getter.foreign.stub'); + $foreignFunStub = file_get_contents($this->resourceStubsPath . 'function.foreign.stub'); + $getterFunStub = file_get_contents($this->resourceStubsPath . 'function.getter.stub'); + + $getters = ''; + foreach ($this->columns as $_column) { + $getters .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)); + } + + $foreignGetterFunctions = ''; + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); + foreach ($foreignKeys as $_foreignKey) { + $foreignGetterFunctions .= $this->writeForeignGetter($foreignGetterStub, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE); + } + } + $functions = []; + $functions['toArray'] = str_replace(['{{ Getters }}'], [$getters], $getterFunStub); + $functions['toArray'] = str_replace(['{{ EntityVariableName }}'], [$this->entityVariableName], $functions['toArray']); + $functions['toArrayWithForeignKeys'] = str_replace(['{{ ForeignGetterFunctions }}'], [$foreignGetterFunctions], $foreignFunStub); + $functions['toArrayWithForeignKeys'] = str_replace(['{{ EntityVariableName }}'], [$this->entityVariableName], $functions['toArrayWithForeignKeys']); + return $functions; + } + + public function writeGetter(string $getterStub, string $columnName, string $attributeName) + { + return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], + [$columnName, ucfirst($attributeName)], + $getterStub); + } + + public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName) + { + return str_replace(['{{ AttributeName }}', '{{ GetterName }}', '{{ AttributeType }}'], + [Str::snake($columnName), ucfirst($columnName), ucfirst($attributeName)], + $foreignGetterStub); + } +} diff --git a/src/Creators/IClassCreator.php b/src/Creators/IClassCreator.php index 79a5471..e41ce24 100644 --- a/src/Creators/IClassCreator.php +++ b/src/Creators/IClassCreator.php @@ -3,16 +3,15 @@ namespace Nanvaie\DatabaseRepository\Creators; use Illuminate\Support\Collection; +use Nanvaie\DatabaseRepository\CustomMySqlQueries; interface IClassCreator { -// public function getOneById(int $id): null|User; -// -// public function getAllByIds(array $ids): Collection; -// - public function createAttributs(Collection $columns, string $attributeStub,string $detectForeignKeys,string $tableName): array; - - public function createFunctions(Collection $columns, bool|string $accessorsStub,string $detectForeignKeys,string $tableName):array; - + public function getNameSpace(): string; + public function createUses(): array; + public function getClassName(): string; + public function getExtendSection(): string; + public function createAttributs(): array; + public function createFunctions(): array; } diff --git a/src/DatabaseRepositoryServiceProvider.php b/src/DatabaseRepositoryServiceProvider.php index 4382fe7..7154ccc 100644 --- a/src/DatabaseRepositoryServiceProvider.php +++ b/src/DatabaseRepositoryServiceProvider.php @@ -20,7 +20,6 @@ */ class DatabaseRepositoryServiceProvider extends ServiceProvider { - public function __construct($app) { parent::__construct($app); @@ -49,7 +48,6 @@ public function offerPublishing(): void } } - /** * Register custom commands. */ diff --git a/stubs/Entities/entity.attribute.stub b/stubs/Entities/entity.attribute.stub index 6df2dec..47de060 100644 --- a/stubs/Entities/entity.attribute.stub +++ b/stubs/Entities/entity.attribute.stub @@ -1 +1 @@ - protected {{ AttributeType }} ${{ AttributeName }}; +protected {{ AttributeType }} ${{ AttributeName }}; diff --git a/stubs/Entities/entity.class.stub b/stubs/Entities/entity.class.stub deleted file mode 100644 index ea530d5..0000000 --- a/stubs/Entities/entity.class.stub +++ /dev/null @@ -1,10 +0,0 @@ -{{ AttributeName }}; + } diff --git a/stubs/Entities/entity.accessors.stub b/stubs/Entities/entity.setter.stub similarity index 57% rename from stubs/Entities/entity.accessors.stub rename to stubs/Entities/entity.setter.stub index 2e18d12..0883693 100644 --- a/stubs/Entities/entity.accessors.stub +++ b/stubs/Entities/entity.setter.stub @@ -1,9 +1,4 @@ - public function get{{ GetterName }}(): {{ AttributeType }} - { - return $this->{{ AttributeName }}; - } - public function set{{ SetterName }}({{ AttributeType }} ${{ AttributeName }}): void { $this->{{ AttributeName }} = ${{ AttributeName }}; diff --git a/stubs/Enums/enum.attribute.stub b/stubs/Enums/enum.attribute.stub index 9bb6678..6d4bc36 100644 --- a/stubs/Enums/enum.attribute.stub +++ b/stubs/Enums/enum.attribute.stub @@ -1 +1 @@ - public const {{ AttributeName }} = '{{ AttributeString }}'; +public const {{ AttributeName }} = '{{ AttributeString }}'; diff --git a/stubs/Enums/enum.class.stub b/stubs/Enums/enum.class.stub deleted file mode 100644 index 22d008c..0000000 --- a/stubs/Enums/enum.class.stub +++ /dev/null @@ -1,10 +0,0 @@ -table = '{{ TableName }}'; + $this->primaryKey = 'id'; + $this->softDelete = {{ HasSoftDelete }}; + $this->factory = new {{ FactoryName }}(); + + parent::__construct(); + } diff --git a/stubs/Repositories/Mysql/mysql.create.stub b/stubs/Repositories/Mysql/mysql.create.stub index 79693d2..a2431aa 100644 --- a/stubs/Repositories/Mysql/mysql.create.stub +++ b/stubs/Repositories/Mysql/mysql.create.stub @@ -1,5 +1,4 @@ - - public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} +public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} { {{ SetterFunctions }} diff --git a/stubs/Repositories/Mysql/mysql.delete.stub b/stubs/Repositories/Mysql/mysql.delete.stub new file mode 100644 index 0000000..eae0902 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.delete.stub @@ -0,0 +1,8 @@ +public function remove({{ EntityName }} ${{ EntityVariableName }}): int + { + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + 'deleted_at' => date('Y-m-d H:i:s'), + ]); + } diff --git a/stubs/Repositories/Mysql/mysql.undelete.stub b/stubs/Repositories/Mysql/mysql.undelete.stub new file mode 100644 index 0000000..3baf14f --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.undelete.stub @@ -0,0 +1,8 @@ +public function restore({{ EntityName }} ${{ EntityVariableName }}): int + { + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + 'deleted_at' => null, + ]); + } diff --git a/stubs/Resources/resource.class.stub b/stubs/Resources/resource.class.stub index f460446..c52cfd6 100644 --- a/stubs/Resources/resource.class.stub +++ b/stubs/Resources/resource.class.stub @@ -6,7 +6,6 @@ use {{ EntityNamespace }}\{{ EntityName }}; use Nanvaie\DatabaseRepository\Models\Entity\Entity; use Nanvaie\DatabaseRepository\Models\Resources\Resource; - class {{ ResourceName }} extends Resource { public function toArray(${{ EntityVariableName }}): array diff --git a/stubs/Resources/resource.function.foreign.stub b/stubs/Resources/resource.function.foreign.stub new file mode 100644 index 0000000..beea893 --- /dev/null +++ b/stubs/Resources/resource.function.foreign.stub @@ -0,0 +1,6 @@ +public function toArrayWithForeignKeys(${{ EntityVariableName }}): array + { + return $this->toArray(${{ EntityVariableName }}) + [ +{{ ForeignGetterFunctions }} + ]; + } diff --git a/stubs/Resources/resource.function.getter.stub b/stubs/Resources/resource.function.getter.stub new file mode 100644 index 0000000..b64d3bf --- /dev/null +++ b/stubs/Resources/resource.function.getter.stub @@ -0,0 +1,6 @@ +public function toArray(${{ EntityVariableName }}): array + { + return [ +{{ Getters }} + ]; + } diff --git a/stubs/base.class.stub b/stubs/base.class.stub new file mode 100644 index 0000000..618ccc1 --- /dev/null +++ b/stubs/base.class.stub @@ -0,0 +1,10 @@ + Date: Wed, 11 Jan 2023 12:47:19 +0330 Subject: [PATCH 13/86] Add useful method for indexes. --- src/Commands/MakeRepository.php | 28 --------- src/Creators/BaseCreator.php | 6 +- src/Creators/CreatorMySqlRepository.php | 10 +++- src/Creators/CreatorRepository.php | 78 +++++++++++++------------ src/CustomMySqlQueries.php | 16 +++++ 5 files changed, 68 insertions(+), 70 deletions(-) diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 3eb6190..861fe53 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -30,34 +30,6 @@ class MakeRepository extends BaseCommand use CustomMySqlQueries; - private function writeFunction(string $functionStub, string $functionName, string $columnName, string $attributeType): string - { - if ($functionName === 'getOneBy') { - $functionReturnType = 'null|{{ EntityName }}'; - $functionName .= ucfirst(Str::camel($columnName)); - $columnName = Str::camel($columnName); - } elseif ($functionName === 'getAllBy') { - $functionReturnType = 'Collection'; - $functionName .= ucfirst(Str::plural(Str::camel($columnName))); - $columnName = Str::plural(Str::camel($columnName)); - } elseif ($functionName === 'create') { - $functionReturnType = $attributeType; - } elseif (in_array($functionName, ['update', 'remove', 'restore'])) { - $functionReturnType = 'int'; - } - - return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}'], - [$functionName, $attributeType, Str::camel($columnName), $functionReturnType], - $functionStub); - } - - private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable): string - { - return str_replace(['{{ SqlRepositoryVariable }}'], - [$sqlRepositoryVariable], - $attributeStub); - } - /** * Execute the console command. * diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 17dd3af..8cc603f 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -81,13 +81,13 @@ public function checkDiffrence(string $filenameWithPath,array $newParamsArray,Ba $this->setChoice($command->choice('Choose one version',self::ALL_OPTIONS,0)); if(array_search($this->getChoice(),self::ALL_OPTIONS)%2==0 ){ $newParamsArray[$attributMatches['name'][$i]]=trim($attributMatches[0][$i]).PHP_EOL; - $command->info("Current version selected for '". $attributMatches['name'][$i] ."', "); + $command->warn("Action: Current version selected for '". $attributMatches['name'][$i] ."', "); } }elseif (array_search($this->getChoice(),self::ALL_OPTIONS)==2){ $newParamsArray[$attributMatches['name'][$i]]=trim($attributMatches[0][$i]).PHP_EOL; - $command->info("Current version selected for '". $attributMatches['name'][$i] ."', "); + $command->warn("Action: Current version selected for '". $attributMatches['name'][$i] ."', "); }else{ - $command->info("New version replaced for '". $attributMatches['name'][$i] ."', "); + $command->warn("Action: New version replaced for '". $attributMatches['name'][$i] ."', "); } } } diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index b3f756d..17ab02b 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -74,10 +74,18 @@ public function createFunctions(): array $functions['getOneById'] = $this->writeGetOneFunction($getOneStub, 'id', 'int'); $functions['getAllByIds'] = $this->writeGetAllFunction($getAllStub, 'id', 'int'); + $indexes = $this->extractIndexes($this->tableName); + foreach ($indexes as $index) { + $indx = 'getOneBy' . ucfirst(Str::camel($index->COLUMN_NAME)); + $functions[$indx] = $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->entityName); + $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); + $functions[$indx] = $this->writeGetAllFunction($getAllStub, $index->COLUMN_NAME, $this->entityName); + } + if ($this->detectForeignKeys) { $foreignKeys = $this->extractForeignKeys($this->tableName); foreach ($foreignKeys as $_foreignKey) { - $indx = 'getAllBy' . ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); + $indx = 'getOneBy' . ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); $functions[$indx] = $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName); $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($_foreignKey->COLUMN_NAME))); $functions[$indx] = $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName); diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index 73f6a0f..24805d6 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -10,20 +10,21 @@ class CreatorRepository implements IClassCreator { public function __construct( public Collection $columns, - public string $sqlRepositoryVariable, - public string $sqlRepositoryName, - public string $repositoryStubsPath, - public string $detectForeignKeys, - public string $tableName, - public string $entityVariableName, - public string $entityName, - public string $entityNamespace, - public string $repositoryName, - public string $interfaceName, - public string $repositoryNamespace + public string $sqlRepositoryVariable, + public string $sqlRepositoryName, + public string $repositoryStubsPath, + public string $detectForeignKeys, + public string $tableName, + public string $entityVariableName, + public string $entityName, + public string $entityNamespace, + public string $repositoryName, + public string $interfaceName, + public string $repositoryNamespace ) { } + use CustomMySqlQueries; private function writeFunction(string $functionStub, string $functionName, string $columnName, string $attributeType): string @@ -49,14 +50,14 @@ private function writeFunction(string $functionStub, string $functionName, strin private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable, string $sqlRepositoryName): string { - return str_replace(['{{ SqlRepositoryVariable }}','{{ SqlRepositoryName }}'], - [$sqlRepositoryVariable,$sqlRepositoryName], + return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'], + [$sqlRepositoryVariable, $sqlRepositoryName], $attributeStub); } public function getNameSpace(): string { - return $this->repositoryNamespace.'\\'.$this->entityName; + return $this->repositoryNamespace . '\\' . $this->entityName; } public function createUses(): array @@ -74,65 +75,66 @@ public function getClassName(): string public function getExtendSection(): string { - return 'implements '.$this->interfaceName; + return 'implements ' . $this->interfaceName; } public function createAttributs(): array { - $attributeSqlStub = file_get_contents($this->repositoryStubsPath.'attribute.sql.stub'); - // Initialize Repository + $attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub'); $attributes = []; - $attributes[$this->sqlRepositoryVariable] = $this->writeSqlAttribute($attributeSqlStub, $this->sqlRepositoryVariable,$this->sqlRepositoryName); -// dd($attributes); + $attributes[$this->sqlRepositoryVariable] = $this->writeSqlAttribute($attributeSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName); return $attributes; } public function createFunctions(): array { - $constructStub = file_get_contents($this->repositoryStubsPath.'construct.stub'); - $functionStub = file_get_contents($this->repositoryStubsPath.'function.stub'); - $setterSqlStub = file_get_contents($this->repositoryStubsPath.'setter.sql.stub'); + $constructStub = file_get_contents($this->repositoryStubsPath . 'construct.stub'); + $functionStub = file_get_contents($this->repositoryStubsPath . 'function.stub'); + $setterSqlStub = file_get_contents($this->repositoryStubsPath . 'setter.sql.stub'); $functions = []; - $functions['__construct'] = $this->getConstruct($setterSqlStub,$constructStub); + $functions['__construct'] = $this->getConstruct($setterSqlStub, $constructStub); $functions['getOneById'] = $this->writeFunction($functionStub, 'getOneBy', 'id', 'int'); $functions['getAllByIds'] = $this->writeFunction($functionStub, 'getAllBy', 'id', 'array'); + $indexes = $this->extractIndexes($this->tableName); + foreach ($indexes as $index) { + $fun_name = ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); + $functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $index->COLUMN_NAME, 'array'); + $fun_name = ucfirst(Str::camel($index->COLUMN_NAME)); + $functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $index->COLUMN_NAME, 'int'); + } if ($this->detectForeignKeys) { $foreignKeys = $this->extractForeignKeys($this->tableName); foreach ($foreignKeys as $_foreignKey) { - $fun_name = ucfirst(Str::plural(Str::camel($_foreignKey->COLUMN_NAME))); - $functions[$fun_name] = $this->writeFunction($functionStub, 'getOneBy', $_foreignKey->COLUMN_NAME, 'int'); - $fun_name = ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); - $functions[$fun_name] = $this->writeFunction($functionStub, 'getAllBy', $_foreignKey->COLUMN_NAME, 'array'); + $functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $_foreignKey->COLUMN_NAME, 'int'); + $fun_name = ucfirst(Str::plural(Str::camel($_foreignKey->COLUMN_NAME))); + $functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $_foreignKey->COLUMN_NAME, 'array'); } } $functions['create'] = $this->writeFunction($functionStub, 'create', $this->entityVariableName, $this->entityName); $functions['update'] = $this->writeFunction($functionStub, 'update', $this->entityVariableName, $this->entityName); if (in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true)) { - $functions['remove'] = $this->writeFunction($functionStub, 'remove', $this->entityVariableName, $this->entityName); - $functions['restore'] = $this->writeFunction($functionStub, 'restore', $this->entityVariableName, $this->entityName); + $functions['remove'] = $this->writeFunction($functionStub, 'remove', $this->entityVariableName, $this->entityName); + $functions['restore'] = $this->writeFunction($functionStub, 'restore', $this->entityVariableName, $this->entityName); } foreach ($functions as &$func) { - $func=str_replace(["{{ SqlRepositoryVariable }}",'{{ SqlRepositoryName }}','{{ EntityName }}'], - [$this->sqlRepositoryVariable,$this->sqlRepositoryName,$this->entityName], + $func = str_replace(["{{ SqlRepositoryVariable }}", '{{ SqlRepositoryName }}', '{{ EntityName }}'], + [$this->sqlRepositoryVariable, $this->sqlRepositoryName, $this->entityName], $func ); } return $functions; } - public function getConstruct(string $setterSqlStub,string $constructStub){ + public function getConstruct(string $setterSqlStub, string $constructStub) + { $setters = ''; - $setters = substr_replace($setters, - $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable,$this->sqlRepositoryName), - -1, 0); - - return str_replace("{{ Setters }}",$setters,$constructStub); - + $setters = substr_replace($setters,$this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName),-1, 0); + return str_replace("{{ Setters }}", $setters, $constructStub); } } diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index 6f9597b..e07e738 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -89,4 +89,20 @@ public function extractForeignKeys(string $tableName): Collection return $foreignKeys; } + + /** + * Extract all indexes from a given table! + */ + public function extractIndexes(string $tableName): Collection + { + $indexes = DB::table('INFORMATION_SCHEMA.KEY_COLUMN_USAGE') + ->where('TABLE_SCHEMA', config('database.connections.mysql.database')) + ->where('TABLE_NAME', $tableName) + ->where('CONSTRAINT_NAME', '!=' ,'PRIMARY') + ->whereNull('REFERENCED_TABLE_NAME') + ->orderBy('ORDINAL_POSITION') + ->get(); + + return $indexes; + } } From 29a8c797d74c7c591694b48c71a5f6f46f191732 Mon Sep 17 00:00:00 2001 From: sama20 Date: Wed, 11 Jan 2023 12:56:43 +0330 Subject: [PATCH 14/86] Remove usefulness doc blocks. --- src/Creators/BaseCreator.php | 1 - src/Creators/CreatorEntity.php | 3 -- src/CustomMySqlQueries.php | 5 ---- src/Models/Entity/Entity.php | 11 -------- src/Models/Factories/IFactory.php | 8 ------ src/Models/Repositories/MySqlRepository.php | 29 ++------------------ src/Models/Resources/Resource.php | 9 +----- stubs/Repositories/Mysql/mysql.getAllBy.stub | 3 ++ stubs/Repositories/Mysql/mysql.getOneBy.stub | 3 ++ 9 files changed, 9 insertions(+), 63 deletions(-) diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 8cc603f..eb04c06 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -10,7 +10,6 @@ class BaseCreator extends BaseCommand { - use Utility; private $creator; private null|string $choice=null; const ALL_OPTIONS = ['Current','New','Always keep current','Always replace with new']; diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index 01e0e30..f08710e 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -122,9 +122,6 @@ private function writeAttribute(string $entityStubsPath, string $attributeName, $attributeStub); } - /** - * Generate getter and setter for given attribute. - */ private function writeAccessors(string $entityStubsPath, string $attributeName, string $attributeType,string $type): string { $accessorStub = file_get_contents($entityStubsPath.$type.'.stub'); diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index e07e738..169f12f 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -43,8 +43,6 @@ trait CustomMySqlQueries /** * Extract all columns from a given table. - * @param string $tableName - * @return Collection */ public function getAllColumnsInTable(string $tableName): Collection { @@ -57,7 +55,6 @@ public function getAllColumnsInTable(string $tableName): Collection /** * Extract all table names. - * @return Collection */ public function getAllTableNames(): Collection { @@ -70,8 +67,6 @@ public function getAllTableNames(): Collection /** * Extract all foreign keys from a given table. Foreign key's relations must define in MySql! - * @param string $tableName - * @return Collection */ public function extractForeignKeys(string $tableName): Collection { diff --git a/src/Models/Entity/Entity.php b/src/Models/Entity/Entity.php index 23ccf37..a1132d1 100644 --- a/src/Models/Entity/Entity.php +++ b/src/Models/Entity/Entity.php @@ -11,9 +11,6 @@ abstract class Entity implements JsonSerializable, Arrayable // contain originals value of attributes private $originals = []; - /** - * @return int - */ abstract public function getId(): int; public function __construct() @@ -44,7 +41,6 @@ public function __isset($name) /** * Make all variables of the object as null - * @return $this */ public function clearVariables(): self { @@ -55,9 +51,6 @@ public function clearVariables(): self return $this; } - /** - * @return int - */ public function getPrimaryKey(): int { return $this->getId(); @@ -101,7 +94,6 @@ public function emptyOriginals() /** * get an Array of Changed Attributes - * @return array */ public function changedAttributesName(): array { @@ -117,7 +109,6 @@ public function changedAttributesName(): array /** * get an Array of Changed Attributes with new values - * @return array */ public function getDirty(): array { @@ -133,7 +124,6 @@ public function getDirty(): array /** * get an Array of Changed Attributes with original values - * @return array */ public function getChanges(): array { @@ -148,7 +138,6 @@ public function getChanges(): array /** * is any attribute changed? - * @return bool */ public function isDirty(): bool { diff --git a/src/Models/Factories/IFactory.php b/src/Models/Factories/IFactory.php index 27a667f..68d1dd7 100644 --- a/src/Models/Factories/IFactory.php +++ b/src/Models/Factories/IFactory.php @@ -8,15 +8,7 @@ interface IFactory { - /** - * @param stdClass $entity - * @return Entity - */ public function makeEntityFromStdClass(stdClass $entity): Entity; - /** - * @param Collection|array $entities - * @return Collection - */ public function makeCollectionOfEntities(Collection|array $entities): Collection; } diff --git a/src/Models/Repositories/MySqlRepository.php b/src/Models/Repositories/MySqlRepository.php index 25f1b7b..ce17006 100644 --- a/src/Models/Repositories/MySqlRepository.php +++ b/src/Models/Repositories/MySqlRepository.php @@ -31,7 +31,6 @@ public function __construct() /** * Notice: this function cannot be used in async jobs because the connection is not serializable! - * @param ConnectionInterface $connection */ public function changeDatabaseConnection($connection) { @@ -64,14 +63,6 @@ public function newQuery(): Builder // return $this; // } - /** - * @param int|null $total - * @param int $offset - * @param int $count - * @param array $orders - * @param array $filters - * @return Collection - */ public function getAllForGridView(null|int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Collection { $query = $this->newQuery(); @@ -99,10 +90,6 @@ public function exists($columnValue, $columnName = null) /** * this is for validation purpose look at AppServiceProvider - * @param $attribute - * @param $value - * @param null $ignoredPrimaryKey - * @return bool */ public function valueExists($attribute, $value, $ignoredPrimaryKey = null) { @@ -121,10 +108,7 @@ public function valueExists($attribute, $value, $ignoredPrimaryKey = null) return $query->exists(); } - /** - * @param Entity $model - */ - public function updateOrCreate($model) + public function updateOrCreate(Entity $model) { if ($this->exists($model->getPrimaryKey())) { $this->update($model); @@ -136,7 +120,7 @@ public function updateOrCreate($model) /** * @param Entity $model */ - public function createIfNotExists($model) + public function createIfNotExists(Entity $model) { if (!$this->exists($model->getPrimaryKey())) { $this->create($model); @@ -157,15 +141,6 @@ public function getMaxId() } } - /** - * @param Builder $query - * @param int $offset - * @param int $count - * @param int|null $total - * @param array $orders - * @param array $filters - * @return Builder - */ protected function processGridViewQuery(Builder $query, null|int &$total, int $offset = 0, int $count = 0, array $orders = [], array $filters = []): Builder { if ($orders) { diff --git a/src/Models/Resources/Resource.php b/src/Models/Resources/Resource.php index 5232a72..6f378bc 100644 --- a/src/Models/Resources/Resource.php +++ b/src/Models/Resources/Resource.php @@ -7,16 +7,9 @@ abstract class Resource implements IResource { - /** - * @param Entity $entity - * @return array - */ + abstract public function toArray(Entity $entity): array; - /** - * @param Collection $entities - * @return array - */ public function collectionToArray(Collection $entities): array { $entityArray = []; diff --git a/stubs/Repositories/Mysql/mysql.getAllBy.stub b/stubs/Repositories/Mysql/mysql.getAllBy.stub index 6c31d38..b27fcb4 100644 --- a/stubs/Repositories/Mysql/mysql.getAllBy.stub +++ b/stubs/Repositories/Mysql/mysql.getAllBy.stub @@ -1,4 +1,7 @@ + /** + * This action has been created because '{{ FunctionName }}' exists in foreign keys or indexes + */ public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection { ${{ EntityVariableName }} = $this->newQuery() diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub index 68b5556..74dd279 100644 --- a/stubs/Repositories/Mysql/mysql.getOneBy.stub +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -1,4 +1,7 @@ + /** + * This action has been created because '{{ FunctionName }}' exists in foreign keys or indexes + */ public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} { ${{ EntityVariableName }} = $this->newQuery() From cc8cc9a1527ae61e87514c0c877dc18bfc7feb6d Mon Sep 17 00:00:00 2001 From: sama20 Date: Wed, 11 Jan 2023 16:15:16 +0330 Subject: [PATCH 15/86] fix: make all did not work correctly. I fixed it. --- src/Commands/BaseCommand.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index ade9807..1b2e2a6 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -69,7 +69,6 @@ public function checkDelete(string $filenameWithPath, string $entityName, string if (file_exists($filenameWithPath) && $this->option('delete')) { unlink($filenameWithPath); $this->info("$objectName '$entityName' has been deleted."); - exit; } } @@ -97,7 +96,6 @@ public function finalized(string $filenameWithPath, string $entityName, string $ } $this->info("\"$entityName\" has been created."); - exit; } public function checkEmpty(Collection $columns, string $tableName): void From c3674e939524fb79aa3b1427913fb6198742c2d5 Mon Sep 17 00:00:00 2001 From: sama20 Date: Thu, 12 Jan 2023 15:43:46 +0330 Subject: [PATCH 16/86] Get Database From User issue:#12 --- Readme.md | 26 ++++++++++---------- config/repository.php | 2 ++ src/Commands/BaseCommand.php | 2 ++ src/Commands/MakeAll.php | 4 ++- src/Commands/MakeRepository.php | 11 ++++++--- src/Creators/CreatorRedisRepository.php | 2 +- src/Creators/CreatorRepository.php | 10 ++++---- stubs/Repositories/Base/base.construct.stub | 3 +-- stubs/Repositories/Base/base.setter.sql.stub | 2 +- stubs/Repositories/Mysql/mysql.create.stub | 3 ++- stubs/Repositories/Mysql/mysql.getAllBy.stub | 3 --- stubs/Repositories/Mysql/mysql.getOneBy.stub | 3 --- 12 files changed, 37 insertions(+), 34 deletions(-) diff --git a/Readme.md b/Readme.md index bf41aeb..018e3dd 100644 --- a/Readme.md +++ b/Readme.md @@ -7,8 +7,6 @@ composer require nanvaie/database-repository --dev ``` ### Setup Laravel Repository -Before publishing assets, add `REPOSITORY_PHP_VERSION` variable to `.env` and set it to your version of choosing. Supported values are: 8.0, 7.4 (Default is 8.0). - Then run following command in console to publish necessary assets in your project directory. ```bash php artisan vendor:publish vendor:publish --tag=database-repository-config @@ -30,17 +28,18 @@ Note: Make sure to run `composer dump-autoload` after these changes. ## Usage List of artisan commands: -| Command | Inputs | Options | Description | -|----------------------------------------|-------------------------------------|--------------------|-----------------------------------| -| `repository:make-entity` | table_name | -f, -d, -k, -g | Create new Entity | -| `repository:make-enum` | table_name | -f, -d, -g | Create new Enum | -| `repository:make-factory` | table_name | -f, -d, -g | Create new Factory | -| `repository:make-resource` | table_name | -f, -d, -k, -g | Create new Resource | -| `repository:make-interface-repository` | table_name | -f, -d, -k, -g | Create new Repository Interface | -| `repository:make-repository` | table_name | -f, -d, -k, -g | Create new Base Repository | -| `repository:make-mysql-repository` | table_name | -f, -d, -k, -g | Create new MySql Repository class | -| `repository:make-redis-repository` | table_name | -f, -d, -k, -g | Create new Redis Repository class | -| `repository:make-all` | --table_names=table_names(optional) | -a, -f, -d, -k, -g | Run all of the above commands | +| Command | Inputs | Options | Description | +|----------------------------------------|---------------------------------------------------------------------------|--------------------|-----------------------------------| +| `repository:make-entity` | table_name | -f, -d, -k, -g | Create new Entity | +| `repository:make-enum` | table_name | -f, -d, -g | Create new Enum | +| `repository:make-factory` | table_name | -f, -d, -g | Create new Factory | +| `repository:make-resource` | table_name | -f, -d, -k, -g | Create new Resource | +| `repository:make-interface-repository` | table_name | -f, -d, -k, -g | Create new Repository Interface | +| `repository:make-repository` | table_name, selected_db(optional) | -f, -d, -k, -g | Create new Base Repository | +| `repository:make-mysql-repository` | table_name | -f, -d, -k, -g | Create new MySql Repository class | +| `repository:make-redis-repository` | table_name | -f, -d, -k, -g | Create new Redis Repository class | +| `repository:make-all` | --table_names=table_names(optional)
--selected_db=database(optional) | -a, -f, -d, -k, -g | Run all of the above commands | + ### Options Explanation - `-f|--force`: Force commands to override existing files. @@ -49,6 +48,7 @@ List of artisan commands: - `-g|--add-to-git`: Add created files to git repository. - `-a|--all-tables`: Use all existing tables. - `--table_names=`: Add table names, separate names with comma. +- `--selected_db=` : Use between `Mysql`,`Redis`, If it does not send, the value will return from `config/repository.php` Example 1. Create new Entity for a table named 'users'. ```bash diff --git a/config/repository.php b/config/repository.php index cf1dd35..8fb4d5f 100644 --- a/config/repository.php +++ b/config/repository.php @@ -4,6 +4,8 @@ 'php_version' => env('REPOSITORY_PHP_VERSION', '8.0'), + 'default_db' => 'MySql',# Options: ( Redis, MySql ) + 'path' => [ 'namespace' => [ 'entities' => 'App\Models\Entities', diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 1b2e2a6..84f63fe 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -10,6 +10,7 @@ class BaseCommand extends Command { // use CustomMySqlQueries; + public string $selectedDb; public string $tableName; public string $detectForeignKeys; public string $entityName; @@ -36,6 +37,7 @@ class BaseCommand extends Command public function setArguments() { + $this->selectedDb = $this->hasArgument('selected_db') && $this->argument('selected_db') ? $this->argument('selected_db') : config('repository.default_db'); $this->tableName = $this->argument('table_name'); if ($this->hasOption('foreign-keys')) $this->detectForeignKeys = $this->option('foreign-keys'); $this->entityName = Str::singular(ucfirst(Str::camel($this->tableName))); diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 245ab45..1bbcaec 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -16,6 +16,7 @@ class MakeAll extends Command * @var string */ protected $signature = 'repository:make-all + {--selected_db= : Main database} {--table_names= : Table names, separate names with comma} {--k|foreign-keys : Detect foreign keys} {--d|delete : Delete resource} @@ -35,6 +36,7 @@ class MakeAll extends Command */ public function handle() { + $this->selectedDb = $this->hasOption('selected_db') && $this->option('selected_db') ? $this->option('selected_db') : config('repository.default_db'); $force = $this->option('force'); $delete = $this->option('delete'); $detectForeignKeys = $this->option('foreign-keys'); @@ -65,7 +67,7 @@ public function handle() $this->call('repository:make-interface-repository', $arguments); $this->call('repository:make-mysql-repository', $arguments); $this->call('repository:make-redis-repository', $arguments); - $this->call('repository:make-repository', $arguments); + $this->call('repository:make-repository', [...$arguments,'selected_db'=>$this->selectedDb]); } } } diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 861fe53..05e3f46 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -15,7 +15,7 @@ class MakeRepository extends BaseCommand * * @var string */ - protected $signature = 'repository:make-repository {table_name} + protected $signature = 'repository:make-repository {table_name} {selected_db?} {--k|foreign-keys : Detect foreign keys} {--d|delete : Delete resource} {--f|force : Override/Delete existing repository class} @@ -38,9 +38,11 @@ class MakeRepository extends BaseCommand public function handle(): void { $this->setArguments(); +// dd($this->selectedDb); $repositoryName = $this->entityName.'Repository'; - $sqlRepositoryName = 'MySql'.$this->entityName.'Repository'; - $sqlRepositoryVariable = 'mysqlRepository'; +// $sqlRepositoryName = 'MySql'.$this->entityName.'Repository'; + $sqlRepositoryName = ucwords($this->selectedDb).$this->entityName.'Repository'; + $sqlRepositoryVariable = 'repository'; $relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); $filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php'; @@ -64,7 +66,8 @@ public function handle(): void $this->entityNamespace, $repositoryName, $this->interfaceName, - $this->repositoryNamespace + $this->repositoryNamespace, + $this->selectedDb ); $creator = new BaseCreator($RepoCreator); $baseContent = $creator->createClass($filenameWithPath,$this); diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php index 6733666..735ecc3 100644 --- a/src/Creators/CreatorRedisRepository.php +++ b/src/Creators/CreatorRedisRepository.php @@ -26,7 +26,7 @@ public function getClassName(): string } public function getExtendSection(): string { - return "extends RedisRepository"; + return "extends RedisRepository implements IUserRepository"; } public function createAttributs(): array { diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index 24805d6..d527755 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Creators; +use App\Models\Repositories\User\IUserRepository; use Illuminate\Support\Collection; use Nanvaie\DatabaseRepository\CustomMySqlQueries; use Illuminate\Support\Str; @@ -20,7 +21,8 @@ public function __construct( public string $entityNamespace, public string $repositoryName, public string $interfaceName, - public string $repositoryNamespace + public string $repositoryNamespace, + public string $selectedDb ) { } @@ -82,7 +84,7 @@ public function createAttributs(): array { $attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub'); $attributes = []; - $attributes[$this->sqlRepositoryVariable] = $this->writeSqlAttribute($attributeSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName); + $attributes['repository'] = 'private IUserRepository $repository;'; return $attributes; } @@ -133,8 +135,6 @@ public function createFunctions(): array public function getConstruct(string $setterSqlStub, string $constructStub) { - $setters = ''; - $setters = substr_replace($setters,$this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName),-1, 0); - return str_replace("{{ Setters }}", $setters, $constructStub); + return str_replace("{{ Setters }}", $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName), $constructStub); } } diff --git a/stubs/Repositories/Base/base.construct.stub b/stubs/Repositories/Base/base.construct.stub index d755cdf..2f2eb37 100644 --- a/stubs/Repositories/Base/base.construct.stub +++ b/stubs/Repositories/Base/base.construct.stub @@ -1,5 +1,4 @@ public function __construct() { -{{ Setters }} - } +{{ Setters }} } diff --git a/stubs/Repositories/Base/base.setter.sql.stub b/stubs/Repositories/Base/base.setter.sql.stub index 97331ca..bec7819 100644 --- a/stubs/Repositories/Base/base.setter.sql.stub +++ b/stubs/Repositories/Base/base.setter.sql.stub @@ -1 +1 @@ - $this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); \ No newline at end of file + $this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); diff --git a/stubs/Repositories/Mysql/mysql.create.stub b/stubs/Repositories/Mysql/mysql.create.stub index a2431aa..e83ac43 100644 --- a/stubs/Repositories/Mysql/mysql.create.stub +++ b/stubs/Repositories/Mysql/mysql.create.stub @@ -1,4 +1,5 @@ -public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} + + public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} { {{ SetterFunctions }} diff --git a/stubs/Repositories/Mysql/mysql.getAllBy.stub b/stubs/Repositories/Mysql/mysql.getAllBy.stub index b27fcb4..6c31d38 100644 --- a/stubs/Repositories/Mysql/mysql.getAllBy.stub +++ b/stubs/Repositories/Mysql/mysql.getAllBy.stub @@ -1,7 +1,4 @@ - /** - * This action has been created because '{{ FunctionName }}' exists in foreign keys or indexes - */ public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection { ${{ EntityVariableName }} = $this->newQuery() diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub index 74dd279..68b5556 100644 --- a/stubs/Repositories/Mysql/mysql.getOneBy.stub +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -1,7 +1,4 @@ - /** - * This action has been created because '{{ FunctionName }}' exists in foreign keys or indexes - */ public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} { ${{ EntityVariableName }} = $this->newQuery() From c2c242094ab7c7870a33f6da723b3e7693a9f39d Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Tue, 17 Jan 2023 07:01:58 +0330 Subject: [PATCH 17/86] remove redundant vendor:publish --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 018e3dd..54fb54d 100644 --- a/Readme.md +++ b/Readme.md @@ -9,7 +9,7 @@ composer require nanvaie/database-repository --dev ### Setup Laravel Repository Then run following command in console to publish necessary assets in your project directory. ```bash -php artisan vendor:publish vendor:publish --tag=database-repository-config +php artisan vendor:publish --tag=database-repository-config ``` ### Setup Lumen Repository From baca9319eb7204c2e9185ac494033fedb1a6d558 Mon Sep 17 00:00:00 2001 From: Javad Date: Sun, 29 Jan 2023 16:44:48 +0330 Subject: [PATCH 18/86] fix: - add POINT datatype as string - remove laravel/helpers package --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 54fb54d..0e62195 100644 --- a/Readme.md +++ b/Readme.md @@ -3,7 +3,7 @@ ## Installation Use following command to add this package to composer development requirement. ```bash -composer require nanvaie/database-repository --dev +composer require nanvaie/database-repository --dev ``` ### Setup Laravel Repository From 9489935fd3994a037adf29cef29f46cb639d899f Mon Sep 17 00:00:00 2001 From: sama20 Date: Sun, 29 Jan 2023 17:15:26 +0330 Subject: [PATCH 19/86] fix: a small bug in interface name --- src/Creators/CreatorRepository.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index d527755..448cbd8 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -84,7 +84,7 @@ public function createAttributs(): array { $attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub'); $attributes = []; - $attributes['repository'] = 'private IUserRepository $repository;'; + $attributes['repository'] = 'private '.$this->interfaceName.' $repository;'; return $attributes; } From 9386a39ef9feaaee2a34a58b40de238c2a15a9fb Mon Sep 17 00:00:00 2001 From: Mohammad-Reza Sharifi Date: Wed, 26 Apr 2023 12:53:11 +0430 Subject: [PATCH 20/86] feat(Composer): Add Support for Laravel 10 --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 2571f73..0f060c3 100644 --- a/composer.json +++ b/composer.json @@ -13,10 +13,10 @@ "php": "^8.0", "ext-pdo": "*", "ext-json": "*", - "illuminate/console": "^6.0|^7.0|^8.0|^9.0", - "illuminate/support": "^6.0|^7.0|^8.0|^9.0", - "illuminate/cache": "^6.0|^7.0|^8.0|^9.0", - "illuminate/database": "^6.0|^7.0|^8.0|^9.0" + "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0", + "illuminate/cache": "^6.0|^7.0|^8.0|^9.0|^10.0", + "illuminate/database": "^6.0|^7.0|^8.0|^9.0|^10.0" }, "autoload": { "psr-4": { From dcbb4443ddfd75c84ecb830874ce0eddf6ca5452 Mon Sep 17 00:00:00 2001 From: Mohsen Etemady Date: Sun, 28 May 2023 11:49:20 +0330 Subject: [PATCH 21/86] ref: Removing Unused Code and Fixing Code Indentation - DatabaseRepositoryServiceProvider: Correcting the mistake of using the container service incorrectly for registering commands --- src/DatabaseRepositoryServiceProvider.php | 73 +++++++---------------- 1 file changed, 20 insertions(+), 53 deletions(-) diff --git a/src/DatabaseRepositoryServiceProvider.php b/src/DatabaseRepositoryServiceProvider.php index 7154ccc..5417bd3 100644 --- a/src/DatabaseRepositoryServiceProvider.php +++ b/src/DatabaseRepositoryServiceProvider.php @@ -40,12 +40,13 @@ public function register(): void public function offerPublishing(): void { - if ($this->app->runningInConsole()) { - $this->publishes([ - __DIR__ . '/../config/repository.php' => $this->app->configPath('repository.php'), - ], 'database-repository-config'); - + if ($this->app->runningInConsole() === false) { + return; } + + $this->publishes([ + __DIR__ . '/../config/repository.php' => $this->app->configPath('repository.php'), + ], 'database-repository-config'); } /** @@ -53,55 +54,21 @@ public function offerPublishing(): void */ private function registerCommands(): void { - if ($this->app->runningInConsole()) { - $this->app->singleton('repository.make-all-repository', function () { - return new MakeAll(); - }); - - $this->app->singleton('repository.make-entity', function () { - return new MakeEntity(); - }); - - $this->app->singleton('repository.make-enum', function () { - return new MakeEnum(); - }); - - $this->app->singleton('repository.make-factory', function () { - return new MakeFactory(); - }); - - $this->app->singleton('repository.make-interface-repository', function () { - return new MakeInterfaceRepository(); - }); - - $this->app->singleton('repository.make-mysql-repository', function () { - return new MakeMySqlRepository(); - }); - - $this->app->singleton('repository.make-redis-repository', function () { - return new MakeRedisRepository(); - }); - - $this->app->singleton('repository.make-repository', function () { - return new MakeRepository(); - }); - - $this->app->singleton('repository.make-resource', function () { - return new MakeResource(); - }); - - $this->commands([ - MakeAll::class, - MakeEntity::class, - MakeEnum::class, - MakeFactory::class, - MakeInterfaceRepository::class, - MakeMySqlRepository::class, - MakeRedisRepository::class, - MakeRepository::class, - MakeResource::class - ]); + if ($this->app->runningInConsole() === false) { + return; } + + $this->commands([ + MakeAll::class, + MakeEntity::class, + MakeEnum::class, + MakeFactory::class, + MakeInterfaceRepository::class, + MakeMySqlRepository::class, + MakeRedisRepository::class, + MakeRepository::class, + MakeResource::class + ]); } } From 7480c8ad35b2ccc76e9dac0737494f7c0b6b394d Mon Sep 17 00:00:00 2001 From: mohamamd Date: Thu, 1 Jun 2023 15:10:13 +0330 Subject: [PATCH 22/86] add redis --- src/Commands/BaseCommand.php | 29 ++++- src/Commands/MakeRedisRepository.php | 13 ++- src/Commands/MakeRepository.php | 17 +-- src/Commands/MakeResource.php | 1 + src/Creators/CreatorRedisRepository.php | 24 +++- src/Creators/CreatorRepository.php | 85 ++++++++++++-- src/DatabaseRepositoryServiceProvider.php | 76 ++++++++---- src/Models/Repositories/RedisRepository.php | 108 +++++++++++++++++- .../Repositories/Base/base.attribute.sql.stub | 1 + .../Base/base.construct_redis.stub | 6 + stubs/Repositories/Base/base.function.stub | 1 + stubs/Repositories/Base/base.setter.sql.stub | 3 +- stubs/Repositories/Redis/base.clear.stub | 1 + ...se.clearable_temporary_cache_strategy.stub | 5 + .../create/base.query_cache_strategy.stub | 1 + .../base.single_key_cache_strategy.stub | 1 + .../create/base.temporary_cache_strategy.stub | 0 ...se.clearable_temporary_cache_strategy.stub | 11 ++ .../getAllBy/base.query_cache_strategy.stub | 17 +++ .../base.single_key_cache_strategy.stub | 6 + .../base.temporary_cache_strategy.stub | 11 ++ ...se.clearable_temporary_cache_strategy.stub | 10 ++ .../getOneBy/base.query_cache_strategy.stub | 10 ++ .../base.single_key_cache_strategy.stub | 6 + .../base.temporary_cache_strategy.stub | 11 ++ ...se.clearable_temporary_cache_strategy.stub | 5 + .../update/base.query_cache_strategy.stub | 1 + .../base.single_key_cache_strategy.stub | 1 + .../update/base.temporary_cache_strategy.stub | 0 29 files changed, 407 insertions(+), 54 deletions(-) create mode 100644 stubs/Repositories/Base/base.construct_redis.stub create mode 100644 stubs/Repositories/Redis/base.clear.stub create mode 100644 stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/create/base.query_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/create/base.temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/update/base.query_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub create mode 100644 stubs/Repositories/Redis/update/base.temporary_cache_strategy.stub diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 84f63fe..9604927 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -2,6 +2,7 @@ namespace Nanvaie\DatabaseRepository\Commands; +use Illuminate\Container\Container; use Illuminate\Support\Collection; use Illuminate\Console\Command; use Nanvaie\DatabaseRepository\CustomMySqlQueries; @@ -35,6 +36,8 @@ class BaseCommand extends Command public string $relativeMysqlRepositoryPath; public string $mysqlRepositoryStubsPath; + public string $strategyName; + public function setArguments() { $this->selectedDb = $this->hasArgument('selected_db') && $this->argument('selected_db') ? $this->argument('selected_db') : config('repository.default_db'); @@ -63,7 +66,9 @@ public function setArguments() $this->mysqlRepositoryName = 'MySql' . $this->entityName . 'Repository'; $this->relativeMysqlRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $this->mysqlRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.mysql'); - + if ($this->hasArgument('strategy')) { + $this->strategyName = $this->argument('strategy'); + } } public function checkDelete(string $filenameWithPath, string $entityName, string $objectName): void @@ -99,7 +104,6 @@ public function finalized(string $filenameWithPath, string $entityName, string $ $this->info("\"$entityName\" has been created."); } - public function checkEmpty(Collection $columns, string $tableName): void { if ($columns->isEmpty()) { @@ -107,7 +111,6 @@ public function checkEmpty(Collection $columns, string $tableName): void exit; } } - public function setChoice($choice): void { \config(['replacement.choice' => $choice]); @@ -117,4 +120,24 @@ public function getChoice(): null|string { return \config('replacement.choice'); } + + public function checkStrategyName() + { + $strategyNames = array("ClearableTemporaryCacheStrategy", "QueryCacheStrategy", "SingleKeyCacheStrategy", "TemporaryCacheStrategy"); + if (!in_array($this->argument('strategy'), $strategyNames)) { + $this->alert("This pattern strategy does not exist !!! "); + exit; + } + } + public function checkDatabasesExist() + { + $entityName=Str::singular(ucfirst(Str::camel($this->argument('table_name')))); + $mysql ="App\Models\Repositories". "\\". $entityName. "\\"."MySql".$entityName."Repository.php"; + $redis ="App\Models\Repositories". "\\". $entityName. "\\"."Redis".$entityName."Repository.php"; + if(!file_exists($mysql) && !file_exists($redis)) { + $this->alert("First create the class databases!!!"); + exit; + } + } + } diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index d4bb78f..1bd030b 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -15,7 +15,7 @@ class MakeRedisRepository extends BaseCommand * * @var string */ - protected $signature = 'repository:make-redis-repository {table_name} + protected $signature = 'repository:make-redis-repository {table_name} {strategy} {--k|foreign-keys : Detect foreign keys} {--d|delete : Delete resource} {--f|force : Override/Delete existing redis repository} @@ -35,9 +35,12 @@ class MakeRedisRepository extends BaseCommand * * @return int */ - public function handle(): void + public function handle() { + + $this->checkStrategyName(); $this->setArguments(); + $redisRepositoryName = "Redis$this->entityName"."Repository"; $redisRepositoryNamespace = config('repository.path.namespace.repositories'); $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; @@ -46,7 +49,6 @@ public function handle(): void $this->checkDelete($filenameWithPath,$redisRepositoryName,"Redis Repository"); $this->checkDirectory($relativeRedisRepositoryPath); $this->checkClassExist($this->repositoryNamespace,$redisRepositoryName,"Redis Repository"); - $columns = $this->getAllColumnsInTable($this->tableName); $this->checkEmpty($columns,$this->tableName); @@ -54,11 +56,10 @@ public function handle(): void $foreignKeys = $this->extractForeignKeys($this->tableName); } - $mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName,$redisRepositoryNamespace, $this->entityName); + $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); + $mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName,$redisRepositoryNamespace, $this->entityName,$this->strategyName,$repositoryStubsPath); $creator = new BaseCreator($mysqlRepoCreator); $baseContent = $creator->createClass($filenameWithPath,$this); - $this->finalized($filenameWithPath, $redisRepositoryName, $baseContent); - } } diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 05e3f46..7d49351 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -15,7 +15,7 @@ class MakeRepository extends BaseCommand * * @var string */ - protected $signature = 'repository:make-repository {table_name} {selected_db?} + protected $signature = 'repository:make-repository {table_name} {strategy} {selected_db?} {--k|foreign-keys : Detect foreign keys} {--d|delete : Delete resource} {--f|force : Override/Delete existing repository class} @@ -37,23 +37,24 @@ class MakeRepository extends BaseCommand */ public function handle(): void { + $this->checkDatabasesExist(); + $this->checkStrategyName(); + $this->setArguments(); -// dd($this->selectedDb); $repositoryName = $this->entityName.'Repository'; // $sqlRepositoryName = 'MySql'.$this->entityName.'Repository'; $sqlRepositoryName = ucwords($this->selectedDb).$this->entityName.'Repository'; $sqlRepositoryVariable = 'repository'; + $redisRepositoryVariable ='redisRepository'; + $redisRepositoryName = 'Redis'.$this->entityName.'Repository'; $relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); $filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php'; - $this->checkDelete($filenameWithPath,$repositoryName,"Repository"); $this->checkDirectory($relativeRepositoryPath); $this->checkClassExist($this->repositoryNamespace,$repositoryName,"Repository"); - $columns = $this->getAllColumnsInTable($this->tableName); $this->checkEmpty($columns,$this->tableName); - $RepoCreator = new CreatorRepository( $columns, $sqlRepositoryVariable, @@ -67,11 +68,13 @@ public function handle(): void $repositoryName, $this->interfaceName, $this->repositoryNamespace, - $this->selectedDb + $this->selectedDb, + $redisRepositoryVariable, + $redisRepositoryName, + $this->strategyName ); $creator = new BaseCreator($RepoCreator); $baseContent = $creator->createClass($filenameWithPath,$this); - $this->finalized($filenameWithPath, $repositoryName, $baseContent); } } diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index 8aaf2de..9055be6 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -65,4 +65,5 @@ public function handle(): void $this->finalized($filenameWithPath,$resourceName,$baseContent); } + } diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php index 735ecc3..85c80c5 100644 --- a/src/Creators/CreatorRedisRepository.php +++ b/src/Creators/CreatorRedisRepository.php @@ -2,12 +2,17 @@ namespace Nanvaie\DatabaseRepository\Creators; +use Illuminate\Support\Str; +use Nanvaie\DatabaseRepository\CustomMySqlQueries; + class CreatorRedisRepository implements IClassCreator { public function __construct( public string $redisRepositoryName, public string $redisRepositoryNamespace, - public string $entityName + public string $entityName, + public string $strategyName, + public string $repositoryStubsPath, ) { @@ -18,7 +23,10 @@ public function getNameSpace(): string } public function createUses(): array { - return ["use Nanvaie\DatabaseRepository\Models\Repositories\RedisRepository;"]; + return [ + "use Nanvaie\DatabaseRepository\Models\Repositories\RedisRepository;", + "use App\Models\Repositories\Redis"."\\".$this->strategyName.";" + ]; } public function getClassName(): string { @@ -26,7 +34,7 @@ public function getClassName(): string } public function getExtendSection(): string { - return "extends RedisRepository implements IUserRepository"; + return "extends RedisRepository"; } public function createAttributs(): array { @@ -34,6 +42,14 @@ public function createAttributs(): array } public function createFunctions(): array { - return []; + $constructStub = file_get_contents($this->repositoryStubsPath . 'construct_redis.stub'); + $functions = []; + $functions['__construct'] = $this->getConstructRedis($constructStub); + return $functions ; } + public function getConstructRedis(string $constructStub) + { + return str_replace("{{Strategy}}",$this->strategyName,$constructStub); + } + } diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index 448cbd8..f1c5af7 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -5,8 +5,11 @@ use App\Models\Repositories\User\IUserRepository; use Illuminate\Support\Collection; use Nanvaie\DatabaseRepository\CustomMySqlQueries; +use Nanvaie\DatabaseRepository\Commands; +use Nanvaie\DatabaseRepository\Commands\MakeRedisRepository; use Illuminate\Support\Str; + class CreatorRepository implements IClassCreator { public function __construct( @@ -22,7 +25,10 @@ public function __construct( public string $repositoryName, public string $interfaceName, public string $repositoryNamespace, - public string $selectedDb + public string $selectedDb, + public string $redisRepositoryVariable, + public string $redisRepositoryName, + public string $strategyName ) { } @@ -35,27 +41,41 @@ private function writeFunction(string $functionStub, string $functionName, strin $functionReturnType = 'null|{{ EntityName }}'; $functionName .= ucfirst(Str::camel($columnName)); $columnName = Str::camel($columnName); + $redisCashFunction = $this->getRedisCashFunctionGetOneBy($this->strategyName); + + } elseif ($functionName === 'getAllBy') { $functionReturnType = 'Collection'; $functionName .= ucfirst(Str::plural(Str::camel($columnName))); $columnName = Str::plural(Str::camel($columnName)); + $redisCashFunction = $this->getRedisCashFunctionGetAllBy($this->strategyName); + + } elseif ($functionName === 'create') { $functionReturnType = $attributeType; + $redisCashFunction = $this->getRedisCashFunctionCreate($this->strategyName); + } elseif (in_array($functionName, ['update', 'remove', 'restore'])) { $functionReturnType = 'int'; - } + $redisCashFunction = $this->getRedisCashFunctionUpdate($this->strategyName); - return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}'], - [$functionName, $attributeType, Str::camel($columnName), $functionReturnType], + } + return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}','{{redisFunction}}'], + [$functionName, $attributeType, Str::camel($columnName), $functionReturnType,$redisCashFunction], $functionStub); } - private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable, string $sqlRepositoryName): string { - return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'], + return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'], [$sqlRepositoryVariable, $sqlRepositoryName], $attributeStub); } + public function writeRedisAttribute(string $attributeStub,string $redisRepositoryVariable,string $redisRepositoryName):string + { + return str_replace(['{{ RedisRepositoryVariable }}', '{{ RedisRepositoryName }}'], + [$redisRepositoryVariable, $redisRepositoryName], + $attributeStub); + } public function getNameSpace(): string { @@ -85,6 +105,7 @@ public function createAttributs(): array $attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub'); $attributes = []; $attributes['repository'] = 'private '.$this->interfaceName.' $repository;'; + $attributes['redisRepository'] = 'private '.$this->redisRepositoryName.' $redisRepository;'; return $attributes; } @@ -93,9 +114,9 @@ public function createFunctions(): array $constructStub = file_get_contents($this->repositoryStubsPath . 'construct.stub'); $functionStub = file_get_contents($this->repositoryStubsPath . 'function.stub'); $setterSqlStub = file_get_contents($this->repositoryStubsPath . 'setter.sql.stub'); - $functions = []; $functions['__construct'] = $this->getConstruct($setterSqlStub, $constructStub); + $functions['__construct'] = $this->getConstructRedis($setterSqlStub, $constructStub); $functions['getOneById'] = $this->writeFunction($functionStub, 'getOneBy', 'id', 'int'); $functions['getAllByIds'] = $this->writeFunction($functionStub, 'getAllBy', 'id', 'array'); $indexes = $this->extractIndexes($this->tableName); @@ -105,7 +126,6 @@ public function createFunctions(): array $fun_name = ucfirst(Str::camel($index->COLUMN_NAME)); $functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $index->COLUMN_NAME, 'int'); } - if ($this->detectForeignKeys) { $foreignKeys = $this->extractForeignKeys($this->tableName); @@ -116,14 +136,12 @@ public function createFunctions(): array $functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $_foreignKey->COLUMN_NAME, 'array'); } } - $functions['create'] = $this->writeFunction($functionStub, 'create', $this->entityVariableName, $this->entityName); $functions['update'] = $this->writeFunction($functionStub, 'update', $this->entityVariableName, $this->entityName); if (in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true)) { $functions['remove'] = $this->writeFunction($functionStub, 'remove', $this->entityVariableName, $this->entityName); $functions['restore'] = $this->writeFunction($functionStub, 'restore', $this->entityVariableName, $this->entityName); } - foreach ($functions as &$func) { $func = str_replace(["{{ SqlRepositoryVariable }}", '{{ SqlRepositoryName }}', '{{ EntityName }}'], [$this->sqlRepositoryVariable, $this->sqlRepositoryName, $this->entityName], @@ -132,9 +150,52 @@ public function createFunctions(): array } return $functions; } - public function getConstruct(string $setterSqlStub, string $constructStub) { - return str_replace("{{ Setters }}", $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName), $constructStub); + return str_replace("{{ Setters }}", $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName,$this->redisRepositoryVariable,$this->redisRepositoryName), $constructStub); + } + public function getConstructRedis(string $setterSqlStub, string $constructStub) + { + return str_replace("{{ Setters }}", $this->writeRedisAttribute($setterSqlStub,$this->redisRepositoryVariable,$this->redisRepositoryName), $constructStub); + } + private function getRedisCashFunctionGetOneBy($strategyName) + { + $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/getOneBy/base.'; + return match ($strategyName) { + 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), + 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), + 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + }; + } + private function getRedisCashFunctionGetAllBy($strategyName) + { + $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/getAllBy/base.'; + return match ($strategyName) { + 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), + 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), + 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + }; + } + private function getRedisCashFunctionCreate($strategyName) + { + $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/create/base.'; + return match ($strategyName) { + 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), + 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), + 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + }; + } + private function getRedisCashFunctionUpdate($strategyName) + { + $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/update/base.'; + return match ($strategyName) { + 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), + 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), + 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + }; } } diff --git a/src/DatabaseRepositoryServiceProvider.php b/src/DatabaseRepositoryServiceProvider.php index 5417bd3..374c900 100644 --- a/src/DatabaseRepositoryServiceProvider.php +++ b/src/DatabaseRepositoryServiceProvider.php @@ -11,6 +11,7 @@ use Nanvaie\DatabaseRepository\Commands\MakeRedisRepository; use Nanvaie\DatabaseRepository\Commands\MakeRepository; use Nanvaie\DatabaseRepository\Commands\MakeResource; +use Nanvaie\DatabaseRepository\Commands\MakeRedis; use Illuminate\Support\ServiceProvider; use Laravel\Lumen\Application as LumenApplication; use Illuminate\Foundation\Application as LaravelApplication; @@ -40,13 +41,12 @@ public function register(): void public function offerPublishing(): void { - if ($this->app->runningInConsole() === false) { - return; - } + if ($this->app->runningInConsole()) { + $this->publishes([ + __DIR__ . '/../config/repository.php' => $this->app->configPath('repository.php'), + ], 'database-repository-config'); - $this->publishes([ - __DIR__ . '/../config/repository.php' => $this->app->configPath('repository.php'), - ], 'database-repository-config'); + } } /** @@ -54,21 +54,57 @@ public function offerPublishing(): void */ private function registerCommands(): void { - if ($this->app->runningInConsole() === false) { - return; - } + if ($this->app->runningInConsole()) { + $this->app->singleton('repository.make-all-repository', function () { + return new MakeAll(); + }); + + $this->app->singleton('repository.make-entity', function () { + return new MakeEntity(); + }); + + $this->app->singleton('repository.make-enum', function () { + return new MakeEnum(); + }); + + $this->app->singleton('repository.make-factory', function () { + return new MakeFactory(); + }); + + $this->app->singleton('repository.make-interface-repository', function () { + return new MakeInterfaceRepository(); + }); - $this->commands([ - MakeAll::class, - MakeEntity::class, - MakeEnum::class, - MakeFactory::class, - MakeInterfaceRepository::class, - MakeMySqlRepository::class, - MakeRedisRepository::class, - MakeRepository::class, - MakeResource::class - ]); + $this->app->singleton('repository.make-mysql-repository', function () { + return new MakeMySqlRepository(); + }); + + $this->app->singleton('repository.make-redis-repository', function () { + return new MakeRedisRepository(); + }); + + $this->app->singleton('repository.make-repository', function () { + return new MakeRepository(); + }); + + $this->app->singleton('repository.make-resource', function () { + return new MakeResource(); + }); + + $this->commands([ + MakeAll::class, + MakeEntity::class, + MakeEnum::class, + MakeFactory::class, + MakeInterfaceRepository::class, + MakeMySqlRepository::class, + MakeRedisRepository::class, + MakeRepository::class, + MakeResource::class, + + + ]); + } } } diff --git a/src/Models/Repositories/RedisRepository.php b/src/Models/Repositories/RedisRepository.php index 1b73277..6398d4b 100644 --- a/src/Models/Repositories/RedisRepository.php +++ b/src/Models/Repositories/RedisRepository.php @@ -12,9 +12,115 @@ public function __construct() { $this->cache = app('cache'); } - protected function getCache(): CacheManager { return $this->cache; } + /** + * @param Collection $entities + * @param Filter[]|Collection $filters + * @return Collection + */ + protected function processFilterWithCollection($entities, $filters) + { + foreach ($filters as $filter) { + $columnName = camel_case($filter->getColumnName()); + $value = $filter->getValue(); + + switch ($filter->getOperand()) { + case 'IsEqualTo': + $entities = $entities->where($columnName, '=', $value); + break; + case 'IsEqualToOrNull': + $entities = $entities->filter(function ($entity, $key) use ($columnName, $value) { + return ($entity->$columnName == $value || empty($entity->$columnName)); + }); + break; + case 'IsNull': + $entities = $entities->whereNull($columnName); + break; + case 'IsNotEqualTo': + $entities = $entities->where($columnName, '<>', $value); + break; + case 'IsNotNull': + $entities = $entities->whereNotNull($columnName); + break; + case 'StartWith': + $entities = $entities->filter(function ($entity) use ($columnName, $value) { + return false !== Str::startsWith($entity->$columnName, $value); + }); + break; + case 'DoesNotContains': + $entities = $entities->filter(function ($entity) use ($columnName, $value) { + return false === Str::contains($entity->$columnName, $value); + }); + break; + case 'Contains': + $entities = $entities->filter(function ($entity) use ($columnName, $value) { + return false !== Str::contains($entity->$columnName, $value); + }); + break; + case 'EndsWith': + $entities = $entities->filter(function ($entity) use ($columnName, $value) { + return false !== Str::endsWith($entity->$columnName, $value); + }); + break; + case 'In': + $entities = $entities->whereIn($columnName, $value); + break; + case 'NotIn': + $entities = $entities->whereNotIn($columnName, $value); + break; + case 'Between': + $entities = $entities->whereBetween($columnName, $value); + break; + case 'IsGreaterThanOrEqualTo': + $entities = $entities->where($columnName, '>=', $value); + break; + case 'IsGreaterThanOrNull': + $entities = $entities->filter(function ($entity) use ($columnName, $value) { + return ($entity->$columnName > $value || empty($entity->$columnName)); + }); + break; + case 'IsGreaterThan': + $entities = $entities->where($columnName, '>', $value); + break; + case 'IsLessThanOrEqualTo': + $entities = $entities->where($columnName, '<=', $value); + break; + case 'IsLessThan': + $entities = $entities->where($columnName, '<', $value); + break; + case 'IsAfterThanOrEqualTo': + $entities = $entities->where($columnName, '>=', $value); + break; + case 'IsAfterThan': + $entities = $entities->where($columnName, '>', $value); + break; + case 'IsBeforeThanOrEqualTo': + $entities = $entities->where($columnName, '<=', $value); + break; + case 'IsBeforeThan': + $entities = $entities->where($columnName, '<', $value); + break; + } + } + + return $entities; + } + + /** + * @param Collection $entities + * @param Order[]|Collection $orders + * @return Collection + */ + protected function processOrderWithCollection($entities, $orders) + { + $sortBy = []; + foreach ($orders as $order) { + $sortBy[$order->getColumnName()] = $order->getValue(); + } + + return $entities->sortBy($sortBy); + } } diff --git a/stubs/Repositories/Base/base.attribute.sql.stub b/stubs/Repositories/Base/base.attribute.sql.stub index c8af2c7..2ef4512 100644 --- a/stubs/Repositories/Base/base.attribute.sql.stub +++ b/stubs/Repositories/Base/base.attribute.sql.stub @@ -1 +1,2 @@ private {{ SqlRepositoryName }} ${{ SqlRepositoryVariable }}; +private {{ RedisRepositoryVariable }} ${{ RedisRepositoryName }}; diff --git a/stubs/Repositories/Base/base.construct_redis.stub b/stubs/Repositories/Base/base.construct_redis.stub new file mode 100644 index 0000000..c028e29 --- /dev/null +++ b/stubs/Repositories/Base/base.construct_redis.stub @@ -0,0 +1,6 @@ + use {{Strategy}}; + public function __construct() + { + $this->cacheTag = ''; + parent::__construct(); + } diff --git a/stubs/Repositories/Base/base.function.stub b/stubs/Repositories/Base/base.function.stub index 4cdbc40..6af2b85 100644 --- a/stubs/Repositories/Base/base.function.stub +++ b/stubs/Repositories/Base/base.function.stub @@ -1,5 +1,6 @@ public function {{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): {{ FunctionReturnType }} { + {{redisFunction}} return $this->{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }}); } diff --git a/stubs/Repositories/Base/base.setter.sql.stub b/stubs/Repositories/Base/base.setter.sql.stub index bec7819..6cc7e72 100644 --- a/stubs/Repositories/Base/base.setter.sql.stub +++ b/stubs/Repositories/Base/base.setter.sql.stub @@ -1 +1,2 @@ - $this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); + $this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); + $this->{{ RedisRepositoryVariable }} = new {{ RedisRepositoryName }}(); diff --git a/stubs/Repositories/Redis/base.clear.stub b/stubs/Repositories/Redis/base.clear.stub new file mode 100644 index 0000000..d956e7e --- /dev/null +++ b/stubs/Repositories/Redis/base.clear.stub @@ -0,0 +1 @@ + $this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub new file mode 100644 index 0000000..b2beec7 --- /dev/null +++ b/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,5 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'create', + 'id' => $id, +]); + $this->redisRepository->clear($cacheKey); diff --git a/stubs/Repositories/Redis/create/base.query_cache_strategy.stub b/stubs/Repositories/Redis/create/base.query_cache_strategy.stub new file mode 100644 index 0000000..597a987 --- /dev/null +++ b/stubs/Repositories/Redis/create/base.query_cache_strategy.stub @@ -0,0 +1 @@ + $this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub new file mode 100644 index 0000000..4f8eaf4 --- /dev/null +++ b/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub @@ -0,0 +1 @@ + $this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/create/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/create/base.temporary_cache_strategy.stub new file mode 100644 index 0000000..e69de29 diff --git a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub new file mode 100644 index 0000000..757f7d2 --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneByIds', + 'id' => $ids, +]); + + $data= $this->redisRepository->get($cacheKey); + if (is_null($data)) { + $data = $this->repository + ->getOneByIds($ids); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } diff --git a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub new file mode 100644 index 0000000..6b3c37e --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -0,0 +1,17 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneByIds', + 'id' => $ids, + ]); + + $entity = $this->redisRepository->get($cacheKey); + + + + + if (is_null($entity)) { + $entity = $this->repository->getOneByIds($ids); + $this->redisRepository->put($cacheKey, $entity); + } + + + diff --git a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub new file mode 100644 index 0000000..5b68f71 --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -0,0 +1,6 @@ + + $entity = $this->redisRepository->get(); + if (is_null($entity)) { + $entity = $this->repository->getOneByIds($id); + $this->redisRepository->put($entity); + } diff --git a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub new file mode 100644 index 0000000..757f7d2 --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneByIds', + 'id' => $ids, +]); + + $data= $this->redisRepository->get($cacheKey); + if (is_null($data)) { + $data = $this->repository + ->getOneByIds($ids); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } diff --git a/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub new file mode 100644 index 0000000..aa5911b --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,10 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneById', + 'id' => $id, +]); + $data= $this->redisRepository->get($cacheKey); + if (is_null($data)) { + $data = $this->repository + ->getOneById($id); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } \ No newline at end of file diff --git a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub new file mode 100644 index 0000000..b28ebce --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub @@ -0,0 +1,10 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneById', + 'id' => $id, + ]); + + $entity = $this->redisRepository->get($cacheKey); + if (is_null($entity)) { + $entity = $this->repository->getOneById($id); + $this->redisRepository->put($cacheKey, $entity); + } diff --git a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub new file mode 100644 index 0000000..b1dfa07 --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub @@ -0,0 +1,6 @@ + + $entity = $this->redisRepository->get(); + if (is_null($entity)) { + $entity = $this->repository->getOneById($id); + $this->redisRepository->put($entity); + } diff --git a/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub new file mode 100644 index 0000000..4a9789c --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneById', + 'id' => $id, +]); + + $data= $this->redisRepository->get($cacheKey); + if (is_null($data)) { + $data = $this->repository + ->getOneById($id); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } diff --git a/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub new file mode 100644 index 0000000..c22ce76 --- /dev/null +++ b/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,5 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'update', + 'id' => $id, +]); + $this->redisRepository->clear($cacheKey); diff --git a/stubs/Repositories/Redis/update/base.query_cache_strategy.stub b/stubs/Repositories/Redis/update/base.query_cache_strategy.stub new file mode 100644 index 0000000..597a987 --- /dev/null +++ b/stubs/Repositories/Redis/update/base.query_cache_strategy.stub @@ -0,0 +1 @@ + $this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub new file mode 100644 index 0000000..4f8eaf4 --- /dev/null +++ b/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub @@ -0,0 +1 @@ + $this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/update/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/update/base.temporary_cache_strategy.stub new file mode 100644 index 0000000..e69de29 From e5a33e4156649ddd322a416c0a4fa24f4ce04646 Mon Sep 17 00:00:00 2001 From: mohamamd Date: Sat, 10 Jun 2023 14:55:56 +0330 Subject: [PATCH 23/86] modify RepositoryRedis --- src/Commands/BaseCommand.php | 12 ++++++++---- src/Commands/MakeAll.php | 16 ++++++++++++---- src/Commands/MakeRedisRepository.php | 1 - 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 9604927..7592331 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -104,6 +104,7 @@ public function finalized(string $filenameWithPath, string $entityName, string $ $this->info("\"$entityName\" has been created."); } + public function checkEmpty(Collection $columns, string $tableName): void { if ($columns->isEmpty()) { @@ -111,6 +112,7 @@ public function checkEmpty(Collection $columns, string $tableName): void exit; } } + public function setChoice($choice): void { \config(['replacement.choice' => $choice]); @@ -129,12 +131,14 @@ public function checkStrategyName() exit; } } + public function checkDatabasesExist() { - $entityName=Str::singular(ucfirst(Str::camel($this->argument('table_name')))); - $mysql ="App\Models\Repositories". "\\". $entityName. "\\"."MySql".$entityName."Repository.php"; - $redis ="App\Models\Repositories". "\\". $entityName. "\\"."Redis".$entityName."Repository.php"; - if(!file_exists($mysql) && !file_exists($redis)) { + + $entityName = Str::singular(ucfirst(Str::camel($this->argument('table_name')))); + $mysql = config('repository.path.namespace.repositories') . "\\" . $entityName . "\\" . "MySql" . $entityName . "Repository.php"; + $redis = config('repository.path.namespace.repositories') . "\\" . $entityName . "\\" . "Redis" . $entityName . "Repository.php"; + if (!(file_exists($mysql) && file_exists($redis))) { $this->alert("First create the class databases!!!"); exit; } diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 1bbcaec..69bfdf3 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -18,6 +18,7 @@ class MakeAll extends Command protected $signature = 'repository:make-all {--selected_db= : Main database} {--table_names= : Table names, separate names with comma} + {--strategy_name= : strategy name} {--k|foreign-keys : Detect foreign keys} {--d|delete : Delete resource} {--f|force : Override/Delete existing classes} @@ -36,12 +37,20 @@ class MakeAll extends Command */ public function handle() { + + + $strategyNames = array("ClearableTemporaryCacheStrategy", "QueryCacheStrategy", "SingleKeyCacheStrategy", "TemporaryCacheStrategy"); + if (!in_array($this->option('strategy_name'), $strategyNames)) { + $this->alert("This pattern strategy does not exist !!! "); + exit; + } + $this->selectedDb = $this->hasOption('selected_db') && $this->option('selected_db') ? $this->option('selected_db') : config('repository.default_db'); $force = $this->option('force'); $delete = $this->option('delete'); $detectForeignKeys = $this->option('foreign-keys'); $addToGit = $this->option('add-to-git'); - + $strategy=$this->option('strategy_name'); if ($this->option('all-tables')) { $tableNames = $this->getAllTableNames()->pluck('TABLE_NAME'); } else if ($this->option('table_names')) { @@ -59,15 +68,14 @@ public function handle() '--force' => $force, '--add-to-git' => $addToGit ]; - $this->call('repository:make-entity', $arguments); $this->call('repository:make-enum', ['table_name' => $_tableName, '--delete' => $delete, '--force' => $force, '--add-to-git' => $addToGit]); $this->call('repository:make-factory', ['table_name' => $_tableName, '--delete' => $delete, '--force' => $force, '--add-to-git' => $addToGit]); $this->call('repository:make-resource', $arguments); $this->call('repository:make-interface-repository', $arguments); $this->call('repository:make-mysql-repository', $arguments); - $this->call('repository:make-redis-repository', $arguments); - $this->call('repository:make-repository', [...$arguments,'selected_db'=>$this->selectedDb]); + $this->call('repository:make-redis-repository',[...$arguments,'strategy'=>$strategy]); + $this->call('repository:make-repository', [...$arguments,'strategy'=>$strategy,'selected_db'=>$this->selectedDb]); } } } diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index 1bd030b..f14413d 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -37,7 +37,6 @@ class MakeRedisRepository extends BaseCommand */ public function handle() { - $this->checkStrategyName(); $this->setArguments(); From c7810c26ad45eef3bea234cabd2ca9fa768d6da0 Mon Sep 17 00:00:00 2001 From: Farshad Tofighi Date: Sat, 15 Jul 2023 12:48:43 +0330 Subject: [PATCH 24/86] refactor --- src/Commands/MakeEnum.php | 5 ++-- src/Creators/BaseCreator.php | 11 ++++++--- src/Creators/CreatorEntity.php | 24 +++++++++++++------ src/Creators/CreatorEnum.php | 4 ++-- src/CustomMySqlQueries.php | 13 ++++++++++ ...se.clearable_temporary_cache_strategy.stub | 4 ++-- .../getAllBy/base.query_cache_strategy.stub | 4 ++-- .../base.single_key_cache_strategy.stub | 2 +- .../base.temporary_cache_strategy.stub | 4 ++-- stubs/base.enum.stub | 8 +++++++ 10 files changed, 57 insertions(+), 22 deletions(-) create mode 100644 stubs/base.enum.stub diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 7a0d391..6300410 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -39,9 +39,8 @@ public function handle(): void $enums = []; foreach ($columns as $_column) { if ($_column->DATA_TYPE == 'enum') { - $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME); - $enums[$enumClassName] = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE)); - + $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME)."Enum"; + $enums[$enumClassName] = array_filter(explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE))); $filenameWithPath = $this->relativeEnumsPath . $enumClassName.'.php'; $this->checkDelete($filenameWithPath,$enumClassName,"Enum"); } diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index eb04c06..0bcb360 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -10,9 +10,12 @@ class BaseCreator extends BaseCommand { + const ENUM_TYPE = 'enum'; + const CLASS_TYPE = 'class'; + const ALL_OPTIONS = ['Current','New','Always keep current','Always replace with new']; + private $creator; private null|string $choice=null; - const ALL_OPTIONS = ['Current','New','Always keep current','Always replace with new']; public function __construct(IClassCreator $creator) { @@ -31,11 +34,13 @@ public function createClass(string $filenameWithPath,BaseCommand $command):strin $specificPattern = '/(public|protected|private) [^\s]* \$*(?[^\s;\=]*)\s*[^;]*;/is'; $attributesArray = $this->checkDiffrence($filenameWithPath,$attributesArray,$command,$specificPattern,$generalPattern); - $attributes = implode(' ',$attributesArray); + $attributes = trim(implode("\n\t",$attributesArray)); + $attributes = (!empty($functionsArray)) ? $attributes."\n" : $attributes; $functions = implode(' ',$functionsArray); $uses = implode(PHP_EOL,$usesArray); - $basePath = __DIR__ . '/../../stubs/base.class.stub' ; + $type = (isset($this->creator->enum)) ? self::ENUM_TYPE : self::CLASS_TYPE; + $basePath = __DIR__ . "/../../stubs/base.$type.stub" ; $this->creator->baseContent = str_replace(['{{ Namespace }}', '{{ UseSection }}', '{{ ClassName }}', '{{ ExtendSection }}', '{{ Parameters }}', '{{ Functions }}'], [ $this->creator->getNameSpace(), diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index f08710e..cdc1f87 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -8,8 +8,11 @@ class CreatorEntity implements IClassCreator { use CustomMySqlQueries; + protected const PARENT_NAME = 'Entity'; + private const BOOL_TYPE = 'bool'; + public function __construct( public Collection $columns, public string $detectForeignKeys, @@ -32,13 +35,19 @@ public function createAttributs():array{ $detectForeignKeys = $this->detectForeignKeys; $tableName = $this->tableName; $attributes = []; + foreach ($columns as $_column) { + $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); $defaultValue = ($_column->COLUMN_DEFAULT ?? 'null') ? ($_column->COLUMN_DEFAULT ?? 'null') : "''"; + + $defaultValue = ($dataType == self::BOOL_TYPE) ? ((in_array($defaultValue, [0, '', "''"])) ? 'false' : + ((in_array($defaultValue, [1, '1'])) ? 'true' : $defaultValue)) : $defaultValue; + $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( $entityStubsPath, - $_column->COLUMN_NAME.($_column->IS_NULLABLE === 'YES' ? ' = '.$defaultValue : ''), - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE] + $_column->COLUMN_NAME.(!in_array($_column->COLUMN_DEFAULT, [null, 'NULL']) ? ' = '.$defaultValue : ''), + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType ); } @@ -73,18 +82,20 @@ public function createFunctions():array $tableName = $this->tableName; $settersAndGetters = []; foreach ($columns as $_column) { + $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); + $settersAndGetters['get'.ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE], + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, 'getter' ); $settersAndGetters['set'.ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $this->dataTypes[$_column->DATA_TYPE], + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, 'setter' ); @@ -94,14 +105,14 @@ public function createFunctions():array // Create Additional Setters and Getters from Foreign keys foreach ($foreignKeys as $_foreignKey) { - $settersAndGetters['get'.ucwords($_column->COLUMN_NAME)] = + $settersAndGetters['get'.ucwords($_foreignKey->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE, 'getter' ); - $settersAndGetters['set'.ucwords($_column->COLUMN_NAME)] = + $settersAndGetters['set'.ucwords($_foreignKey->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_foreignKey->VARIABLE_NAME, @@ -115,7 +126,6 @@ public function createFunctions():array private function writeAttribute(string $entityStubsPath, string $attributeName, string $attributeType): string { - $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); return str_replace(['{{ AttributeType }}', '{{ AttributeName }}'], [$attributeType, $attributeName], diff --git a/src/Creators/CreatorEnum.php b/src/Creators/CreatorEnum.php index bb828c4..a4fd16b 100644 --- a/src/Creators/CreatorEnum.php +++ b/src/Creators/CreatorEnum.php @@ -38,12 +38,12 @@ public function createFunctions(): array public function createUses(): array { - return ['use Nanvaie\DatabaseRepository\Models\Enums\Enum;']; + return []; } public function getExtendSection(): string { - return 'extends Enum'; + return ''; } public function getNameSpace(): string diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index 169f12f..8bd24db 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -41,6 +41,10 @@ trait CustomMySqlQueries 'point' => 'string', ]; + protected $columnTypes = [ + 'tinyint(1)' => 'bool' + ]; + /** * Extract all columns from a given table. */ @@ -100,4 +104,13 @@ public function extractIndexes(string $tableName): Collection return $indexes; } + + public function getDataType(string $columnType, string $dataType): string + { + if(array_key_exists($columnType, $this->columnTypes)) { + return $this->columnTypes[$columnType]; + } + + return $this->dataTypes[$dataType]; + } } diff --git a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub index 757f7d2..0a76552 100644 --- a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneByIds', + 'function_name' => 'getAllByIds', 'id' => $ids, ]); $data= $this->redisRepository->get($cacheKey); if (is_null($data)) { $data = $this->repository - ->getOneByIds($ids); + ->getAllByIds($ids); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); } diff --git a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub index 6b3c37e..0a089f7 100644 --- a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -1,5 +1,5 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneByIds', + 'function_name' => 'getAllByIds', 'id' => $ids, ]); @@ -9,7 +9,7 @@ $cacheKey = $this->redisRepository->makeKey([ if (is_null($entity)) { - $entity = $this->repository->getOneByIds($ids); + $entity = $this->repository->getAllByIds($ids); $this->redisRepository->put($cacheKey, $entity); } diff --git a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub index 5b68f71..35fdec6 100644 --- a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ $entity = $this->redisRepository->get(); if (is_null($entity)) { - $entity = $this->repository->getOneByIds($id); + $entity = $this->repository->getAllByIds($id); $this->redisRepository->put($entity); } diff --git a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub index 757f7d2..0a76552 100644 --- a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneByIds', + 'function_name' => 'getAllByIds', 'id' => $ids, ]); $data= $this->redisRepository->get($cacheKey); if (is_null($data)) { $data = $this->repository - ->getOneByIds($ids); + ->getAllByIds($ids); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); } diff --git a/stubs/base.enum.stub b/stubs/base.enum.stub new file mode 100644 index 0000000..2e04611 --- /dev/null +++ b/stubs/base.enum.stub @@ -0,0 +1,8 @@ + Date: Sat, 15 Jul 2023 15:10:55 +0330 Subject: [PATCH 25/86] update Readme.md --- Readme.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Readme.md b/Readme.md index 0e62195..346bd0f 100644 --- a/Readme.md +++ b/Readme.md @@ -49,6 +49,7 @@ List of artisan commands: - `-a|--all-tables`: Use all existing tables. - `--table_names=`: Add table names, separate names with comma. - `--selected_db=` : Use between `Mysql`,`Redis`, If it does not send, the value will return from `config/repository.php` +- `--strategy_name=` : add a trait to your redis repository based on the strategy you choose Example 1. Create new Entity for a table named 'users'. ```bash @@ -64,3 +65,12 @@ Example 3. Create all necessary classes for all tables with enabled foreign key ```bash php artisan repository:make-all -a -k ``` + +## Strategy +List of strategies for redis repository + +`ClearableTemporaryCacheStrategy` `QueryCacheStrategy` `SingleKeyCacheStrategy` `TemporaryCacheStrategy` + +```bash +php artisan repository:make-all --table_names=users --strategy_name=QueryCacheStrategy +``` \ No newline at end of file From de65388f18d1a3dc562a9f6fda7d23a09ebc13e5 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 15 Jul 2023 16:36:32 +0330 Subject: [PATCH 26/86] add SingleKeyCacheStrategy description --- Readme.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index 346bd0f..908d0a9 100644 --- a/Readme.md +++ b/Readme.md @@ -66,11 +66,17 @@ Example 3. Create all necessary classes for all tables with enabled foreign key php artisan repository:make-all -a -k ``` -## Strategy -List of strategies for redis repository +## Cache Strategy +We created some strategies for caching data, based on the number of records and change frequency +### SingleKeyCacheStrategy +SingleKeyCacheStrategy is a good choice for tables with very few rows, such as less than 50 records. This strategy creates one cache key and stores all the data on it. Then, when the app queries data, it loops through the data and returns the result. +### QueryCacheStrategy + +### TemporaryCacheStrategy + +### ClearableTemporaryCacheStrategy -`ClearableTemporaryCacheStrategy` `QueryCacheStrategy` `SingleKeyCacheStrategy` `TemporaryCacheStrategy` ```bash php artisan repository:make-all --table_names=users --strategy_name=QueryCacheStrategy -``` \ No newline at end of file +``` From c57e7e4b192e12f174f0534d8b140a8e058680cc Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 15 Jul 2023 16:47:28 +0330 Subject: [PATCH 27/86] Update Readme.md --- Readme.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Readme.md b/Readme.md index 908d0a9..3aeb560 100644 --- a/Readme.md +++ b/Readme.md @@ -68,9 +68,16 @@ php artisan repository:make-all -a -k ## Cache Strategy We created some strategies for caching data, based on the number of records and change frequency + ### SingleKeyCacheStrategy SingleKeyCacheStrategy is a good choice for tables with very few rows, such as less than 50 records. This strategy creates one cache key and stores all the data on it. Then, when the app queries data, it loops through the data and returns the result. + +This strategy has one cache key and clears all the cached data whenever there is a change. This ensures that the data is always updated and valid. + ### QueryCacheStrategy +QueryCacheStrategy is suitable for tables that have low change frequency and not too many records. For example, if the table has less than 10,000 rows or if it has more than that but the queries are not very unique and there are similar queries, this strategy works well. + +This strategy assigns a tag to each cache of the repository and clears all the cached data whenever there is a change. This ensures that the data is always updated and valid. ### TemporaryCacheStrategy From c9c06b1e5f92491aa74eff066bec2a3afbe5f4a6 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 15 Jul 2023 16:54:25 +0330 Subject: [PATCH 28/86] add TemporaryCacheStrategy description --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 3aeb560..f0a4dae 100644 --- a/Readme.md +++ b/Readme.md @@ -80,6 +80,7 @@ QueryCacheStrategy is suitable for tables that have low change frequency and not This strategy assigns a tag to each cache of the repository and clears all the cached data whenever there is a change. This ensures that the data is always updated and valid. ### TemporaryCacheStrategy +TemporaryCacheStrategy is useful when we have a large or diverse amount of data and the data user can tolerate some delay in the updates. We cache every request and delay the changes that are not critical to be reflected in real time. For example, if we have a post and we edit its content, we can cache the old version until the cache expires. We set the cache expiration time for each data item based on the maximum delay that the user can accept. This way, we use this strategy to cache data temporarily. ### ClearableTemporaryCacheStrategy From 886914c7c7176c22cf89d81a81b488d8e92c4258 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 15 Jul 2023 16:59:25 +0330 Subject: [PATCH 29/86] Update Readme.md --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index f0a4dae..c30eb5b 100644 --- a/Readme.md +++ b/Readme.md @@ -80,10 +80,10 @@ QueryCacheStrategy is suitable for tables that have low change frequency and not This strategy assigns a tag to each cache of the repository and clears all the cached data whenever there is a change. This ensures that the data is always updated and valid. ### TemporaryCacheStrategy -TemporaryCacheStrategy is useful when we have a large or diverse amount of data and the data user can tolerate some delay in the updates. We cache every request and delay the changes that are not critical to be reflected in real time. For example, if we have a post and we edit its content, we can cache the old version until the cache expires. We set the cache expiration time for each data item based on the maximum delay that the user can accept. This way, we use this strategy to cache data temporarily. +TemporaryCacheStrategy is useful when we have a large or diverse amount of data and the data user can tolerate some delay in the updates. We cache every request and delay the changes that are not critical to be reflected in real time. For example, if we have a post and we edit its content, we can cache the old version until the cache expires. We set the cache expiration time for each data item based on the maximum delay the user can accept. This way, we use this strategy to cache data temporarily. ### ClearableTemporaryCacheStrategy - +Sometimes, we need to clear the data from a temporary cache when some critical changes occur. ClearableTemporaryCacheStrategy is suitable for these situations. ```bash php artisan repository:make-all --table_names=users --strategy_name=QueryCacheStrategy From 775fb00e5a176400fe2d0350f4abd51f6f6d1aab Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 15 Jul 2023 17:47:57 +0330 Subject: [PATCH 30/86] Update Readme.md --- Readme.md | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/Readme.md b/Readme.md index c30eb5b..9ae9cbd 100644 --- a/Readme.md +++ b/Readme.md @@ -1,19 +1,19 @@ # Database Repository / PHP Repository / Laravel Repository ## Installation -Use following command to add this package to composer development requirement. +Use the following command to add this package to the composer development requirement. ```bash composer require nanvaie/database-repository --dev ``` ### Setup Laravel Repository -Then run following command in console to publish necessary assets in your project directory. +Then run the following command in the console to publish the necessary assets in your project directory. ```bash php artisan vendor:publish --tag=database-repository-config ``` ### Setup Lumen Repository -Navigate to `app.php` in `bootstrap` folder and add following line after service providers registrations: +Navigate to `app.php` in `bootstrap` folder and add the following line after service providers registrations: ```php // snip if ($app->environment('local', 'testing')) { @@ -21,11 +21,15 @@ if ($app->environment('local', 'testing')) { } // snip ``` -Copy [repository.php](config/repository.php) to project config folder located at project root. +Copy [repository.php](config/repository.php) to the project config folder located at the project root. Note: Make sure to run `composer dump-autoload` after these changes. ## Usage +To use this package easily, you can run the following command. It will create all the required components such as Entity, IRepository, Repository, MySqlRepository, RedisRepository, Resource, and Factory for the users table. +```bash +php artisan repository:make-all --table_names=users --strategy_name=QueryCacheStrategy +``` List of artisan commands: | Command | Inputs | Options | Description | @@ -44,24 +48,24 @@ List of artisan commands: ### Options Explanation - `-f|--force`: Force commands to override existing files. - `-d|--delete`: Delete already created files. -- `-k|--foreign-keys`: Try to detect foreign keys of table. -- `-g|--add-to-git`: Add created files to git repository. +- `-k|--foreign-keys`: Try to detect foreign keys of a table. +- `-g|--add-to-git`: Add created files to the git repository. - `-a|--all-tables`: Use all existing tables. - `--table_names=`: Add table names, separate names with comma. - `--selected_db=` : Use between `Mysql`,`Redis`, If it does not send, the value will return from `config/repository.php` -- `--strategy_name=` : add a trait to your redis repository based on the strategy you choose +- `--strategy_name=` : add a trait to your Redis repository based on the strategy you choose -Example 1. Create new Entity for a table named 'users'. +Example 1. Create a new Entity for a table named 'users'. ```bash php artisan repository:make-entity users ``` -Example 2. Create all necessary classes for two tables named 'users' and 'customers' with enabled foreign key option. +Example 2. Create all necessary classes for two tables named 'users' and 'customers' with an enabled foreign key option. ```bash php artisan repository:make-all --table_names=users,customers -k ``` -Example 3. Create all necessary classes for all tables with enabled foreign key option(this may be used for new projects). +Example 3. Create all necessary classes for all tables with an enabled foreign key option(this may be used for new projects). ```bash php artisan repository:make-all -a -k ``` From ae3a6c9de170f641ca69594ba5b334d7fc8de357 Mon Sep 17 00:00:00 2001 From: Farshad Tofighi Date: Sun, 16 Jul 2023 15:42:04 +0330 Subject: [PATCH 31/86] refactor and add table name to cache tag --- src/Commands/MakeAll.php | 2 -- src/Commands/MakeInterfaceRepository.php | 14 ++++---- src/Creators/BaseCreator.php | 17 +++++++--- src/Creators/CreatorFactory.php | 2 +- src/Creators/CreatorMySqlRepository.php | 13 ++++---- src/Creators/CreatorRepository.php | 12 +++---- stubs/Entities/entity.getter.stub | 3 +- stubs/Entities/entity.setter.stub | 3 +- stubs/Factories/factory.class.stub | 4 +-- stubs/Factories/factory.setter.stub | 2 +- stubs/Repositories/Base/base.construct.stub | 6 ++-- .../Base/base.construct_redis.stub | 13 ++++---- stubs/Repositories/Base/base.function.stub | 9 +++-- stubs/Repositories/Base/base.setter.sql.stub | 4 +-- .../Interface/interface.class.stub | 2 +- .../interface.deleteAndUndelete.stub | 4 +-- stubs/Repositories/Mysql/mysql.class.stub | 3 +- stubs/Repositories/Mysql/mysql.construct.stub | 14 ++++---- stubs/Repositories/Mysql/mysql.create.stub | 19 +++++------ stubs/Repositories/Mysql/mysql.delete.stub | 16 ++++----- .../Mysql/mysql.deleteAndUndelete.stub | 33 +++++++++---------- stubs/Repositories/Mysql/mysql.getAllBy.stub | 15 ++++----- stubs/Repositories/Mysql/mysql.getOneBy.stub | 15 ++++----- stubs/Repositories/Mysql/mysql.getter.stub | 2 +- stubs/Repositories/Mysql/mysql.setter.stub | 2 +- stubs/Repositories/Mysql/mysql.timeField.stub | 2 +- stubs/Repositories/Mysql/mysql.undelete.stub | 16 ++++----- stubs/Repositories/Mysql/mysql.update.stub | 19 +++++------ stubs/Repositories/Redis/base.clear.stub | 2 +- ...se.clearable_temporary_cache_strategy.stub | 11 ++++--- .../create/base.query_cache_strategy.stub | 2 +- .../base.single_key_cache_strategy.stub | 2 +- ...se.clearable_temporary_cache_strategy.stub | 18 +++++----- .../getAllBy/base.query_cache_strategy.stub | 6 ---- .../base.single_key_cache_strategy.stub | 10 +++--- .../base.temporary_cache_strategy.stub | 18 +++++----- ...se.clearable_temporary_cache_strategy.stub | 21 ++++++------ .../getOneBy/base.query_cache_strategy.stub | 1 + .../base.single_key_cache_strategy.stub | 10 +++--- .../base.temporary_cache_strategy.stub | 16 ++++----- ...se.clearable_temporary_cache_strategy.stub | 3 +- .../update/base.query_cache_strategy.stub | 2 +- .../base.single_key_cache_strategy.stub | 2 +- stubs/Resources/resource.class.stub | 4 +-- .../Resources/resource.function.foreign.stub | 10 +++--- stubs/Resources/resource.function.getter.stub | 10 +++--- stubs/Resources/resource.getter.default.stub | 2 +- stubs/Resources/resource.getter.foreign.stub | 2 +- stubs/base.class.stub | 2 +- 49 files changed, 210 insertions(+), 210 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 69bfdf3..1bacf02 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -37,8 +37,6 @@ class MakeAll extends Command */ public function handle() { - - $strategyNames = array("ClearableTemporaryCacheStrategy", "QueryCacheStrategy", "SingleKeyCacheStrategy", "TemporaryCacheStrategy"); if (!in_array($this->option('strategy_name'), $strategyNames)) { $this->alert("This pattern strategy does not exist !!! "); diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index fbe4b77..bcbb2e1 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -70,28 +70,28 @@ public function handle(): void $updateFunctionStub = file_get_contents($this->interfaceRepositoryStubsPath . 'update.stub'); $deleteAndUndeleteStub = file_get_contents($this->interfaceRepositoryStubsPath . 'deleteAndUndelete.stub'); - $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, 'id', 'int'), -1, 0); - $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, 'id', 'int'), -1, 0); + $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, 'id', 'int'), -2, 0); + $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, 'id', 'int'), -2, 0); if ($this->detectForeignKeys) { foreach ($foreignKeys as $_foreignKey) { - $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName), -1, 0); - $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName), -1, 0); + $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName), -2, 0); + $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName), -2, 0); } } $allColumns = $columns->pluck('COLUMN_NAME')->toArray(); if (in_array('created_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $createFunctionStub, -1, 0); + $baseContent = substr_replace($baseContent, $createFunctionStub, -2, 0); } if (in_array('updated_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $updateFunctionStub, -1, 0); + $baseContent = substr_replace($baseContent, $updateFunctionStub, -2, 0); } if (in_array('deleted_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $deleteAndUndeleteStub, -1, 0); + $baseContent = substr_replace($baseContent, $deleteAndUndeleteStub, -2, 0); } $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ InterfaceRepositoryName }}', '{{ RepositoryNamespace }}'], diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 0bcb360..4a52835 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -13,6 +13,8 @@ class BaseCreator extends BaseCommand const ENUM_TYPE = 'enum'; const CLASS_TYPE = 'class'; const ALL_OPTIONS = ['Current','New','Always keep current','Always replace with new']; + const QUERY_CACHE_STRATEGY = 'QueryCacheStrategy'; + const SINGLE_KEY_CACHE_STRATEGY = 'SingleKeyCacheStrategy'; private $creator; private null|string $choice=null; @@ -35,20 +37,22 @@ public function createClass(string $filenameWithPath,BaseCommand $command):strin $attributesArray = $this->checkDiffrence($filenameWithPath,$attributesArray,$command,$specificPattern,$generalPattern); $attributes = trim(implode("\n\t",$attributesArray)); - $attributes = (!empty($functionsArray)) ? $attributes."\n" : $attributes; - $functions = implode(' ',$functionsArray); + $functions = trim(implode("\n",$functionsArray)); + $functions = (!empty($attributes)) ? "\n\n\t".$functions : $functions; $uses = implode(PHP_EOL,$usesArray); $type = (isset($this->creator->enum)) ? self::ENUM_TYPE : self::CLASS_TYPE; $basePath = __DIR__ . "/../../stubs/base.$type.stub" ; - $this->creator->baseContent = str_replace(['{{ Namespace }}', '{{ UseSection }}', '{{ ClassName }}', '{{ ExtendSection }}', '{{ Parameters }}', '{{ Functions }}'], + + $this->creator->baseContent = str_replace(['{{ Namespace }}', '{{ UseSection }}', '{{ ClassName }}', '{{ ExtendSection }}', '{{ Parameters }}', '{{ Functions }}', '{{ CacheTag }}'], [ $this->creator->getNameSpace(), $uses, $this->creator->getClassName(), $this->creator->getExtendSection(), $attributes, - $functions + $functions, + $this->setCachetag($command) ], file_get_contents($basePath)); @@ -100,4 +104,9 @@ public function checkDiffrence(string $filenameWithPath,array $newParamsArray,Ba } return $newParamsArray; } + + private function setCacheTag(BaseCommand $command) + { + return (isset($command->strategyName) && in_array($command->strategyName, [self::QUERY_CACHE_STRATEGY, self::SINGLE_KEY_CACHE_STRATEGY])) ? "'$command->tableName'" : "''"; + } } diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php index ed5c2fa..c5e9773 100644 --- a/src/Creators/CreatorFactory.php +++ b/src/Creators/CreatorFactory.php @@ -37,7 +37,7 @@ public function createFunctions(): array $setterStub = file_get_contents($this->factoryStubsPath . 'setter.stub'); $setterFunctions = ''; foreach ($this->columns as $_column) { - $setterFunctions .= $this->writeSetter($setterStub, $_column->COLUMN_NAME); + $setterFunctions .= trim($this->writeSetter($setterStub, $_column->COLUMN_NAME))."\n\t\t"; } return ['makeEntityFromStdClass' => str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityVariableName }}'], diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index 17ab02b..68ff09f 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -97,14 +97,14 @@ public function createFunctions(): array // Create "create" function foreach ($this->columns as $_column) { if (!in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { - $getterFunctions .= $this->writeGetterFunction($getterStub, $_column->COLUMN_NAME); + $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME))."\n\t\t\t\t"; } if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { - $setterFunctions .= $this->writeSetterFunction($setterStub, $_column->COLUMN_NAME); + $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME))."\n\t\t"; } } $createFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ SetterFunctions }}"], - [substr($getterFunctions, 0, -1), substr($setterFunctions, 0, -1)], + [trim(substr($getterFunctions, 0, -1)), trim(substr($setterFunctions, 0, -1))], $createFunctionStub ); @@ -115,14 +115,14 @@ public function createFunctions(): array // Create "update" function foreach ($this->columns as $_column) { if (!in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { - $getterFunctions .= $this->writeGetterFunction($getterStub, $_column->COLUMN_NAME); + $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME))."\n\t\t\t\t"; } if ($_column->COLUMN_NAME === 'updated_at') { - $setterFunctions .= $this->writeSetterFunction($setterStub, $_column->COLUMN_NAME); + $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME))."\n\t\t"; } } $updateFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ UpdateFieldSetter }}"], - [substr($getterFunctions, 0, -1), substr($setterFunctions, 0, -1)], + [trim(substr($getterFunctions, 0, -1)), trim(substr($setterFunctions, 0, -1))], $updateFunctionStub ); @@ -133,6 +133,7 @@ public function createFunctions(): array $functions['remove'] = $deleteStub; $functions['restore'] = $undeleteStub; } + foreach ($functions as &$func) { $func = str_replace(["{{ EntityName }}", "{{ EntityVariableName }}"], [$this->entityName, $this->entityVariableName], diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index f1c5af7..a5b7dd0 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -152,11 +152,11 @@ public function createFunctions(): array } public function getConstruct(string $setterSqlStub, string $constructStub) { - return str_replace("{{ Setters }}", $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName,$this->redisRepositoryVariable,$this->redisRepositoryName), $constructStub); + return str_replace("{{ Setters }}", trim($this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName,$this->redisRepositoryVariable,$this->redisRepositoryName)), $constructStub); } public function getConstructRedis(string $setterSqlStub, string $constructStub) { - return str_replace("{{ Setters }}", $this->writeRedisAttribute($setterSqlStub,$this->redisRepositoryVariable,$this->redisRepositoryName), $constructStub); + return str_replace("{{ Setters }}", trim($this->writeRedisAttribute($setterSqlStub,$this->redisRepositoryVariable,$this->redisRepositoryName)), $constructStub); } private function getRedisCashFunctionGetOneBy($strategyName) { @@ -165,7 +165,7 @@ private function getRedisCashFunctionGetOneBy($strategyName) 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), - 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), }; } private function getRedisCashFunctionGetAllBy($strategyName) @@ -175,7 +175,7 @@ private function getRedisCashFunctionGetAllBy($strategyName) 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), - 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), }; } private function getRedisCashFunctionCreate($strategyName) @@ -185,7 +185,7 @@ private function getRedisCashFunctionCreate($strategyName) 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), - 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), }; } private function getRedisCashFunctionUpdate($strategyName) @@ -195,7 +195,7 @@ private function getRedisCashFunctionUpdate($strategyName) 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), - 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'), + 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), }; } } diff --git a/stubs/Entities/entity.getter.stub b/stubs/Entities/entity.getter.stub index 730522b..a9a8bc5 100644 --- a/stubs/Entities/entity.getter.stub +++ b/stubs/Entities/entity.getter.stub @@ -1,5 +1,4 @@ - - public function get{{ GetterName }}(): {{ AttributeType }} + public function get{{ GetterName }}(): {{ AttributeType }} { return $this->{{ AttributeName }}; } diff --git a/stubs/Entities/entity.setter.stub b/stubs/Entities/entity.setter.stub index 0883693..7865c08 100644 --- a/stubs/Entities/entity.setter.stub +++ b/stubs/Entities/entity.setter.stub @@ -1,5 +1,4 @@ - - public function set{{ SetterName }}({{ AttributeType }} ${{ AttributeName }}): void + public function set{{ SetterName }}({{ AttributeType }} ${{ AttributeName }}): void { $this->{{ AttributeName }} = ${{ AttributeName }}; } diff --git a/stubs/Factories/factory.class.stub b/stubs/Factories/factory.class.stub index 7ffa7c4..c2d5c5f 100644 --- a/stubs/Factories/factory.class.stub +++ b/stubs/Factories/factory.class.stub @@ -1,7 +1,7 @@ -public function makeEntityFromStdClass(stdClass $entity): {{ EntityName }} + public function makeEntityFromStdClass(stdClass $entity): {{ EntityName }} { ${{ EntityVariableName }} = new {{ EntityName }}(); -{{ SetterFunctions }} + {{ SetterFunctions }} return ${{ EntityVariableName }}; } diff --git a/stubs/Factories/factory.setter.stub b/stubs/Factories/factory.setter.stub index 3eca867..657234c 100644 --- a/stubs/Factories/factory.setter.stub +++ b/stubs/Factories/factory.setter.stub @@ -1 +1 @@ - ${{ EntityVariableName }}->set{{ SetterName }}($entity->{{ AttributeName }}); +${{ EntityVariableName }}->set{{ SetterName }}($entity->{{ AttributeName }}); diff --git a/stubs/Repositories/Base/base.construct.stub b/stubs/Repositories/Base/base.construct.stub index 2f2eb37..414e264 100644 --- a/stubs/Repositories/Base/base.construct.stub +++ b/stubs/Repositories/Base/base.construct.stub @@ -1,4 +1,4 @@ - public function __construct() - { -{{ Setters }} } + { + {{ Setters }} + } diff --git a/stubs/Repositories/Base/base.construct_redis.stub b/stubs/Repositories/Base/base.construct_redis.stub index c028e29..23d3b45 100644 --- a/stubs/Repositories/Base/base.construct_redis.stub +++ b/stubs/Repositories/Base/base.construct_redis.stub @@ -1,6 +1,7 @@ - use {{Strategy}}; - public function __construct() - { - $this->cacheTag = ''; - parent::__construct(); - } +use {{Strategy}}; + + public function __construct() + { + $this->cacheTag = {{ CacheTag }}; + parent::__construct(); + } diff --git a/stubs/Repositories/Base/base.function.stub b/stubs/Repositories/Base/base.function.stub index 6af2b85..04d915a 100644 --- a/stubs/Repositories/Base/base.function.stub +++ b/stubs/Repositories/Base/base.function.stub @@ -1,6 +1,5 @@ - - public function {{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): {{ FunctionReturnType }} - { + public function {{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): {{ FunctionReturnType }} + { {{redisFunction}} - return $this->{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }}); - } + return $this->{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }}); + } diff --git a/stubs/Repositories/Base/base.setter.sql.stub b/stubs/Repositories/Base/base.setter.sql.stub index 6cc7e72..94901a9 100644 --- a/stubs/Repositories/Base/base.setter.sql.stub +++ b/stubs/Repositories/Base/base.setter.sql.stub @@ -1,2 +1,2 @@ - $this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); - $this->{{ RedisRepositoryVariable }} = new {{ RedisRepositoryName }}(); +$this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); + $this->{{ RedisRepositoryVariable }} = new {{ RedisRepositoryName }}(); diff --git a/stubs/Repositories/Interface/interface.class.stub b/stubs/Repositories/Interface/interface.class.stub index cb9a94d..401663c 100644 --- a/stubs/Repositories/Interface/interface.class.stub +++ b/stubs/Repositories/Interface/interface.class.stub @@ -6,4 +6,4 @@ use {{ EntityNamespace }}\{{ EntityName }}; use Illuminate\Support\Collection; interface {{ InterfaceRepositoryName }} -{} \ No newline at end of file +{} diff --git a/stubs/Repositories/Interface/interface.deleteAndUndelete.stub b/stubs/Repositories/Interface/interface.deleteAndUndelete.stub index 031de27..314223d 100644 --- a/stubs/Repositories/Interface/interface.deleteAndUndelete.stub +++ b/stubs/Repositories/Interface/interface.deleteAndUndelete.stub @@ -1,4 +1,4 @@ - public function remove({{ EntityName }} ${{ EntityVariableName }}): int; + public function remove({{ EntityName }} ${{ EntityVariableName }}): int; - public function restore({{ EntityName }} ${{ EntityVariableName }}): int; + public function restore({{ EntityName }} ${{ EntityVariableName }}): int; diff --git a/stubs/Repositories/Mysql/mysql.class.stub b/stubs/Repositories/Mysql/mysql.class.stub index 9b92ecd..920ac2d 100644 --- a/stubs/Repositories/Mysql/mysql.class.stub +++ b/stubs/Repositories/Mysql/mysql.class.stub @@ -18,5 +18,6 @@ class {{ MySqlRepositoryName }} extends MySqlRepository implements {{ Repository parent::__construct(); } -{{ Functions }} + + {{ Functions }} } diff --git a/stubs/Repositories/Mysql/mysql.construct.stub b/stubs/Repositories/Mysql/mysql.construct.stub index 3c40aba..406fe80 100644 --- a/stubs/Repositories/Mysql/mysql.construct.stub +++ b/stubs/Repositories/Mysql/mysql.construct.stub @@ -1,9 +1,9 @@ public function __construct() - { - $this->table = '{{ TableName }}'; - $this->primaryKey = 'id'; - $this->softDelete = {{ HasSoftDelete }}; - $this->factory = new {{ FactoryName }}(); + { + $this->table = '{{ TableName }}'; + $this->primaryKey = 'id'; + $this->softDelete = {{ HasSoftDelete }}; + $this->factory = new {{ FactoryName }}(); - parent::__construct(); - } + parent::__construct(); + } diff --git a/stubs/Repositories/Mysql/mysql.create.stub b/stubs/Repositories/Mysql/mysql.create.stub index e83ac43..c70bd9c 100644 --- a/stubs/Repositories/Mysql/mysql.create.stub +++ b/stubs/Repositories/Mysql/mysql.create.stub @@ -1,14 +1,13 @@ - public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} - { -{{ SetterFunctions }} + { + {{ SetterFunctions }} - $id = $this->newQuery() - ->insertGetId([ -{{ GetterFunctions }} - ]); + $id = $this->newQuery() + ->insertGetId([ + {{ GetterFunctions }} + ]); - ${{ EntityVariableName }}->setId($id); + ${{ EntityVariableName }}->setId($id); - return ${{ EntityVariableName }}; - } + return ${{ EntityVariableName }}; + } diff --git a/stubs/Repositories/Mysql/mysql.delete.stub b/stubs/Repositories/Mysql/mysql.delete.stub index eae0902..5a99837 100644 --- a/stubs/Repositories/Mysql/mysql.delete.stub +++ b/stubs/Repositories/Mysql/mysql.delete.stub @@ -1,8 +1,8 @@ -public function remove({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => date('Y-m-d H:i:s'), - ]); - } + public function remove({{ EntityName }} ${{ EntityVariableName }}): int + { + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + 'deleted_at' => date('Y-m-d H:i:s'), + ]); + } diff --git a/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub index a0da20b..725ee00 100644 --- a/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub +++ b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub @@ -1,18 +1,17 @@ + public function remove({{ EntityName }} ${{ EntityVariableName }}): int + { + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + 'deleted_at' => date('Y-m-d H:i:s'), + ]); + } - public function remove({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => date('Y-m-d H:i:s'), - ]); - } - - public function restore({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => null, - ]); - } + public function restore({{ EntityName }} ${{ EntityVariableName }}): int + { + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + 'deleted_at' => null, + ]); + } diff --git a/stubs/Repositories/Mysql/mysql.getAllBy.stub b/stubs/Repositories/Mysql/mysql.getAllBy.stub index 6c31d38..0c6d435 100644 --- a/stubs/Repositories/Mysql/mysql.getAllBy.stub +++ b/stubs/Repositories/Mysql/mysql.getAllBy.stub @@ -1,9 +1,8 @@ + public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection + { + ${{ EntityVariableName }} = $this->newQuery() + ->whereIn('{{ ColumnName }}', ${{ AttributeNamePlural }}) + ->get(); - public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection - { - ${{ EntityVariableName }} = $this->newQuery() - ->whereIn('{{ ColumnName }}', ${{ AttributeNamePlural }}) - ->get(); - - return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); - } + return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); + } diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub index 68b5556..b18cf9e 100644 --- a/stubs/Repositories/Mysql/mysql.getOneBy.stub +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -1,9 +1,8 @@ + public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} + { + ${{ EntityVariableName }} = $this->newQuery() + ->where('{{ ColumnName }}', ${{ AttributeName }}) + ->first(); - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} - { - ${{ EntityVariableName }} = $this->newQuery() - ->where('{{ ColumnName }}', ${{ AttributeName }}) - ->first(); - - return ${{ EntityVariableName }} ? $this->factory->makeEntityFromStdClass(${{ EntityVariableName }}) : null; - } + return ${{ EntityVariableName }} ? $this->factory->makeEntityFromStdClass(${{ EntityVariableName }}) : null; + } diff --git a/stubs/Repositories/Mysql/mysql.getter.stub b/stubs/Repositories/Mysql/mysql.getter.stub index 3886dce..fccab8d 100644 --- a/stubs/Repositories/Mysql/mysql.getter.stub +++ b/stubs/Repositories/Mysql/mysql.getter.stub @@ -1 +1 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), + '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), diff --git a/stubs/Repositories/Mysql/mysql.setter.stub b/stubs/Repositories/Mysql/mysql.setter.stub index 5bdf5ba..2b886d7 100644 --- a/stubs/Repositories/Mysql/mysql.setter.stub +++ b/stubs/Repositories/Mysql/mysql.setter.stub @@ -1 +1 @@ - ${{ EntityVariableName }}->set{{ SetterName }}(date('Y-m-d H:i:s')); + ${{ EntityVariableName }}->set{{ SetterName }}(date('Y-m-d H:i:s')); diff --git a/stubs/Repositories/Mysql/mysql.timeField.stub b/stubs/Repositories/Mysql/mysql.timeField.stub index 1f24763..f5b27ac 100644 --- a/stubs/Repositories/Mysql/mysql.timeField.stub +++ b/stubs/Repositories/Mysql/mysql.timeField.stub @@ -1 +1 @@ - '{{ ColumnName }}' => date('Y-m-d H:i:s'), + '{{ ColumnName }}' => date('Y-m-d H:i:s'), diff --git a/stubs/Repositories/Mysql/mysql.undelete.stub b/stubs/Repositories/Mysql/mysql.undelete.stub index 3baf14f..54238af 100644 --- a/stubs/Repositories/Mysql/mysql.undelete.stub +++ b/stubs/Repositories/Mysql/mysql.undelete.stub @@ -1,8 +1,8 @@ -public function restore({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => null, - ]); - } + public function restore({{ EntityName }} ${{ EntityVariableName }}): int + { + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + 'deleted_at' => null, + ]); + } diff --git a/stubs/Repositories/Mysql/mysql.update.stub b/stubs/Repositories/Mysql/mysql.update.stub index 11da133..7671962 100644 --- a/stubs/Repositories/Mysql/mysql.update.stub +++ b/stubs/Repositories/Mysql/mysql.update.stub @@ -1,11 +1,10 @@ + public function update({{ EntityName }} ${{ EntityVariableName }}): int + { + {{ UpdateFieldSetter }} - public function update({{ EntityName }} ${{ EntityVariableName }}): int - { -{{ UpdateFieldSetter }} - - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ -{{ GetterFunctions }} - ]); - } + return $this->newQuery() + ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) + ->update([ + {{ GetterFunctions }} + ]); + } diff --git a/stubs/Repositories/Redis/base.clear.stub b/stubs/Repositories/Redis/base.clear.stub index d956e7e..e67fa83 100644 --- a/stubs/Repositories/Redis/base.clear.stub +++ b/stubs/Repositories/Redis/base.clear.stub @@ -1 +1 @@ - $this->redisRepository->clear(); +$this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub index b2beec7..6eac59f 100644 --- a/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub @@ -1,5 +1,6 @@ -$cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'create', - 'id' => $id, -]); - $this->redisRepository->clear($cacheKey); + $cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'create', + 'id' => $id, + ]); + + $this->redisRepository->clear($cacheKey); diff --git a/stubs/Repositories/Redis/create/base.query_cache_strategy.stub b/stubs/Repositories/Redis/create/base.query_cache_strategy.stub index 597a987..e67fa83 100644 --- a/stubs/Repositories/Redis/create/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/create/base.query_cache_strategy.stub @@ -1 +1 @@ - $this->redisRepository->clear(); +$this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub index 4f8eaf4..e67fa83 100644 --- a/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/create/base.single_key_cache_strategy.stub @@ -1 +1 @@ - $this->redisRepository->clear(); +$this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub index 0a76552..15b27a8 100644 --- a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getAllByIds', - 'id' => $ids, -]); + 'function_name' => 'getAllByIds', + 'id' => $ids, + ]); - $data= $this->redisRepository->get($cacheKey); - if (is_null($data)) { - $data = $this->repository - ->getAllByIds($ids); - $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); - } + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $data = $this->repository->getAllByIds($ids); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } diff --git a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub index 0a089f7..c9be1e6 100644 --- a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -5,13 +5,7 @@ $cacheKey = $this->redisRepository->makeKey([ $entity = $this->redisRepository->get($cacheKey); - - - if (is_null($entity)) { $entity = $this->repository->getAllByIds($ids); $this->redisRepository->put($cacheKey, $entity); } - - - diff --git a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub index 35fdec6..5cfac3d 100644 --- a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ +$entity = $this->redisRepository->get(); - $entity = $this->redisRepository->get(); - if (is_null($entity)) { - $entity = $this->repository->getAllByIds($id); - $this->redisRepository->put($entity); - } + if (is_null($entity)) { + $entity = $this->repository->getAllByIds($id); + $this->redisRepository->put($entity); + } diff --git a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub index 0a76552..d74c282 100644 --- a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getAllByIds', - 'id' => $ids, -]); + 'function_name' => 'getAllByIds', + 'id' => $ids, + ]); - $data= $this->redisRepository->get($cacheKey); - if (is_null($data)) { - $data = $this->repository - ->getAllByIds($ids); - $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); - } + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $data = $this->repository->getAllByIds($ids); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } diff --git a/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub index aa5911b..a079432 100644 --- a/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub @@ -1,10 +1,11 @@ -$cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneById', - 'id' => $id, -]); - $data= $this->redisRepository->get($cacheKey); - if (is_null($data)) { - $data = $this->repository - ->getOneById($id); - $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); - } \ No newline at end of file + $cacheKey = $this->redisRepository->makeKey([ + 'function_name' => 'getOneById', + 'id' => $id, + ]); + + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $data = $this->repository->getOneById($id); + $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); + } diff --git a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub index b28ebce..5e260a0 100644 --- a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub @@ -4,6 +4,7 @@ $cacheKey = $this->redisRepository->makeKey([ ]); $entity = $this->redisRepository->get($cacheKey); + if (is_null($entity)) { $entity = $this->repository->getOneById($id); $this->redisRepository->put($cacheKey, $entity); diff --git a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub index b1dfa07..60b7609 100644 --- a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ + $entity = $this->redisRepository->get(); - $entity = $this->redisRepository->get(); - if (is_null($entity)) { - $entity = $this->repository->getOneById($id); - $this->redisRepository->put($entity); - } + if (is_null($entity)) { + $entity = $this->repository->getOneById($id); + $this->redisRepository->put($entity); + } diff --git a/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub index 4a9789c..aa606f6 100644 --- a/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneById', - 'id' => $id, -]); + 'function_name' => 'getOneById', + 'id' => $id, + ]); - $data= $this->redisRepository->get($cacheKey); - if (is_null($data)) { - $data = $this->repository - ->getOneById($id); + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $data = $this->repository->getOneById($id); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); - } + } diff --git a/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub index c22ce76..ead52a7 100644 --- a/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub @@ -2,4 +2,5 @@ $cacheKey = $this->redisRepository->makeKey([ 'function_name' => 'update', 'id' => $id, ]); - $this->redisRepository->clear($cacheKey); + +$this->redisRepository->clear($cacheKey); diff --git a/stubs/Repositories/Redis/update/base.query_cache_strategy.stub b/stubs/Repositories/Redis/update/base.query_cache_strategy.stub index 597a987..e67fa83 100644 --- a/stubs/Repositories/Redis/update/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/update/base.query_cache_strategy.stub @@ -1 +1 @@ - $this->redisRepository->clear(); +$this->redisRepository->clear(); diff --git a/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub index 4f8eaf4..e67fa83 100644 --- a/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/update/base.single_key_cache_strategy.stub @@ -1 +1 @@ - $this->redisRepository->clear(); +$this->redisRepository->clear(); diff --git a/stubs/Resources/resource.class.stub b/stubs/Resources/resource.class.stub index c52cfd6..d155085 100644 --- a/stubs/Resources/resource.class.stub +++ b/stubs/Resources/resource.class.stub @@ -11,14 +11,14 @@ class {{ ResourceName }} extends Resource public function toArray(${{ EntityVariableName }}): array { return [ -{{ GetterFunctions }} + {{ GetterFunctions }} ]; } public function toArrayWithForeignKeys(${{ EntityVariableName }}): array { return $this->toArray(${{ EntityVariableName }}) + [ -{{ ForeignGetterFunctions }} + {{ ForeignGetterFunctions }} ]; } } diff --git a/stubs/Resources/resource.function.foreign.stub b/stubs/Resources/resource.function.foreign.stub index beea893..b774e84 100644 --- a/stubs/Resources/resource.function.foreign.stub +++ b/stubs/Resources/resource.function.foreign.stub @@ -1,6 +1,6 @@ public function toArrayWithForeignKeys(${{ EntityVariableName }}): array - { - return $this->toArray(${{ EntityVariableName }}) + [ -{{ ForeignGetterFunctions }} - ]; - } +{ + return $this->toArray(${{ EntityVariableName }}) + [ + {{ ForeignGetterFunctions }} + ]; +} diff --git a/stubs/Resources/resource.function.getter.stub b/stubs/Resources/resource.function.getter.stub index b64d3bf..0ce2a7b 100644 --- a/stubs/Resources/resource.function.getter.stub +++ b/stubs/Resources/resource.function.getter.stub @@ -1,6 +1,6 @@ public function toArray(${{ EntityVariableName }}): array - { - return [ -{{ Getters }} - ]; - } +{ + return [ + {{ Getters }} + ]; +} diff --git a/stubs/Resources/resource.getter.default.stub b/stubs/Resources/resource.getter.default.stub index 7c12036..dbbc815 100644 --- a/stubs/Resources/resource.getter.default.stub +++ b/stubs/Resources/resource.getter.default.stub @@ -1 +1 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), +'{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), diff --git a/stubs/Resources/resource.getter.foreign.stub b/stubs/Resources/resource.getter.foreign.stub index 42c3769..64404ce 100644 --- a/stubs/Resources/resource.getter.foreign.stub +++ b/stubs/Resources/resource.getter.foreign.stub @@ -1 +1 @@ - '{{ AttributeName }}' => ${{ EntityVariableName }}->get{{ GetterName }}() ? (new {{ AttributeType }}Resource())->toArray(${{ EntityVariableName }}->get{{ GetterName }}()) : null, +'{{ AttributeName }}' => ${{ EntityVariableName }}->get{{ GetterName }}() ? (new {{ AttributeType }}Resource())->toArray(${{ EntityVariableName }}->get{{ GetterName }}()) : null, diff --git a/stubs/base.class.stub b/stubs/base.class.stub index 618ccc1..7bdbcdd 100644 --- a/stubs/base.class.stub +++ b/stubs/base.class.stub @@ -6,5 +6,5 @@ namespace {{ Namespace }}; class {{ ClassName }} {{ ExtendSection }} { - {{ Parameters }}{{ Functions }} + {{ Parameters }} {{ Functions }} } From ae528debccd709003c0399cad1684bf48dec2067 Mon Sep 17 00:00:00 2001 From: Farshad Tofighi Date: Mon, 17 Jul 2023 15:32:45 +0330 Subject: [PATCH 32/86] add getOne and getAll for indexed columns --- src/Commands/MakeInterfaceRepository.php | 11 ++++++++ src/Creators/CreatorMySqlRepository.php | 11 +++++--- src/Creators/CreatorRepository.php | 25 +++++++++++-------- src/CustomMySqlQueries.php | 8 ++++++ .../Interface/interface.getOneBy.stub | 2 +- stubs/Repositories/Mysql/mysql.getOneBy.stub | 2 +- ...se.clearable_temporary_cache_strategy.stub | 6 ++--- .../getAllBy/base.query_cache_strategy.stub | 6 ++--- .../base.single_key_cache_strategy.stub | 2 +- .../base.temporary_cache_strategy.stub | 6 ++--- ...se.clearable_temporary_cache_strategy.stub | 6 ++--- .../getOneBy/base.query_cache_strategy.stub | 6 ++--- .../base.single_key_cache_strategy.stub | 2 +- .../base.temporary_cache_strategy.stub | 6 ++--- 14 files changed, 64 insertions(+), 35 deletions(-) diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index bcbb2e1..ebf1471 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -72,6 +72,17 @@ public function handle(): void $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, 'id', 'int'), -2, 0); $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, 'id', 'int'), -2, 0); + $columnsInfo = $this->getAllColumnsInTable($this->tableName); + + $indexes = $this->extractIndexes($this->tableName); + foreach ($indexes as $index) { + $columnInfo = collect($columnsInfo)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); + $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)), -2, 0); + + if($index->Non_unique == 1) { + $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getAllStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)), -2, 0); + } + } if ($this->detectForeignKeys) { foreach ($foreignKeys as $_foreignKey) { diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index 68ff09f..de5a61d 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -73,13 +73,18 @@ public function createFunctions(): array $functions['__construct'] = $this->getConstruct($this->tableName, $this->factoryName, $hasSoftDelete, $constructContent); $functions['getOneById'] = $this->writeGetOneFunction($getOneStub, 'id', 'int'); $functions['getAllByIds'] = $this->writeGetAllFunction($getAllStub, 'id', 'int'); + $columnsInfo = $this->getAllColumnsInTable($this->tableName); $indexes = $this->extractIndexes($this->tableName); foreach ($indexes as $index) { + $columnInfo = collect($columnsInfo)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); $indx = 'getOneBy' . ucfirst(Str::camel($index->COLUMN_NAME)); - $functions[$indx] = $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->entityName); - $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); - $functions[$indx] = $this->writeGetAllFunction($getAllStub, $index->COLUMN_NAME, $this->entityName); + $functions[$indx] = $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)); + + if($index->Non_unique == 1) { + $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); + $functions[$indx] = $this->writeGetAllFunction($getAllStub, $index->COLUMN_NAME, $this->entityName); + } } if ($this->detectForeignKeys) { diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index a5b7dd0..b42bb43 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -37,31 +37,30 @@ public function __construct( private function writeFunction(string $functionStub, string $functionName, string $columnName, string $attributeType): string { + $columnNameSingle = Str::camel($columnName); + if ($functionName === 'getOneBy') { $functionReturnType = 'null|{{ EntityName }}'; $functionName .= ucfirst(Str::camel($columnName)); $columnName = Str::camel($columnName); $redisCashFunction = $this->getRedisCashFunctionGetOneBy($this->strategyName); - - } elseif ($functionName === 'getAllBy') { $functionReturnType = 'Collection'; $functionName .= ucfirst(Str::plural(Str::camel($columnName))); $columnName = Str::plural(Str::camel($columnName)); $redisCashFunction = $this->getRedisCashFunctionGetAllBy($this->strategyName); - - } elseif ($functionName === 'create') { $functionReturnType = $attributeType; $redisCashFunction = $this->getRedisCashFunctionCreate($this->strategyName); - } elseif (in_array($functionName, ['update', 'remove', 'restore'])) { $functionReturnType = 'int'; $redisCashFunction = $this->getRedisCashFunctionUpdate($this->strategyName); - } + + $redisCashFunction = str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ ColumnNameSingle }}'], [$functionName, $columnName, $columnNameSingle], $redisCashFunction); + return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}','{{redisFunction}}'], - [$functionName, $attributeType, Str::camel($columnName), $functionReturnType,$redisCashFunction], + [$functionName, $attributeType, Str::camel($columnName), $functionReturnType, $redisCashFunction], $functionStub); } private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable, string $sqlRepositoryName): string @@ -119,12 +118,18 @@ public function createFunctions(): array $functions['__construct'] = $this->getConstructRedis($setterSqlStub, $constructStub); $functions['getOneById'] = $this->writeFunction($functionStub, 'getOneBy', 'id', 'int'); $functions['getAllByIds'] = $this->writeFunction($functionStub, 'getAllBy', 'id', 'array'); + $columnsInfo = $this->getAllColumnsInTable($this->tableName); + $indexes = $this->extractIndexes($this->tableName); foreach ($indexes as $index) { - $fun_name = ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); - $functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $index->COLUMN_NAME, 'array'); + $columnInfo = collect($columnsInfo)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); $fun_name = ucfirst(Str::camel($index->COLUMN_NAME)); - $functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $index->COLUMN_NAME, 'int'); + $functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)); + + if($index->Non_unique == 1) { + $fun_name = ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); + $functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $index->COLUMN_NAME, 'array'); + } } if ($this->detectForeignKeys) { $foreignKeys = $this->extractForeignKeys($this->tableName); diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index 8bd24db..d00247f 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -102,6 +102,14 @@ public function extractIndexes(string $tableName): Collection ->orderBy('ORDINAL_POSITION') ->get(); + $indexesData = DB::select("SHOW INDEX FROM $tableName WHERE Key_name != 'PRIMARY'"); + + collect($indexes)->each(function ($index) use ($indexesData) { + $indexesData = collect($indexesData)->where('Column_name', $index->COLUMN_NAME)->first(); + $index->Non_unique = $indexesData->Non_unique; + $index->Index_type = $indexesData->Index_type; + }); + return $indexes; } diff --git a/stubs/Repositories/Interface/interface.getOneBy.stub b/stubs/Repositories/Interface/interface.getOneBy.stub index 7e755c7..a3ff008 100644 --- a/stubs/Repositories/Interface/interface.getOneBy.stub +++ b/stubs/Repositories/Interface/interface.getOneBy.stub @@ -1,2 +1,2 @@ - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }}; + public function getOneBy{{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): null|{{ EntityName }}; diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub index b18cf9e..f8e44e2 100644 --- a/stubs/Repositories/Mysql/mysql.getOneBy.stub +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -1,4 +1,4 @@ - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): null|{{ EntityName }} + public function getOneBy{{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): null|{{ EntityName }} { ${{ EntityVariableName }} = $this->newQuery() ->where('{{ ColumnName }}', ${{ AttributeName }}) diff --git a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub index 15b27a8..05b3d7a 100644 --- a/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getAllByIds', - 'id' => $ids, + 'function_name' => '{{ FunctionName }}', + '{{ ColumnNameSingle }}' => ${{ ColumnName }}, ]); $data = $this->redisRepository->get($cacheKey); if (is_null($data)) { - $data = $this->repository->getAllByIds($ids); + $data = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); } diff --git a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub index c9be1e6..19585ef 100644 --- a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getAllByIds', - 'id' => $ids, + 'function_name' => '{{ FunctionName }}', + '{{ ColumnNameSingle }}' => ${{ ColumnName }}, ]); $entity = $this->redisRepository->get($cacheKey); if (is_null($entity)) { - $entity = $this->repository->getAllByIds($ids); + $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $entity); } diff --git a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub index 5cfac3d..633800a 100644 --- a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ $entity = $this->redisRepository->get(); if (is_null($entity)) { - $entity = $this->repository->getAllByIds($id); + $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($entity); } diff --git a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub index d74c282..0a45aff 100644 --- a/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getAllByIds', - 'id' => $ids, + 'function_name' => '{{ FunctionName }}', + '{{ ColumnNameSingle }}' => ${{ ColumnName }}, ]); $data = $this->redisRepository->get($cacheKey); if (is_null($data)) { - $data = $this->repository->getAllByIds($ids); + $data = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); } diff --git a/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub index a079432..6f55216 100644 --- a/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneById', - 'id' => $id, + 'function_name' => '{{ FunctionName }}', + '{{ ColumnName }}' => ${{ ColumnName }}, ]); $data = $this->redisRepository->get($cacheKey); if (is_null($data)) { - $data = $this->repository->getOneById($id); + $data = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); } diff --git a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub index 5e260a0..4477fc3 100644 --- a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneById', - 'id' => $id, + 'function_name' => '{{ FunctionName }}', + '{{ ColumnName }}' => ${{ ColumnName }}, ]); $entity = $this->redisRepository->get($cacheKey); if (is_null($entity)) { - $entity = $this->repository->getOneById($id); + $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $entity); } diff --git a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub index 60b7609..22cdd14 100644 --- a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ $entity = $this->redisRepository->get(); if (is_null($entity)) { - $entity = $this->repository->getOneById($id); + $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($entity); } diff --git a/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub index aa606f6..2565c67 100644 --- a/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub @@ -1,11 +1,11 @@ $cacheKey = $this->redisRepository->makeKey([ - 'function_name' => 'getOneById', - 'id' => $id, + 'function_name' => '{{ FunctionName }}', + '{{ ColumnName }}' => ${{ ColumnName }}, ]); $data = $this->redisRepository->get($cacheKey); if (is_null($data)) { - $data = $this->repository->getOneById($id); + $data = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $data, Time::HALF_HOUR_BY_SECOND); } From b975e85563649b97ae05b6690eb3758bf54d2089 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Wed, 15 Nov 2023 21:22:51 +0330 Subject: [PATCH 33/86] use path instead of namespace --- src/Commands/BaseCommand.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 7592331..62abbb4 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -136,8 +136,8 @@ public function checkDatabasesExist() { $entityName = Str::singular(ucfirst(Str::camel($this->argument('table_name')))); - $mysql = config('repository.path.namespace.repositories') . "\\" . $entityName . "\\" . "MySql" . $entityName . "Repository.php"; - $redis = config('repository.path.namespace.repositories') . "\\" . $entityName . "\\" . "Redis" . $entityName . "Repository.php"; + $mysql = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . "MySql" . $entityName . "Repository.php"; + $redis = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . "Redis" . $entityName . "Repository.php"; if (!(file_exists($mysql) && file_exists($redis))) { $this->alert("First create the class databases!!!"); exit; From 2da4e57831992f67e0e61135f9264031239a0992 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 18 Nov 2023 19:15:41 +0330 Subject: [PATCH 34/86] change namespace to eghamat24 --- Readme.md | 4 ++-- composer.json | 6 +++--- src/Commands/BaseCommand.php | 4 ++-- src/Commands/MakeAll.php | 4 ++-- src/Commands/MakeEntity.php | 10 ++++----- src/Commands/MakeEnum.php | 8 +++---- src/Commands/MakeFactory.php | 8 +++---- src/Commands/MakeInterfaceRepository.php | 4 ++-- src/Commands/MakeMySqlRepository.php | 10 ++++----- src/Commands/MakeRedisRepository.php | 8 +++---- src/Commands/MakeRepository.php | 8 +++---- src/Commands/MakeResource.php | 8 +++---- src/Creators/BaseCreator.php | 8 +++---- src/Creators/CreatorEntity.php | 6 +++--- src/Creators/CreatorEnum.php | 4 ++-- src/Creators/CreatorFactory.php | 4 ++-- src/Creators/CreatorMySqlRepository.php | 6 +++--- src/Creators/CreatorRedisRepository.php | 19 ++++++++++------ src/Creators/CreatorRepository.php | 8 +++---- src/Creators/CreatorResource.php | 8 +++---- src/Creators/IClassCreator.php | 4 ++-- src/CustomMySqlQueries.php | 2 +- src/DatabaseRepositoryServiceProvider.php | 24 ++++++++++----------- src/Models/Entity/Entity.php | 2 +- src/Models/Enums/Enum.php | 2 +- src/Models/Enums/GriewFilterOperator.php | 2 +- src/Models/Factories/Factory.php | 4 ++-- src/Models/Factories/IFactory.php | 4 ++-- src/Models/Repositories/MySqlRepository.php | 8 +++---- src/Models/Repositories/RedisRepository.php | 2 +- src/Models/Resources/IResource.php | 4 ++-- src/Models/Resources/Resource.php | 4 ++-- stubs/Repositories/Mysql/mysql.class.stub | 2 +- stubs/Resources/resource.class.stub | 4 ++-- 34 files changed, 110 insertions(+), 103 deletions(-) diff --git a/Readme.md b/Readme.md index 9ae9cbd..c2c292a 100644 --- a/Readme.md +++ b/Readme.md @@ -3,7 +3,7 @@ ## Installation Use the following command to add this package to the composer development requirement. ```bash -composer require nanvaie/database-repository --dev +composer require eghamat24/database-repository --dev ``` ### Setup Laravel Repository @@ -17,7 +17,7 @@ Navigate to `app.php` in `bootstrap` folder and add the following line after ser ```php // snip if ($app->environment('local', 'testing')) { - $app->register(Nanvaie\DatabaseRepository\DatabaseRepositoryServiceProvider::class); + $app->register(Eghamat24\DatabaseRepository\DatabaseRepositoryServiceProvider::class); } // snip ``` diff --git a/composer.json b/composer.json index 0f060c3..5c36fb2 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "nanvaie/database-repository", + "name": "eghamat24/database-repository", "description": "Repository Pattern", "type": "library", "license": "MIT", @@ -20,13 +20,13 @@ }, "autoload": { "psr-4": { - "Nanvaie\\DatabaseRepository\\": "src/" + "Eghamat24\\DatabaseRepository\\": "src/" } }, "extra": { "laravel": { "providers": [ - "Nanvaie\\DatabaseRepository\\DatabaseRepositoryServiceProvider" + "Eghamat24\\DatabaseRepository\\DatabaseRepositoryServiceProvider" ] } } diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 62abbb4..2ac62bf 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -1,11 +1,11 @@ entityNamespace\\$this->entityName;", - "use Nanvaie\DatabaseRepository\Models\Factories\Factory;", + "use Eghamat24\DatabaseRepository\Models\Factories\Factory;", "use stdClass;" ]; diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index de5a61d..043c574 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -1,10 +1,10 @@ entityNamespace\\$this->entityName;", "use $this->factoryNamespace\\$this->factoryName;", "use Illuminate\Support\Collection;", - "use Nanvaie\DatabaseRepository\Models\Repositories\MySqlRepository;" + "use Eghamat24\DatabaseRepository\Models\Repositories\MySqlRepository;" ]; } public function getClassName(): string diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php index 85c80c5..4d86d33 100644 --- a/src/Creators/CreatorRedisRepository.php +++ b/src/Creators/CreatorRedisRepository.php @@ -1,9 +1,9 @@ redisRepositoryNamespace . '\\' . $this->entityName; } + public function createUses(): array { return [ - "use Nanvaie\DatabaseRepository\Models\Repositories\RedisRepository;", - "use App\Models\Repositories\Redis"."\\".$this->strategyName.";" + 'use Eghamat24\DatabaseRepository\Models\Repositories\RedisRepository;', + 'use Eghamat24\DatabaseRepository\Models\Repositories\CacheStrategies\\' . $this->strategyName . ';' ]; } + public function getClassName(): string { return $this->redisRepositoryName; } + public function getExtendSection(): string { return "extends RedisRepository"; } + public function createAttributs(): array { return []; } + public function createFunctions(): array { $constructStub = file_get_contents($this->repositoryStubsPath . 'construct_redis.stub'); $functions = []; $functions['__construct'] = $this->getConstructRedis($constructStub); - return $functions ; + return $functions; } + public function getConstructRedis(string $constructStub) { - return str_replace("{{Strategy}}",$this->strategyName,$constructStub); + return str_replace("{{Strategy}}", $this->strategyName, $constructStub); } } diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index b42bb43..d5b5467 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -1,12 +1,12 @@ entityNamespace\\$this->entityName;", - "use Nanvaie\DatabaseRepository\Models\Entity\Entity;", - "use Nanvaie\DatabaseRepository\Models\Resources\Resource;"]; + "use Eghamat24\DatabaseRepository\Models\Entity\Entity;", + "use Eghamat24\DatabaseRepository\Models\Resources\Resource;"]; } public function getClassName(): string diff --git a/src/Creators/IClassCreator.php b/src/Creators/IClassCreator.php index e41ce24..98521ed 100644 --- a/src/Creators/IClassCreator.php +++ b/src/Creators/IClassCreator.php @@ -1,9 +1,9 @@ Date: Sat, 18 Nov 2023 19:16:09 +0330 Subject: [PATCH 35/86] add cache strategies --- .../ClearableTemporaryCacheStrategy.php | 46 +++++++++++++++++++ .../CacheStrategies/QueryCacheStrategy.php | 45 ++++++++++++++++++ .../SingleKeyCacheStrategy.php | 35 ++++++++++++++ .../TemporaryCacheStrategy.php | 40 ++++++++++++++++ 4 files changed, 166 insertions(+) create mode 100644 src/Models/Repositories/CacheStrategies/ClearableTemporaryCacheStrategy.php create mode 100644 src/Models/Repositories/CacheStrategies/QueryCacheStrategy.php create mode 100644 src/Models/Repositories/CacheStrategies/SingleKeyCacheStrategy.php create mode 100644 src/Models/Repositories/CacheStrategies/TemporaryCacheStrategy.php diff --git a/src/Models/Repositories/CacheStrategies/ClearableTemporaryCacheStrategy.php b/src/Models/Repositories/CacheStrategies/ClearableTemporaryCacheStrategy.php new file mode 100644 index 0000000..c234467 --- /dev/null +++ b/src/Models/Repositories/CacheStrategies/ClearableTemporaryCacheStrategy.php @@ -0,0 +1,46 @@ +getCache()->tags($this->cacheTag)->get($cacheKey); + } + + /** + * @param string $cacheKey + * @param mixed $data + * @param $time + * @return mixed + */ + public function put(string $cacheKey, $data, $seconds) + { + $this->getCache()->tags($this->cacheTag)->put($cacheKey, $data, $seconds); + } + + /** + * @return mixed + */ + public function clear($cacheKey) + { + return $this->getCache()->tags($this->cacheTag)->forget($cacheKey); + } +} diff --git a/src/Models/Repositories/CacheStrategies/QueryCacheStrategy.php b/src/Models/Repositories/CacheStrategies/QueryCacheStrategy.php new file mode 100644 index 0000000..29baf04 --- /dev/null +++ b/src/Models/Repositories/CacheStrategies/QueryCacheStrategy.php @@ -0,0 +1,45 @@ +getCache()->tags($this->cacheTag)->get($cacheKey); + } + + /** + * @param string $cacheKey + * @param mixed $data + * @return mixed + */ + public function put(string $cacheKey, $data) + { + return $this->getCache()->tags($this->cacheTag)->forever($cacheKey, $data); + } + + /** + * @return mixed + */ + public function clear() + { + return $this->getCache()->tags($this->cacheTag)->flush(); + } +} \ No newline at end of file diff --git a/src/Models/Repositories/CacheStrategies/SingleKeyCacheStrategy.php b/src/Models/Repositories/CacheStrategies/SingleKeyCacheStrategy.php new file mode 100644 index 0000000..9f9b025 --- /dev/null +++ b/src/Models/Repositories/CacheStrategies/SingleKeyCacheStrategy.php @@ -0,0 +1,35 @@ +getCache()->forever($this->cacheKey, $entities); + } + + /** + * @return mixed + */ + public function get() + { + return $this->getCache()->get($this->cacheKey); + } + + /** + * @return mixed + */ + public function clear() + { + return $this->getCache()->forget($this->cacheKey); + } +} \ No newline at end of file diff --git a/src/Models/Repositories/CacheStrategies/TemporaryCacheStrategy.php b/src/Models/Repositories/CacheStrategies/TemporaryCacheStrategy.php new file mode 100644 index 0000000..dff9af7 --- /dev/null +++ b/src/Models/Repositories/CacheStrategies/TemporaryCacheStrategy.php @@ -0,0 +1,40 @@ +getCache()->tags($this->cacheTag)->get($cacheKey); + } + + /** + * @param string $cacheKey + * @param mixed $data + * @param DateInterval|DateTimeInterface|int $ttl + * @return bool + */ + public function put(string $cacheKey, mixed $data, DateInterval|DateTimeInterface|int $ttl): bool + { + return $this->getCache()->tags($this->cacheTag)->put($cacheKey, $data, $ttl); + } +} From f90203ba70f78eccc1caba68a2e42897f8c8e8ba Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 18 Nov 2023 19:20:14 +0330 Subject: [PATCH 36/86] change php to 8.1 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 5c36fb2..632114e 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ } ], "require": { - "php": "^8.0", + "php": "^8.1", "ext-pdo": "*", "ext-json": "*", "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0", From 18cf0c4895669070bb228985d0a2843ea03f7434 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 27 Nov 2023 12:17:09 +0330 Subject: [PATCH 37/86] refactor(Creator): spell fixed --- src/Creators/BaseCreator.php | 2 +- src/Creators/CreatorEntity.php | 3 +-- src/Creators/CreatorEnum.php | 2 +- src/Creators/CreatorFactory.php | 2 +- src/Creators/CreatorMySqlRepository.php | 2 +- src/Creators/CreatorRedisRepository.php | 2 +- src/Creators/CreatorRepository.php | 2 +- src/Creators/CreatorResource.php | 2 +- src/Creators/IClassCreator.php | 2 +- 9 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 20437d4..7eca2cd 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -26,7 +26,7 @@ public function __construct(IClassCreator $creator) public function createClass(string $filenameWithPath,BaseCommand $command):string { - $attributesArray = $this->creator->createAttributs(); + $attributesArray = $this->creator->createAttributes(); $functionsArray = $this->creator->createFunctions(); $usesArray = $this->creator->createUses(); diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index 92da447..5232e43 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -29,7 +29,7 @@ public function getExtendSection(): string return 'extends '.self::PARENT_NAME; } - public function createAttributs():array{ + public function createAttributes():array{ $columns = $this->columns; $entityStubsPath = $this->entityStubsPath; $detectForeignKeys = $this->detectForeignKeys; @@ -75,7 +75,6 @@ public function createUses(): array public function createFunctions():array { - $columns = $this->columns; $entityStubsPath = $this->entityStubsPath; $detectForeignKeys = $this->detectForeignKeys; diff --git a/src/Creators/CreatorEnum.php b/src/Creators/CreatorEnum.php index 5588fcc..1006073 100644 --- a/src/Creators/CreatorEnum.php +++ b/src/Creators/CreatorEnum.php @@ -18,7 +18,7 @@ public function __construct( } - public function createAttributs(): array + public function createAttributes(): array { $attributes = []; foreach ($this->enum as $_enum) { diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php index eb680ee..a7aea82 100644 --- a/src/Creators/CreatorFactory.php +++ b/src/Creators/CreatorFactory.php @@ -26,7 +26,7 @@ public function getNameSpace(): string return $this->factoryNamespace; } - public function createAttributs(): array + public function createAttributes(): array { // TODO: Implement createAttributs() method. return []; diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index 043c574..51026a2 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -48,7 +48,7 @@ public function getExtendSection(): string { return "extends MySqlRepository implements " . $this->interfaceName; } - public function createAttributs(): array + public function createAttributes(): array { return []; } diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php index 4d86d33..91edc8b 100644 --- a/src/Creators/CreatorRedisRepository.php +++ b/src/Creators/CreatorRedisRepository.php @@ -41,7 +41,7 @@ public function getExtendSection(): string return "extends RedisRepository"; } - public function createAttributs(): array + public function createAttributes(): array { return []; } diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index d5b5467..eefcbbc 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -99,7 +99,7 @@ public function getExtendSection(): string return 'implements ' . $this->interfaceName; } - public function createAttributs(): array + public function createAttributes(): array { $attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub'); $attributes = []; diff --git a/src/Creators/CreatorResource.php b/src/Creators/CreatorResource.php index 6473fdd..f07f4b0 100644 --- a/src/Creators/CreatorResource.php +++ b/src/Creators/CreatorResource.php @@ -46,7 +46,7 @@ public function getExtendSection(): string return 'extends Resource'; } - public function createAttributs(): array + public function createAttributes(): array { return []; } diff --git a/src/Creators/IClassCreator.php b/src/Creators/IClassCreator.php index 98521ed..b2c2e42 100644 --- a/src/Creators/IClassCreator.php +++ b/src/Creators/IClassCreator.php @@ -11,7 +11,7 @@ public function getNameSpace(): string; public function createUses(): array; public function getClassName(): string; public function getExtendSection(): string; - public function createAttributs(): array; + public function createAttributes(): array; public function createFunctions(): array; } From bda78680a1a78868ad34b81f6225019ce157c797 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 27 Nov 2023 12:17:58 +0330 Subject: [PATCH 38/86] style(CreatorResource): some indent change --- src/Creators/CreatorResource.php | 3 +-- stubs/Resources/resource.function.foreign.stub | 12 ++++++------ stubs/Resources/resource.function.getter.stub | 12 ++++++------ stubs/Resources/resource.getter.foreign.stub | 2 +- 4 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/Creators/CreatorResource.php b/src/Creators/CreatorResource.php index f07f4b0..bcc0daa 100644 --- a/src/Creators/CreatorResource.php +++ b/src/Creators/CreatorResource.php @@ -53,7 +53,6 @@ public function createAttributes(): array public function createFunctions(): array { - $getterStub = file_get_contents($this->resourceStubsPath . 'getter.default.stub'); $foreignGetterStub = file_get_contents($this->resourceStubsPath . 'getter.foreign.stub'); $foreignFunStub = file_get_contents($this->resourceStubsPath . 'function.foreign.stub'); @@ -61,7 +60,7 @@ public function createFunctions(): array $getters = ''; foreach ($this->columns as $_column) { - $getters .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)); + $getters .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)) . "\t\t\t"; } $foreignGetterFunctions = ''; diff --git a/stubs/Resources/resource.function.foreign.stub b/stubs/Resources/resource.function.foreign.stub index b774e84..4e0825d 100644 --- a/stubs/Resources/resource.function.foreign.stub +++ b/stubs/Resources/resource.function.foreign.stub @@ -1,6 +1,6 @@ -public function toArrayWithForeignKeys(${{ EntityVariableName }}): array -{ - return $this->toArray(${{ EntityVariableName }}) + [ - {{ ForeignGetterFunctions }} - ]; -} + public function toArrayWithForeignKeys(${{ EntityVariableName }}): array + { + return $this->toArray(${{ EntityVariableName }}) + [ + {{ ForeignGetterFunctions }} + ]; + } diff --git a/stubs/Resources/resource.function.getter.stub b/stubs/Resources/resource.function.getter.stub index 0ce2a7b..ced9819 100644 --- a/stubs/Resources/resource.function.getter.stub +++ b/stubs/Resources/resource.function.getter.stub @@ -1,6 +1,6 @@ -public function toArray(${{ EntityVariableName }}): array -{ - return [ - {{ Getters }} - ]; -} + public function toArray(${{ EntityVariableName }}): array + { + return [ + {{ Getters }} + ]; + } diff --git a/stubs/Resources/resource.getter.foreign.stub b/stubs/Resources/resource.getter.foreign.stub index 64404ce..abb8705 100644 --- a/stubs/Resources/resource.getter.foreign.stub +++ b/stubs/Resources/resource.getter.foreign.stub @@ -1 +1 @@ -'{{ AttributeName }}' => ${{ EntityVariableName }}->get{{ GetterName }}() ? (new {{ AttributeType }}Resource())->toArray(${{ EntityVariableName }}->get{{ GetterName }}()) : null, + '{{ AttributeName }}' => ${{ EntityVariableName }}->get{{ GetterName }}() ? (new {{ AttributeType }}Resource())->toArray(${{ EntityVariableName }}->get{{ GetterName }}()) : null, From c11eb4f3df7a8a836130acbeb185c64d60d1e189 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 27 Nov 2023 12:56:08 +0330 Subject: [PATCH 39/86] style(CreatorResource): bug fix space before to array function --- stubs/base.class.stub | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stubs/base.class.stub b/stubs/base.class.stub index 7bdbcdd..618ccc1 100644 --- a/stubs/base.class.stub +++ b/stubs/base.class.stub @@ -6,5 +6,5 @@ namespace {{ Namespace }}; class {{ ClassName }} {{ ExtendSection }} { - {{ Parameters }} {{ Functions }} + {{ Parameters }}{{ Functions }} } From e735727bed8489123fdb0086e0dae632ced0d4d6 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 27 Nov 2023 12:58:26 +0330 Subject: [PATCH 40/86] fix(interface stub): add enter --- stubs/Repositories/Interface/interface.class.stub | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/stubs/Repositories/Interface/interface.class.stub b/stubs/Repositories/Interface/interface.class.stub index 401663c..9ca3e56 100644 --- a/stubs/Repositories/Interface/interface.class.stub +++ b/stubs/Repositories/Interface/interface.class.stub @@ -6,4 +6,5 @@ use {{ EntityNamespace }}\{{ EntityName }}; use Illuminate\Support\Collection; interface {{ InterfaceRepositoryName }} -{} +{ +} \ No newline at end of file From 05725a059a40bbea92e65cb1e94a75e93b2f5b49 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 27 Nov 2023 13:02:59 +0330 Subject: [PATCH 41/86] style: reformat --- src/Commands/MakeAll.php | 6 +- src/Commands/MakeEntity.php | 11 +-- src/Commands/MakeEnum.php | 18 ++--- src/Commands/MakeFactory.php | 12 ++-- src/Commands/MakeInterfaceRepository.php | 2 +- src/Commands/MakeMySqlRepository.php | 10 +-- src/Commands/MakeRedisRepository.php | 12 ++-- src/Commands/MakeRepository.php | 16 ++--- src/Commands/MakeResource.php | 14 ++-- src/Creators/BaseCreator.php | 78 ++++++++++----------- src/Creators/CreatorEntity.php | 45 ++++++------ src/Creators/CreatorEnum.php | 26 +++---- src/Creators/CreatorFactory.php | 2 +- src/Creators/CreatorMySqlRepository.php | 16 +++-- src/Creators/CreatorRepository.php | 38 ++++++---- src/Creators/IClassCreator.php | 5 ++ src/CustomMySqlQueries.php | 8 +-- src/Models/Entity/Entity.php | 2 +- src/Models/Repositories/MySqlRepository.php | 2 +- src/Models/Repositories/RedisRepository.php | 2 + src/Models/Resources/Resource.php | 1 - 21 files changed, 174 insertions(+), 152 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 1769f99..88218ab 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -48,7 +48,7 @@ public function handle() $delete = $this->option('delete'); $detectForeignKeys = $this->option('foreign-keys'); $addToGit = $this->option('add-to-git'); - $strategy=$this->option('strategy_name'); + $strategy = $this->option('strategy_name'); if ($this->option('all-tables')) { $tableNames = $this->getAllTableNames()->pluck('TABLE_NAME'); } else if ($this->option('table_names')) { @@ -72,8 +72,8 @@ public function handle() $this->call('repository:make-resource', $arguments); $this->call('repository:make-interface-repository', $arguments); $this->call('repository:make-mysql-repository', $arguments); - $this->call('repository:make-redis-repository',[...$arguments,'strategy'=>$strategy]); - $this->call('repository:make-repository', [...$arguments,'strategy'=>$strategy,'selected_db'=>$this->selectedDb]); + $this->call('repository:make-redis-repository', [...$arguments, 'strategy' => $strategy]); + $this->call('repository:make-repository', [...$arguments, 'strategy' => $strategy, 'selected_db' => $this->selectedDb]); } } } diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index eae35e0..8b39040 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -12,6 +12,7 @@ class MakeEntity extends BaseCommand { use CustomMySqlQueries; + /** * The name and signature of the console command. * @@ -36,14 +37,14 @@ class MakeEntity extends BaseCommand public function handle(): void { $this->setArguments(); - $filenameWithPath = $this->relativeEntitiesPath . $this->entityName.'.php'; + $filenameWithPath = $this->relativeEntitiesPath . $this->entityName . '.php'; - $this->checkDelete($filenameWithPath,$this->entityName,"Entity"); + $this->checkDelete($filenameWithPath, $this->entityName, "Entity"); $this->checkDirectory($this->relativeEntitiesPath); - $this->checkClassExist($this->entityNamespace,$this->entityName,"Entity"); + $this->checkClassExist($this->entityNamespace, $this->entityName, "Entity"); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); @@ -57,7 +58,7 @@ public function handle(): void $this->entityStubsPath ); $creator = new BaseCreator($entityCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); + $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $this->entityName, $baseContent); diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 1621967..48d1939 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -34,29 +34,29 @@ public function handle(): void $this->setArguments(); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); $enums = []; foreach ($columns as $_column) { if ($_column->DATA_TYPE == 'enum') { - $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME)."Enum"; + $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME) . "Enum"; $enums[$enumClassName] = array_filter(explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE))); - $filenameWithPath = $this->relativeEnumsPath . $enumClassName.'.php'; - $this->checkDelete($filenameWithPath,$enumClassName,"Enum"); + $filenameWithPath = $this->relativeEnumsPath . $enumClassName . '.php'; + $this->checkDelete($filenameWithPath, $enumClassName, "Enum"); } } - $attributeStub = file_get_contents($this->enumStubPath.'attribute.stub'); + $attributeStub = file_get_contents($this->enumStubPath . 'attribute.stub'); foreach ($enums as $enumName => $enum) { - $filenameWithPath = $this->relativeEnumsPath . $enumName.'.php'; + $filenameWithPath = $this->relativeEnumsPath . $enumName . '.php'; $this->checkDirectory($this->enumNamespace); - $this->checkClassExist($this->relativeEnumsPath,$enumName,"Enum"); + $this->checkClassExist($this->relativeEnumsPath, $enumName, "Enum"); - $enumCreator = new CreatorEnum($columns,$attributeStub,$enum,$enumName,$this->enumNamespace); + $enumCreator = new CreatorEnum($columns, $attributeStub, $enum, $enumName, $this->enumNamespace); $creator = new BaseCreator($enumCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); + $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $enumName, $baseContent); } diff --git a/src/Commands/MakeFactory.php b/src/Commands/MakeFactory.php index e3558a1..756c737 100644 --- a/src/Commands/MakeFactory.php +++ b/src/Commands/MakeFactory.php @@ -44,20 +44,20 @@ public function handle(): void { $this->setArguments(); - $filenameWithPath = $this->relativeFactoriesPath . $this->factoryName.'.php'; + $filenameWithPath = $this->relativeFactoriesPath . $this->factoryName . '.php'; - $this->checkDelete($filenameWithPath,$this->entityName,"Factory"); + $this->checkDelete($filenameWithPath, $this->entityName, "Factory"); $this->checkDirectory($this->relativeFactoriesPath); - $this->checkClassExist($this->factoryNamespace,$this->entityName,"Factory"); + $this->checkClassExist($this->factoryNamespace, $this->entityName, "Factory"); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } - $baseContent = file_get_contents($this->factoryStubsPath.'class.stub'); + $baseContent = file_get_contents($this->factoryStubsPath . 'class.stub'); $factoryCreator = new CreatorFactory( $columns, @@ -69,7 +69,7 @@ public function handle(): void $this->factoryName, $baseContent); $creator = new BaseCreator($factoryCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); + $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $this->factoryName, $baseContent); } diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index 815b198..675dc61 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -79,7 +79,7 @@ public function handle(): void $columnInfo = collect($columnsInfo)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)), -2, 0); - if($index->Non_unique == 1) { + if ($index->Non_unique == 1) { $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getAllStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)), -2, 0); } } diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index 155c867..30a9ae3 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -39,12 +39,12 @@ class MakeMySqlRepository extends BaseCommand public function handle(): void { $this->setArguments(); - $filenameWithPath = $this->relativeMysqlRepositoryPath . $this->mysqlRepositoryName.'.php'; - $this->checkDelete($filenameWithPath,$this->mysqlRepositoryName,"MySql Repository"); + $filenameWithPath = $this->relativeMysqlRepositoryPath . $this->mysqlRepositoryName . '.php'; + $this->checkDelete($filenameWithPath, $this->mysqlRepositoryName, "MySql Repository"); $this->checkDirectory($this->relativeMysqlRepositoryPath); - $this->checkClassExist($this->repositoryNamespace,$this->mysqlRepositoryName,"MySql Repository"); + $this->checkClassExist($this->repositoryNamespace, $this->mysqlRepositoryName, "MySql Repository"); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); $mysqlRepoCreator = new CreatorMySqlRepository($columns, $this->tableName, @@ -60,7 +60,7 @@ public function handle(): void $this->detectForeignKeys ); $creator = new BaseCreator($mysqlRepoCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); + $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $this->mysqlRepositoryName, $baseContent); } diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index 812763f..3fb49cc 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -40,25 +40,25 @@ public function handle() $this->checkStrategyName(); $this->setArguments(); - $redisRepositoryName = "Redis$this->entityName"."Repository"; + $redisRepositoryName = "Redis$this->entityName" . "Repository"; $redisRepositoryNamespace = config('repository.path.namespace.repositories'); $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $filenameWithPath = $relativeRedisRepositoryPath . $redisRepositoryName . '.php'; - $this->checkDelete($filenameWithPath,$redisRepositoryName,"Redis Repository"); + $this->checkDelete($filenameWithPath, $redisRepositoryName, "Redis Repository"); $this->checkDirectory($relativeRedisRepositoryPath); - $this->checkClassExist($this->repositoryNamespace,$redisRepositoryName,"Redis Repository"); + $this->checkClassExist($this->repositoryNamespace, $redisRepositoryName, "Redis Repository"); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); if ($this->detectForeignKeys) { $foreignKeys = $this->extractForeignKeys($this->tableName); } $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); - $mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName,$redisRepositoryNamespace, $this->entityName,$this->strategyName,$repositoryStubsPath); + $mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName, $redisRepositoryNamespace, $this->entityName, $this->strategyName, $repositoryStubsPath); $creator = new BaseCreator($mysqlRepoCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); + $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $redisRepositoryName, $baseContent); } } diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index a0fd857..d764fef 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -41,20 +41,20 @@ public function handle(): void $this->checkStrategyName(); $this->setArguments(); - $repositoryName = $this->entityName.'Repository'; + $repositoryName = $this->entityName . 'Repository'; // $sqlRepositoryName = 'MySql'.$this->entityName.'Repository'; - $sqlRepositoryName = ucwords($this->selectedDb).$this->entityName.'Repository'; + $sqlRepositoryName = ucwords($this->selectedDb) . $this->entityName . 'Repository'; $sqlRepositoryVariable = 'repository'; - $redisRepositoryVariable ='redisRepository'; - $redisRepositoryName = 'Redis'.$this->entityName.'Repository'; + $redisRepositoryVariable = 'redisRepository'; + $redisRepositoryName = 'Redis' . $this->entityName . 'Repository'; $relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); $filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php'; - $this->checkDelete($filenameWithPath,$repositoryName,"Repository"); + $this->checkDelete($filenameWithPath, $repositoryName, "Repository"); $this->checkDirectory($relativeRepositoryPath); - $this->checkClassExist($this->repositoryNamespace,$repositoryName,"Repository"); + $this->checkClassExist($this->repositoryNamespace, $repositoryName, "Repository"); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); $RepoCreator = new CreatorRepository( $columns, $sqlRepositoryVariable, @@ -74,7 +74,7 @@ public function handle(): void $this->strategyName ); $creator = new BaseCreator($RepoCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); + $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $repositoryName, $baseContent); } } diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index 0db3c56..9ab6d31 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -38,18 +38,18 @@ class MakeResource extends BaseCommand public function handle(): void { $this->setArguments(); - $resourceName = $this->entityName."Resource"; + $resourceName = $this->entityName . "Resource"; $resourceNamespace = config('repository.path.namespace.resources'); $relativeResourcesPath = config('repository.path.relative.resources'); $resourceStubsPath = __DIR__ . '/../../' . config('repository.path.stub.resources'); - $filenameWithPath = $relativeResourcesPath . $resourceName.'.php'; + $filenameWithPath = $relativeResourcesPath . $resourceName . '.php'; - $this->checkDelete($filenameWithPath,$resourceName,"Resource"); + $this->checkDelete($filenameWithPath, $resourceName, "Resource"); $this->checkDirectory($relativeResourcesPath); - $this->checkClassExist($resourceNamespace,$resourceName,"Resource"); + $this->checkClassExist($resourceNamespace, $resourceName, "Resource"); $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns,$this->tableName); + $this->checkEmpty($columns, $this->tableName); $RepoCreator = new CreatorResource($columns, $this->tableName, @@ -61,8 +61,8 @@ public function handle(): void $this->detectForeignKeys, $this->entityVariableName); $creator = new BaseCreator($RepoCreator); - $baseContent = $creator->createClass($filenameWithPath,$this); - $this->finalized($filenameWithPath,$resourceName,$baseContent); + $baseContent = $creator->createClass($filenameWithPath, $this); + $this->finalized($filenameWithPath, $resourceName, $baseContent); } diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 7eca2cd..25503cb 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -12,37 +12,37 @@ class BaseCreator extends BaseCommand { const ENUM_TYPE = 'enum'; const CLASS_TYPE = 'class'; - const ALL_OPTIONS = ['Current','New','Always keep current','Always replace with new']; + const ALL_OPTIONS = ['Current', 'New', 'Always keep current', 'Always replace with new']; const QUERY_CACHE_STRATEGY = 'QueryCacheStrategy'; const SINGLE_KEY_CACHE_STRATEGY = 'SingleKeyCacheStrategy'; private $creator; - private null|string $choice=null; + private null|string $choice = null; public function __construct(IClassCreator $creator) { $this->creator = $creator; } - public function createClass(string $filenameWithPath,BaseCommand $command):string + public function createClass(string $filenameWithPath, BaseCommand $command): string { $attributesArray = $this->creator->createAttributes(); $functionsArray = $this->creator->createFunctions(); $usesArray = $this->creator->createUses(); $specificPattern = "/(?public|private|protected)\sfunction\s+(?\w+)\s*\((?[^\)]*)\)\s*:?\s*(?.{0,100})\s*(?\{(?:[^{}]+|(?&body))*\})/"; - $functionsArray = $this->checkDiffrence($filenameWithPath,$functionsArray,$command,$specificPattern); + $functionsArray = $this->checkDiffrence($filenameWithPath, $functionsArray, $command, $specificPattern); $generalPattern = "/class\s*[^$]*\{(?[^}]*)((public|protected|private) function |})/isU"; $specificPattern = '/(public|protected|private) [^\s]* \$*(?[^\s;\=]*)\s*[^;]*;/is'; - $attributesArray = $this->checkDiffrence($filenameWithPath,$attributesArray,$command,$specificPattern,$generalPattern); + $attributesArray = $this->checkDiffrence($filenameWithPath, $attributesArray, $command, $specificPattern, $generalPattern); - $attributes = trim(implode("\n\t",$attributesArray)); - $functions = trim(implode("\n",$functionsArray)); - $functions = (!empty($attributes)) ? "\n\n\t".$functions : $functions; - $uses = implode(PHP_EOL,$usesArray); + $attributes = trim(implode("\n\t", $attributesArray)); + $functions = trim(implode("\n", $functionsArray)); + $functions = (!empty($attributes)) ? "\n\n\t" . $functions : $functions; + $uses = implode(PHP_EOL, $usesArray); $type = (isset($this->creator->enum)) ? self::ENUM_TYPE : self::CLASS_TYPE; - $basePath = __DIR__ . "/../../stubs/base.$type.stub" ; + $basePath = __DIR__ . "/../../stubs/base.$type.stub"; $this->creator->baseContent = str_replace(['{{ Namespace }}', '{{ UseSection }}', '{{ ClassName }}', '{{ ExtendSection }}', '{{ Parameters }}', '{{ Functions }}', '{{ CacheTag }}'], [ @@ -59,43 +59,43 @@ public function createClass(string $filenameWithPath,BaseCommand $command):strin return $this->creator->baseContent; } - public function checkDiffrence(string $filenameWithPath,array $newParamsArray,BaseCommand $command,string $specificPattern,string $generalPattern='/(?.*)/is'): array + public function checkDiffrence(string $filenameWithPath, array $newParamsArray, BaseCommand $command, string $specificPattern, string $generalPattern = '/(?.*)/is'): array { if (file_exists($filenameWithPath)) { $file = file_get_contents($filenameWithPath); - if(preg_match($generalPattern, $file, $matches)){ - if(preg_match_all($specificPattern,$matches['main_part'],$attributMatches)){ - for ($i=0; $igetChoice(),self::ALL_OPTIONS)<2) + if (preg_match($generalPattern, $file, $matches)) { + if (preg_match_all($specificPattern, $matches['main_part'], $attributMatches)) { + for ($i = 0; $i < count($attributMatches['name']); $i++) { + if (array_search($this->getChoice(), self::ALL_OPTIONS) < 2) $this->setChoice(null); - if(!isset($newParamsArray[$attributMatches['name'][$i]])){ + if (!isset($newParamsArray[$attributMatches['name'][$i]])) { $newParamsArray[$attributMatches['name'][$i]] = ''; } $attr = $newParamsArray[$attributMatches['name'][$i]]; - if(preg_replace('/\s+/', '', $attr)===preg_replace('/\s+/', '', $attributMatches[0][$i])){ - $command->info("There is no diffrence between '". $attributMatches['name'][$i] ."' "); - }else{ - $command->warn("WARN: '". $attributMatches['name'][$i]."'s are not the same"); - if(is_null($this->getChoice()) && array_search($this->getChoice(),self::ALL_OPTIONS)<2){ - // $command->table( ['Current','new'], [['Current'=>trim($attributMatches[0][$i]),'New'=>trim($attr)]],'default'); - $command->line("######################## CURRENT #########################",'fg=magenta'); - $command->line(trim($attributMatches[0][$i]),'fg=magenta'); - $command->line("##########################################################",'fg=magenta'); - $command->line(" ",'fg=magenta'); - $command->line("########################## NEW ###########################",'fg=cyan'); - $command->line(trim($attr),'fg=cyan'); - $command->line("##########################################################",'fg=cyan'); - $this->setChoice($command->choice('Choose one version',self::ALL_OPTIONS,0)); - if(array_search($this->getChoice(),self::ALL_OPTIONS)%2==0 ){ - $newParamsArray[$attributMatches['name'][$i]]=trim($attributMatches[0][$i]).PHP_EOL; - $command->warn("Action: Current version selected for '". $attributMatches['name'][$i] ."', "); + if (preg_replace('/\s+/', '', $attr) === preg_replace('/\s+/', '', $attributMatches[0][$i])) { + $command->info("There is no diffrence between '" . $attributMatches['name'][$i] . "' "); + } else { + $command->warn("WARN: '" . $attributMatches['name'][$i] . "'s are not the same"); + if (is_null($this->getChoice()) && array_search($this->getChoice(), self::ALL_OPTIONS) < 2) { + // $command->table( ['Current','new'], [['Current'=>trim($attributMatches[0][$i]),'New'=>trim($attr)]],'default'); + $command->line("######################## CURRENT #########################", 'fg=magenta'); + $command->line(trim($attributMatches[0][$i]), 'fg=magenta'); + $command->line("##########################################################", 'fg=magenta'); + $command->line(" ", 'fg=magenta'); + $command->line("########################## NEW ###########################", 'fg=cyan'); + $command->line(trim($attr), 'fg=cyan'); + $command->line("##########################################################", 'fg=cyan'); + $this->setChoice($command->choice('Choose one version', self::ALL_OPTIONS, 0)); + if (array_search($this->getChoice(), self::ALL_OPTIONS) % 2 == 0) { + $newParamsArray[$attributMatches['name'][$i]] = trim($attributMatches[0][$i]) . PHP_EOL; + $command->warn("Action: Current version selected for '" . $attributMatches['name'][$i] . "', "); } - }elseif (array_search($this->getChoice(),self::ALL_OPTIONS)==2){ - $newParamsArray[$attributMatches['name'][$i]]=trim($attributMatches[0][$i]).PHP_EOL; - $command->warn("Action: Current version selected for '". $attributMatches['name'][$i] ."', "); - }else{ - $command->warn("Action: New version replaced for '". $attributMatches['name'][$i] ."', "); + } elseif (array_search($this->getChoice(), self::ALL_OPTIONS) == 2) { + $newParamsArray[$attributMatches['name'][$i]] = trim($attributMatches[0][$i]) . PHP_EOL; + $command->warn("Action: Current version selected for '" . $attributMatches['name'][$i] . "', "); + } else { + $command->warn("Action: New version replaced for '" . $attributMatches['name'][$i] . "', "); } } } @@ -107,6 +107,6 @@ public function checkDiffrence(string $filenameWithPath,array $newParamsArray,Ba private function setCacheTag(BaseCommand $command) { - return (isset($command->strategyName) && in_array($command->strategyName, [self::QUERY_CACHE_STRATEGY, self::SINGLE_KEY_CACHE_STRATEGY])) ? "'$command->tableName'" : "''"; + return (isset($command->strategyName) && in_array($command->strategyName, [self::QUERY_CACHE_STRATEGY, self::SINGLE_KEY_CACHE_STRATEGY])) ? "'$command->tableName'" : "''"; } } diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index 5232e43..fd51119 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -15,21 +15,22 @@ class CreatorEntity implements IClassCreator public function __construct( public Collection $columns, - public string $detectForeignKeys, - public string $tableName, - public string $entityName, - public string $entityNamespace, - public string $entityStubsPath) + public string $detectForeignKeys, + public string $tableName, + public string $entityName, + public string $entityNamespace, + public string $entityStubsPath) { } public function getExtendSection(): string { - return 'extends '.self::PARENT_NAME; + return 'extends ' . self::PARENT_NAME; } - public function createAttributes():array{ + public function createAttributes(): array + { $columns = $this->columns; $entityStubsPath = $this->entityStubsPath; $detectForeignKeys = $this->detectForeignKeys; @@ -46,7 +47,7 @@ public function createAttributes():array{ $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( $entityStubsPath, - $_column->COLUMN_NAME.(!in_array($_column->COLUMN_DEFAULT, [null, 'NULL']) ? ' = '.$defaultValue : ''), + $_column->COLUMN_NAME . (!in_array($_column->COLUMN_DEFAULT, [null, 'NULL']) ? ' = ' . $defaultValue : ''), ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType ); } @@ -73,7 +74,7 @@ public function createUses(): array return ["use Eghamat24\DatabaseRepository\Models\Entity\Entity;"]; } - public function createFunctions():array + public function createFunctions(): array { $columns = $this->columns; $entityStubsPath = $this->entityStubsPath; @@ -83,14 +84,14 @@ public function createFunctions():array foreach ($columns as $_column) { $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); - $settersAndGetters['get'.ucwords($_column->COLUMN_NAME)] = + $settersAndGetters['get' . ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_column->COLUMN_NAME, ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, 'getter' ); - $settersAndGetters['set'.ucwords($_column->COLUMN_NAME)] = + $settersAndGetters['set' . ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_column->COLUMN_NAME, @@ -104,20 +105,20 @@ public function createFunctions():array // Create Additional Setters and Getters from Foreign keys foreach ($foreignKeys as $_foreignKey) { - $settersAndGetters['get'.ucwords($_foreignKey->COLUMN_NAME)] = + $settersAndGetters['get' . ucwords($_foreignKey->COLUMN_NAME)] = $this->writeAccessors( $entityStubsPath, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE, 'getter' ); - $settersAndGetters['set'.ucwords($_foreignKey->COLUMN_NAME)] = - $this->writeAccessors( - $entityStubsPath, - $_foreignKey->VARIABLE_NAME, - $_foreignKey->ENTITY_DATA_TYPE, - 'setter' - ); + $settersAndGetters['set' . ucwords($_foreignKey->COLUMN_NAME)] = + $this->writeAccessors( + $entityStubsPath, + $_foreignKey->VARIABLE_NAME, + $_foreignKey->ENTITY_DATA_TYPE, + 'setter' + ); } } return $settersAndGetters; @@ -125,15 +126,15 @@ public function createFunctions():array private function writeAttribute(string $entityStubsPath, string $attributeName, string $attributeType): string { - $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); + $attributeStub = file_get_contents($entityStubsPath . 'attribute.stub'); return str_replace(['{{ AttributeType }}', '{{ AttributeName }}'], [$attributeType, $attributeName], $attributeStub); } - private function writeAccessors(string $entityStubsPath, string $attributeName, string $attributeType,string $type): string + private function writeAccessors(string $entityStubsPath, string $attributeName, string $attributeType, string $type): string { - $accessorStub = file_get_contents($entityStubsPath.$type.'.stub'); + $accessorStub = file_get_contents($entityStubsPath . $type . '.stub'); return str_replace(['{{ AttributeType }}', '{{ AttributeName }}', '{{ GetterName }}', '{{ SetterName }}'], [$attributeType, $attributeName, ucfirst($attributeName), ucfirst($attributeName)], $accessorStub); diff --git a/src/Creators/CreatorEnum.php b/src/Creators/CreatorEnum.php index 1006073..7adc139 100644 --- a/src/Creators/CreatorEnum.php +++ b/src/Creators/CreatorEnum.php @@ -9,10 +9,10 @@ class CreatorEnum implements IClassCreator { public function __construct( public Collection $columns, - public $attributeStub, - public $enum, - public $enumName, - public $enumNamespace + public $attributeStub, + public $enum, + public $enumName, + public $enumNamespace ) { @@ -20,15 +20,15 @@ public function __construct( public function createAttributes(): array { - $attributes = []; - foreach ($this->enum as $_enum) { - $attributes[strtoupper($_enum)] = $this->writeAttribute( - $this->attributeStub, - strtoupper($_enum), - $_enum - ); - } - return $attributes; + $attributes = []; + foreach ($this->enum as $_enum) { + $attributes[strtoupper($_enum)] = $this->writeAttribute( + $this->attributeStub, + strtoupper($_enum), + $_enum + ); + } + return $attributes; } public function createFunctions(): array diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php index a7aea82..58d736c 100644 --- a/src/Creators/CreatorFactory.php +++ b/src/Creators/CreatorFactory.php @@ -37,7 +37,7 @@ public function createFunctions(): array $setterStub = file_get_contents($this->factoryStubsPath . 'setter.stub'); $setterFunctions = ''; foreach ($this->columns as $_column) { - $setterFunctions .= trim($this->writeSetter($setterStub, $_column->COLUMN_NAME))."\n\t\t"; + $setterFunctions .= trim($this->writeSetter($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; } return ['makeEntityFromStdClass' => str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityVariableName }}'], diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index 51026a2..725333a 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -27,10 +27,12 @@ public function __construct( ) { } + public function getNameSpace(): string { return $this->repositoryNamespace . '\\' . $this->entityName; } + public function createUses(): array { return [ @@ -40,18 +42,22 @@ public function createUses(): array "use Eghamat24\DatabaseRepository\Models\Repositories\MySqlRepository;" ]; } + public function getClassName(): string { return $this->mysqlRepositoryName; } + public function getExtendSection(): string { return "extends MySqlRepository implements " . $this->interfaceName; } + public function createAttributes(): array { return []; } + public function createFunctions(): array { @@ -81,7 +87,7 @@ public function createFunctions(): array $indx = 'getOneBy' . ucfirst(Str::camel($index->COLUMN_NAME)); $functions[$indx] = $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)); - if($index->Non_unique == 1) { + if ($index->Non_unique == 1) { $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); $functions[$indx] = $this->writeGetAllFunction($getAllStub, $index->COLUMN_NAME, $this->entityName); } @@ -102,10 +108,10 @@ public function createFunctions(): array // Create "create" function foreach ($this->columns as $_column) { if (!in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { - $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME))."\n\t\t\t\t"; + $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME)) . "\n\t\t\t\t"; } if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { - $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME))."\n\t\t"; + $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; } } $createFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ SetterFunctions }}"], @@ -120,10 +126,10 @@ public function createFunctions(): array // Create "update" function foreach ($this->columns as $_column) { if (!in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { - $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME))."\n\t\t\t\t"; + $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME)) . "\n\t\t\t\t"; } if ($_column->COLUMN_NAME === 'updated_at') { - $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME))."\n\t\t"; + $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; } } $updateFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ UpdateFieldSetter }}"], diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index eefcbbc..9b93b5c 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -38,7 +38,7 @@ public function __construct( private function writeFunction(string $functionStub, string $functionName, string $columnName, string $attributeType): string { $columnNameSingle = Str::camel($columnName); - + if ($functionName === 'getOneBy') { $functionReturnType = 'null|{{ EntityName }}'; $functionName .= ucfirst(Str::camel($columnName)); @@ -59,19 +59,21 @@ private function writeFunction(string $functionStub, string $functionName, strin $redisCashFunction = str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ ColumnNameSingle }}'], [$functionName, $columnName, $columnNameSingle], $redisCashFunction); - return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}','{{redisFunction}}'], + return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}', '{{redisFunction}}'], [$functionName, $attributeType, Str::camel($columnName), $functionReturnType, $redisCashFunction], $functionStub); } + private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable, string $sqlRepositoryName): string { - return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'], + return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'], [$sqlRepositoryVariable, $sqlRepositoryName], $attributeStub); } - public function writeRedisAttribute(string $attributeStub,string $redisRepositoryVariable,string $redisRepositoryName):string + + public function writeRedisAttribute(string $attributeStub, string $redisRepositoryVariable, string $redisRepositoryName): string { - return str_replace(['{{ RedisRepositoryVariable }}', '{{ RedisRepositoryName }}'], + return str_replace(['{{ RedisRepositoryVariable }}', '{{ RedisRepositoryName }}'], [$redisRepositoryVariable, $redisRepositoryName], $attributeStub); } @@ -103,8 +105,8 @@ public function createAttributes(): array { $attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub'); $attributes = []; - $attributes['repository'] = 'private '.$this->interfaceName.' $repository;'; - $attributes['redisRepository'] = 'private '.$this->redisRepositoryName.' $redisRepository;'; + $attributes['repository'] = 'private ' . $this->interfaceName . ' $repository;'; + $attributes['redisRepository'] = 'private ' . $this->redisRepositoryName . ' $redisRepository;'; return $attributes; } @@ -126,7 +128,7 @@ public function createFunctions(): array $fun_name = ucfirst(Str::camel($index->COLUMN_NAME)); $functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)); - if($index->Non_unique == 1) { + if ($index->Non_unique == 1) { $fun_name = ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); $functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $index->COLUMN_NAME, 'array'); } @@ -155,27 +157,31 @@ public function createFunctions(): array } return $functions; } + public function getConstruct(string $setterSqlStub, string $constructStub) { - return str_replace("{{ Setters }}", trim($this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName,$this->redisRepositoryVariable,$this->redisRepositoryName)), $constructStub); + return str_replace("{{ Setters }}", trim($this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName, $this->redisRepositoryVariable, $this->redisRepositoryName)), $constructStub); } + public function getConstructRedis(string $setterSqlStub, string $constructStub) { - return str_replace("{{ Setters }}", trim($this->writeRedisAttribute($setterSqlStub,$this->redisRepositoryVariable,$this->redisRepositoryName)), $constructStub); + return str_replace("{{ Setters }}", trim($this->writeRedisAttribute($setterSqlStub, $this->redisRepositoryVariable, $this->redisRepositoryName)), $constructStub); } + private function getRedisCashFunctionGetOneBy($strategyName) { - $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/getOneBy/base.'; + $repositoryRedisStubsPath = __DIR__ . '/../../' . 'stubs/Repositories/Redis/getOneBy/base.'; return match ($strategyName) { 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), 'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'), 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), - }; + }; } + private function getRedisCashFunctionGetAllBy($strategyName) { - $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/getAllBy/base.'; + $repositoryRedisStubsPath = __DIR__ . '/../../' . 'stubs/Repositories/Redis/getAllBy/base.'; return match ($strategyName) { 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), @@ -183,9 +189,10 @@ private function getRedisCashFunctionGetAllBy($strategyName) 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), }; } + private function getRedisCashFunctionCreate($strategyName) { - $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/create/base.'; + $repositoryRedisStubsPath = __DIR__ . '/../../' . 'stubs/Repositories/Redis/create/base.'; return match ($strategyName) { 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), @@ -193,9 +200,10 @@ private function getRedisCashFunctionCreate($strategyName) 'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'temporary_cache_strategy.stub'), }; } + private function getRedisCashFunctionUpdate($strategyName) { - $repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/update/base.'; + $repositoryRedisStubsPath = __DIR__ . '/../../' . 'stubs/Repositories/Redis/update/base.'; return match ($strategyName) { 'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'), 'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'), diff --git a/src/Creators/IClassCreator.php b/src/Creators/IClassCreator.php index b2c2e42..2099cc8 100644 --- a/src/Creators/IClassCreator.php +++ b/src/Creators/IClassCreator.php @@ -8,10 +8,15 @@ interface IClassCreator { public function getNameSpace(): string; + public function createUses(): array; + public function getClassName(): string; + public function getExtendSection(): string; + public function createAttributes(): array; + public function createFunctions(): array; } diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index e57ca20..2d2f5f2 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -97,25 +97,25 @@ public function extractIndexes(string $tableName): Collection $indexes = DB::table('INFORMATION_SCHEMA.KEY_COLUMN_USAGE') ->where('TABLE_SCHEMA', config('database.connections.mysql.database')) ->where('TABLE_NAME', $tableName) - ->where('CONSTRAINT_NAME', '!=' ,'PRIMARY') + ->where('CONSTRAINT_NAME', '!=', 'PRIMARY') ->whereNull('REFERENCED_TABLE_NAME') ->orderBy('ORDINAL_POSITION') ->get(); $indexesData = DB::select("SHOW INDEX FROM $tableName WHERE Key_name != 'PRIMARY'"); - + collect($indexes)->each(function ($index) use ($indexesData) { $indexesData = collect($indexesData)->where('Column_name', $index->COLUMN_NAME)->first(); $index->Non_unique = $indexesData->Non_unique; $index->Index_type = $indexesData->Index_type; }); - + return $indexes; } public function getDataType(string $columnType, string $dataType): string { - if(array_key_exists($columnType, $this->columnTypes)) { + if (array_key_exists($columnType, $this->columnTypes)) { return $this->columnTypes[$columnType]; } diff --git a/src/Models/Entity/Entity.php b/src/Models/Entity/Entity.php index a26b471..0e3d0a4 100644 --- a/src/Models/Entity/Entity.php +++ b/src/Models/Entity/Entity.php @@ -100,7 +100,7 @@ public function changedAttributesName(): array $changedAttributes = []; $attributes = $this->toArray(); foreach ($attributes as $key => $value) { - if (isset($this->originals[$key]) && $value !== $this->originals[$key] && ! ((is_array($this->originals[$key]) || is_object($this->originals[$key])))) { + if (isset($this->originals[$key]) && $value !== $this->originals[$key] && !((is_array($this->originals[$key]) || is_object($this->originals[$key])))) { $changedAttributes[] = $key; } } diff --git a/src/Models/Repositories/MySqlRepository.php b/src/Models/Repositories/MySqlRepository.php index 916ddd4..366b2df 100644 --- a/src/Models/Repositories/MySqlRepository.php +++ b/src/Models/Repositories/MySqlRepository.php @@ -108,7 +108,7 @@ public function valueExists($attribute, $value, $ignoredPrimaryKey = null) return $query->exists(); } - public function updateOrCreate(Entity $model) + public function updateOrCreate(Entity $model) { if ($this->exists($model->getPrimaryKey())) { $this->update($model); diff --git a/src/Models/Repositories/RedisRepository.php b/src/Models/Repositories/RedisRepository.php index 353c04c..6e16c97 100644 --- a/src/Models/Repositories/RedisRepository.php +++ b/src/Models/Repositories/RedisRepository.php @@ -12,10 +12,12 @@ public function __construct() { $this->cache = app('cache'); } + protected function getCache(): CacheManager { return $this->cache; } + /** * @param Collection $entities * @param Filter[]|Collection $filters diff --git a/src/Models/Resources/Resource.php b/src/Models/Resources/Resource.php index b0fb697..4026885 100644 --- a/src/Models/Resources/Resource.php +++ b/src/Models/Resources/Resource.php @@ -7,7 +7,6 @@ abstract class Resource implements IResource { - abstract public function toArray(Entity $entity): array; public function collectionToArray(Collection $entities): array From 3a31be0c729b9fbe4b35d3a50a05c2fd72f04fae Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 25 Dec 2023 22:21:58 +0330 Subject: [PATCH 42/86] fix(base repository): fix return --- src/Creators/CreatorRepository.php | 14 +++++++++++--- stubs/Repositories/Base/base.function.stub | 2 +- .../Redis/getAllBy/base.query_cache_strategy.stub | 8 ++++---- .../getAllBy/base.single_key_cache_strategy.stub | 4 ++-- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php index 9b93b5c..d81f307 100644 --- a/src/Creators/CreatorRepository.php +++ b/src/Creators/CreatorRepository.php @@ -9,7 +9,6 @@ use Eghamat24\DatabaseRepository\Commands\MakeRedisRepository; use Illuminate\Support\Str; - class CreatorRepository implements IClassCreator { public function __construct( @@ -39,28 +38,37 @@ private function writeFunction(string $functionStub, string $functionName, strin { $columnNameSingle = Str::camel($columnName); + $returnResult = ''; + $functionReturnType = ''; + if ($functionName === 'getOneBy') { $functionReturnType = 'null|{{ EntityName }}'; $functionName .= ucfirst(Str::camel($columnName)); $columnName = Str::camel($columnName); $redisCashFunction = $this->getRedisCashFunctionGetOneBy($this->strategyName); + $returnResult = 'return $entity;'; } elseif ($functionName === 'getAllBy') { $functionReturnType = 'Collection'; $functionName .= ucfirst(Str::plural(Str::camel($columnName))); $columnName = Str::plural(Str::camel($columnName)); $redisCashFunction = $this->getRedisCashFunctionGetAllBy($this->strategyName); + $returnResult = 'return $entities;'; } elseif ($functionName === 'create') { $functionReturnType = $attributeType; $redisCashFunction = $this->getRedisCashFunctionCreate($this->strategyName); + $returnResult = 'return $this->{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }});'; } elseif (in_array($functionName, ['update', 'remove', 'restore'])) { $functionReturnType = 'int'; $redisCashFunction = $this->getRedisCashFunctionUpdate($this->strategyName); + $returnResult = 'return $this->{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }});'; } $redisCashFunction = str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ ColumnNameSingle }}'], [$functionName, $columnName, $columnNameSingle], $redisCashFunction); - return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}', '{{redisFunction}}'], - [$functionName, $attributeType, Str::camel($columnName), $functionReturnType, $redisCashFunction], + $returnResult = str_replace(['{{ SqlRepositoryVariable }}', '{{ FunctionName }}', '{{ AttributeName }}'], [$this->sqlRepositoryVariable, $functionName, Str::camel($columnName)], $returnResult); + + return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}', '{{redisFunction}}', '{{returnResult}}'], + [$functionName, $attributeType, Str::camel($columnName), $functionReturnType, $redisCashFunction, $returnResult], $functionStub); } diff --git a/stubs/Repositories/Base/base.function.stub b/stubs/Repositories/Base/base.function.stub index 04d915a..f0002e5 100644 --- a/stubs/Repositories/Base/base.function.stub +++ b/stubs/Repositories/Base/base.function.stub @@ -1,5 +1,5 @@ public function {{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): {{ FunctionReturnType }} { {{redisFunction}} - return $this->{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }}); + {{returnResult}} } diff --git a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub index 19585ef..d8266c6 100644 --- a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -3,9 +3,9 @@ $cacheKey = $this->redisRepository->makeKey([ '{{ ColumnNameSingle }}' => ${{ ColumnName }}, ]); - $entity = $this->redisRepository->get($cacheKey); + $entities = $this->redisRepository->get($cacheKey); - if (is_null($entity)) { - $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); - $this->redisRepository->put($cacheKey, $entity); + if (is_null($entities)) { + $entities = $this->repository->{{ FunctionName }}(${{ ColumnName }}); + $this->redisRepository->put($cacheKey, $entities); } diff --git a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub index 633800a..8d10c3f 100644 --- a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ $entity = $this->redisRepository->get(); if (is_null($entity)) { - $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); - $this->redisRepository->put($entity); + $entities = $this->repository->{{ FunctionName }}(${{ ColumnName }}); + $this->redisRepository->put($entities); } From 0f7dd291abf00d41d5163fe9a1abebb3325043c3 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 25 Dec 2023 23:24:44 +0330 Subject: [PATCH 43/86] fix(entity): default int value --- src/Creators/CreatorEntity.php | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index fd51119..5346c5b 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -38,16 +38,38 @@ public function createAttributes(): array $attributes = []; foreach ($columns as $_column) { + $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); - $defaultValue = ($_column->COLUMN_DEFAULT ?? 'null') ? ($_column->COLUMN_DEFAULT ?? 'null') : "''"; - $defaultValue = ($dataType == self::BOOL_TYPE) ? ((in_array($defaultValue, [0, '', "''"])) ? 'false' : - ((in_array($defaultValue, [1, '1'])) ? 'true' : $defaultValue)) : $defaultValue; + $defaultValue = null; + if ($_column->COLUMN_DEFAULT !== null) { + $defaultValue = $_column->COLUMN_DEFAULT; + + if ($dataType == 'int') { + $defaultValue = intval($defaultValue); + } + + if ($dataType == self::BOOL_TYPE) { + if (in_array($defaultValue, [0, '', "''"])) { + $defaultValue = 'false'; + } elseif (in_array($defaultValue, [1, '1'])) { + $defaultValue = 'true'; + } + } + } + + $columnString = $_column->COLUMN_NAME; + if (!in_array($_column->COLUMN_DEFAULT, [null, 'NULL'])) { + $columnString .= ' = ' . $defaultValue; + } + if ($_column->IS_NULLABLE === 'YES') { + $columnString .= ' = null'; + } $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( $entityStubsPath, - $_column->COLUMN_NAME . (!in_array($_column->COLUMN_DEFAULT, [null, 'NULL']) ? ' = ' . $defaultValue : ''), + $columnString, ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType ); } From 45d38be9d38b636889e57c9f7dbb2899953f7d59 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Mon, 25 Dec 2023 23:27:38 +0330 Subject: [PATCH 44/86] fix(enum): use case instead of const --- src/Creators/CreatorEnum.php | 2 +- stubs/Enums/enum.attribute.stub | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Creators/CreatorEnum.php b/src/Creators/CreatorEnum.php index 7adc139..b6fb428 100644 --- a/src/Creators/CreatorEnum.php +++ b/src/Creators/CreatorEnum.php @@ -53,7 +53,7 @@ public function getNameSpace(): string public function getClassName(): string { - return $this->enumName; + return $this->enumName . ' : string'; } private function writeAttribute(string $attributeStub, string $attributeName, string $attributeString): string diff --git a/stubs/Enums/enum.attribute.stub b/stubs/Enums/enum.attribute.stub index 6d4bc36..a4c959e 100644 --- a/stubs/Enums/enum.attribute.stub +++ b/stubs/Enums/enum.attribute.stub @@ -1 +1 @@ -public const {{ AttributeName }} = '{{ AttributeString }}'; +case {{ AttributeName }} = '{{ AttributeString }}'; From 4460b25dbf5b03741695082df3fd0efc86762375 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Mon, 1 Jan 2024 02:16:24 +0330 Subject: [PATCH 45/86] refactor(composer.json): add laravel/framework to require-dev section --- composer.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/composer.json b/composer.json index 632114e..5cde4a1 100644 --- a/composer.json +++ b/composer.json @@ -18,6 +18,9 @@ "illuminate/cache": "^6.0|^7.0|^8.0|^9.0|^10.0", "illuminate/database": "^6.0|^7.0|^8.0|^9.0|^10.0" }, + "require-dev": { + "laravel/framework": "^8.0|^9.0|^10.0" + }, "autoload": { "psr-4": { "Eghamat24\\DatabaseRepository\\": "src/" From a1761752991ee48497b34b45fba54068c18ff3b5 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Mon, 1 Jan 2024 02:20:34 +0330 Subject: [PATCH 46/86] refactor(Trait): add type in class in CustomMySqlQueries --- src/CustomMySqlQueries.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index 2d2f5f2..1192503 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -8,7 +8,7 @@ trait CustomMySqlQueries { - protected $dataTypes = [ + protected array $dataTypes = [ 'bool' => 'bool', 'boolean' => 'bool', 'bit' => 'string', @@ -41,7 +41,7 @@ trait CustomMySqlQueries 'point' => 'string', ]; - protected $columnTypes = [ + protected array $columnTypes = [ 'tinyint(1)' => 'bool' ]; From 898f1d5162fc32ebf2b9ea3f804a9ad4f233ceb0 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Thu, 4 Jan 2024 23:18:01 +0330 Subject: [PATCH 47/86] refactor(Commands): improvement code style --- src/Commands/MakeAll.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 88218ab..4670aa7 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -4,7 +4,6 @@ use Illuminate\Console\Command; use Eghamat24\DatabaseRepository\CustomMySqlQueries; -use phpDocumentor\Reflection\PseudoTypes\NonEmptyLowercaseString; class MakeAll extends Command { @@ -37,9 +36,15 @@ class MakeAll extends Command */ public function handle() { - $strategyNames = array("ClearableTemporaryCacheStrategy", "QueryCacheStrategy", "SingleKeyCacheStrategy", "TemporaryCacheStrategy"); - if (!in_array($this->option('strategy_name'), $strategyNames)) { - $this->alert("This pattern strategy does not exist !!! "); + $strategyNames = [ + 'ClearableTemporaryCacheStrategy', + 'QueryCacheStrategy', + 'SingleKeyCacheStrategy', + 'TemporaryCacheStrategy' + ]; + + if (in_array($this->option('strategy_name'), $strategyNames) === false) { + $this->alert('This pattern strategy does not exist !!! '); exit; } @@ -49,6 +54,7 @@ public function handle() $detectForeignKeys = $this->option('foreign-keys'); $addToGit = $this->option('add-to-git'); $strategy = $this->option('strategy_name'); + if ($this->option('all-tables')) { $tableNames = $this->getAllTableNames()->pluck('TABLE_NAME'); } else if ($this->option('table_names')) { @@ -59,6 +65,7 @@ public function handle() } foreach ($tableNames as $_tableName) { + $arguments = [ 'table_name' => $_tableName, '--foreign-keys' => $detectForeignKeys, From 3c5e0104c18f235598b336b973522c6087ca916d Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Thu, 4 Jan 2024 23:18:51 +0330 Subject: [PATCH 48/86] fix(Commands): convert selectedDb property to local variable in MakAll.php --- src/Commands/MakeAll.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 4670aa7..19b4df5 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -48,7 +48,8 @@ public function handle() exit; } - $this->selectedDb = $this->hasOption('selected_db') && $this->option('selected_db') ? $this->option('selected_db') : config('repository.default_db'); + $selectedDb = $this->option('selected_db') ?: config('repository.default_db'); + $force = $this->option('force'); $delete = $this->option('delete'); $detectForeignKeys = $this->option('foreign-keys'); From d65ae555b1800725234ea5bb09d172dc32edc80e Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Thu, 4 Jan 2024 23:20:33 +0330 Subject: [PATCH 49/86] fix(Commands): using array lookup for command list in MakAll.php --- src/Commands/MakeAll.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 19b4df5..05cccc4 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -74,14 +74,20 @@ public function handle() '--force' => $force, '--add-to-git' => $addToGit ]; - $this->call('repository:make-entity', $arguments); - $this->call('repository:make-enum', ['table_name' => $_tableName, '--delete' => $delete, '--force' => $force, '--add-to-git' => $addToGit]); - $this->call('repository:make-factory', ['table_name' => $_tableName, '--delete' => $delete, '--force' => $force, '--add-to-git' => $addToGit]); - $this->call('repository:make-resource', $arguments); - $this->call('repository:make-interface-repository', $arguments); - $this->call('repository:make-mysql-repository', $arguments); - $this->call('repository:make-redis-repository', [...$arguments, 'strategy' => $strategy]); - $this->call('repository:make-repository', [...$arguments, 'strategy' => $strategy, 'selected_db' => $this->selectedDb]); + + $commands = [ + 'repository:make-entity' => $arguments, + 'repository:make-enum' => array_diff_key($arguments, ['--foreign-keys' => null]), + 'repository:make-factory' => array_diff_key($arguments, ['--foreign-keys' => null]), + 'repository:make-resource' => $arguments, + 'repository:make-interface-repository' => $arguments, + 'repository:make-redis-repository' => $arguments + ['strategy' => $strategy], + 'repository:make-repository' => $arguments + ['strategy' => $strategy, 'selected_db' => $selectedDb] + ]; + + foreach ($commands as $command => $args) { + $this->call($command, $args); + } } } } From 028107b4c5f50a471f27c640acd05075047bc399 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Thu, 4 Jan 2024 23:27:38 +0330 Subject: [PATCH 50/86] refactor(Commands): extract runCommandsWIthArguments method --- src/Commands/MakeAll.php | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 05cccc4..3364b5b 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -75,19 +75,30 @@ public function handle() '--add-to-git' => $addToGit ]; - $commands = [ - 'repository:make-entity' => $arguments, - 'repository:make-enum' => array_diff_key($arguments, ['--foreign-keys' => null]), - 'repository:make-factory' => array_diff_key($arguments, ['--foreign-keys' => null]), - 'repository:make-resource' => $arguments, - 'repository:make-interface-repository' => $arguments, - 'repository:make-redis-repository' => $arguments + ['strategy' => $strategy], - 'repository:make-repository' => $arguments + ['strategy' => $strategy, 'selected_db' => $selectedDb] - ]; + $this->runCommandsWithArguments($arguments, $strategy, $selectedDb); + } + } + + /** + * @param array $arguments + * @param bool|array|string|null $strategy + * @param mixed $selectedDb + * @return void + */ + private function runCommandsWithArguments(array $arguments, bool|array|string|null $strategy, mixed $selectedDb): void + { + $commands = [ + 'repository:make-entity' => $arguments, + 'repository:make-enum' => array_diff_key($arguments, ['--foreign-keys' => null]), + 'repository:make-factory' => array_diff_key($arguments, ['--foreign-keys' => null]), + 'repository:make-resource' => $arguments, + 'repository:make-interface-repository' => $arguments, + 'repository:make-redis-repository' => $arguments + ['strategy' => $strategy], + 'repository:make-repository' => $arguments + ['strategy' => $strategy, 'selected_db' => $selectedDb] + ]; - foreach ($commands as $command => $args) { - $this->call($command, $args); - } + foreach ($commands as $command => $args) { + $this->call($command, $args); } } } From a1d63399802c1ba474339516790ec2b4f4d25ed4 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Fri, 5 Jan 2024 00:44:14 +0330 Subject: [PATCH 51/86] refactor(Commands): improvement code style in MakeEnum.php --- src/Commands/MakeEnum.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 48d1939..4486633 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -6,10 +6,11 @@ use Eghamat24\DatabaseRepository\Creators\BaseCreator; use Eghamat24\DatabaseRepository\Creators\CreatorEnum; use Eghamat24\DatabaseRepository\CustomMySqlQueries; -use Illuminate\Console\Command; class MakeEnum extends BaseCommand { + use CustomMySqlQueries; + /** * The name and signature of the console command. * @@ -27,8 +28,6 @@ class MakeEnum extends BaseCommand */ protected $description = 'Create a new enum(s).'; - use CustomMySqlQueries; - public function handle(): void { $this->setArguments(); @@ -39,10 +38,10 @@ public function handle(): void $enums = []; foreach ($columns as $_column) { if ($_column->DATA_TYPE == 'enum') { - $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME) . "Enum"; + $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME) . 'Enum'; $enums[$enumClassName] = array_filter(explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE))); $filenameWithPath = $this->relativeEnumsPath . $enumClassName . '.php'; - $this->checkDelete($filenameWithPath, $enumClassName, "Enum"); + $this->checkDelete($filenameWithPath, $enumClassName, 'Enum'); } } @@ -52,7 +51,7 @@ public function handle(): void $filenameWithPath = $this->relativeEnumsPath . $enumName . '.php'; $this->checkDirectory($this->enumNamespace); - $this->checkClassExist($this->relativeEnumsPath, $enumName, "Enum"); + $this->checkClassExist($this->relativeEnumsPath, $enumName, 'Enum'); $enumCreator = new CreatorEnum($columns, $attributeStub, $enum, $enumName, $this->enumNamespace); $creator = new BaseCreator($enumCreator); From 8159810c69c13c6aba3faedf56d3c3508891c0c8 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Fri, 5 Jan 2024 00:45:40 +0330 Subject: [PATCH 52/86] refactor(Commands): reduce indent and more readability --- src/Commands/MakeEnum.php | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 4486633..7e0c0e3 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -37,12 +37,15 @@ public function handle(): void $enums = []; foreach ($columns as $_column) { - if ($_column->DATA_TYPE == 'enum') { - $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME) . 'Enum'; - $enums[$enumClassName] = array_filter(explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE))); - $filenameWithPath = $this->relativeEnumsPath . $enumClassName . '.php'; - $this->checkDelete($filenameWithPath, $enumClassName, 'Enum'); + + if ($_column->DATA_TYPE !== 'enum') { + continue; } + + $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME) . 'Enum'; + $enums[$enumClassName] = array_filter(explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE))); + $filenameWithPath = $this->relativeEnumsPath . $enumClassName . '.php'; + $this->checkDelete($filenameWithPath, $enumClassName, 'Enum'); } $attributeStub = file_get_contents($this->enumStubPath . 'attribute.stub'); From 002ae26f8628a539007e83be5f07b522113a5158 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Fri, 5 Jan 2024 00:47:43 +0330 Subject: [PATCH 53/86] refactor(Commands): extract extractEnumsFromColumns method --- src/Commands/MakeEnum.php | 56 ++++++++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 7e0c0e3..a536280 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -2,6 +2,7 @@ namespace Eghamat24\DatabaseRepository\Commands; +use Illuminate\Support\Collection; use Illuminate\Support\Str; use Eghamat24\DatabaseRepository\Creators\BaseCreator; use Eghamat24\DatabaseRepository\Creators\CreatorEnum; @@ -35,18 +36,7 @@ public function handle(): void $this->checkEmpty($columns, $this->tableName); - $enums = []; - foreach ($columns as $_column) { - - if ($_column->DATA_TYPE !== 'enum') { - continue; - } - - $enumClassName = Str::studly(Str::singular(ucfirst(Str::camel($_column->TABLE_NAME))) . '_' . $_column->COLUMN_NAME) . 'Enum'; - $enums[$enumClassName] = array_filter(explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $_column->COLUMN_TYPE))); - $filenameWithPath = $this->relativeEnumsPath . $enumClassName . '.php'; - $this->checkDelete($filenameWithPath, $enumClassName, 'Enum'); - } + $enums = $this->extractEnumsFromColumns($columns); $attributeStub = file_get_contents($this->enumStubPath . 'attribute.stub'); @@ -63,4 +53,46 @@ public function handle(): void $this->finalized($filenameWithPath, $enumName, $baseContent); } } + + + /** + * @param Collection $columns + * @return array + */ + public function extractEnumsFromColumns(Collection $columns): array + { + $enums = []; + foreach ($columns as $_column) { + + if ($_column->DATA_TYPE !== 'enum') { + continue; + } + + $enumClassName = $this->getEnumClassName($_column); + $enums[$enumClassName] = $this->extractEnumValues($_column->COLUMN_TYPE); + + $this->checkDelete( + $this->relativeEnumsPath . $enumClassName . '.php', + $enumClassName, + 'Enum' + ); + } + + return $enums; + } + + private function getEnumClassName(mixed $_column): string + { + $tableName = ucfirst(Str::camel($_column->TABLE_NAME)); + $columnName = $_column->COLUMN_NAME; + + return Str::studly(Str::singular($tableName) . '_' . $columnName) . 'Enum'; + } + + private function extractEnumValues($columnType): array + { + $items = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $columnType)); + + return array_filter($items); + } } From 538c3e6abf4565841331e8d9b264fcb0836849aa Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Fri, 5 Jan 2024 00:49:00 +0330 Subject: [PATCH 54/86] refactor(Commands): extract getBaseCreator method in MakeEnum.php --- src/Commands/MakeEnum.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index a536280..4a3fa21 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -46,9 +46,8 @@ public function handle(): void $this->checkDirectory($this->enumNamespace); $this->checkClassExist($this->relativeEnumsPath, $enumName, 'Enum'); - $enumCreator = new CreatorEnum($columns, $attributeStub, $enum, $enumName, $this->enumNamespace); - $creator = new BaseCreator($enumCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); + $baseContent = $this->getBaseCreator($columns, $attributeStub, $enum, $enumName) + ->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $enumName, $baseContent); } @@ -95,4 +94,18 @@ private function extractEnumValues($columnType): array return array_filter($items); } + + /** + * @param Collection $columns + * @param bool|string $attributeStub + * @param mixed $enum + * @param int|string $enumName + * @return BaseCreator + */ + private function getBaseCreator(Collection $columns, bool|string $attributeStub, mixed $enum, int|string $enumName): BaseCreator + { + $enumCreator = new CreatorEnum($columns, $attributeStub, $enum, $enumName, $this->enumNamespace); + + return new BaseCreator($enumCreator); + } } From 58c14054cabc07c3bc08639010053e9b641ded11 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Fri, 5 Jan 2024 11:51:39 +0330 Subject: [PATCH 55/86] refactor(Commands): improvement code style --- src/Commands/MakeMySqlRepository.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index 30a9ae3..d0a4d64 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -2,15 +2,15 @@ namespace Eghamat24\DatabaseRepository\Commands; -use Illuminate\Support\Str; use Eghamat24\DatabaseRepository\Creators\BaseCreator; -use Eghamat24\DatabaseRepository\Creators\CreatorEntity; use Eghamat24\DatabaseRepository\Creators\CreatorMySqlRepository; use Eghamat24\DatabaseRepository\CustomMySqlQueries; -use Illuminate\Console\Command; +use Illuminate\Support\Collection; class MakeMySqlRepository extends BaseCommand { + use CustomMySqlQueries; + /** * The name and signature of the console command. * @@ -29,7 +29,6 @@ class MakeMySqlRepository extends BaseCommand */ protected $description = 'Create a new MySql repository class'; - use CustomMySqlQueries; /** * Execute the console command. From 4994e6b35cb995a08124f6c1207b4be14721dcec Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Fri, 5 Jan 2024 11:52:37 +0330 Subject: [PATCH 56/86] refactor(Commands): modify and refactor handle method in MakeMySqlRepository --- src/Commands/MakeMySqlRepository.php | 58 +++++++++++++++++++++------- 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index d0a4d64..2a1754b 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -11,6 +11,8 @@ class MakeMySqlRepository extends BaseCommand { use CustomMySqlQueries; + private const OBJECT_NAME = 'MySql Repository'; + /** * The name and signature of the console command. * @@ -30,22 +32,52 @@ class MakeMySqlRepository extends BaseCommand protected $description = 'Create a new MySql repository class'; - /** - * Execute the console command. - * - * @return int - */ public function handle(): void { $this->setArguments(); - $filenameWithPath = $this->relativeMysqlRepositoryPath . $this->mysqlRepositoryName . '.php'; - $this->checkDelete($filenameWithPath, $this->mysqlRepositoryName, "MySql Repository"); + + $filenameWithPath = $this->getFileNameWithPath( + $this->relativeMysqlRepositoryPath, + $this->mysqlRepositoryName + ); + + $this->checkAndPrepare($filenameWithPath); + + $this->finalized( + $filenameWithPath, + $this->mysqlRepositoryName, + $this->generateBaseContent($filenameWithPath) + ); + } + + + private function getFileNameWithPath(string $relativePath, string $sectionName): string + { + return $relativePath . $sectionName . '.php'; + } + + + private function checkAndPrepare(string $filenameWithPath) + { + $this->checkDelete($filenameWithPath, $this->mysqlRepositoryName, self::OBJECT_NAME); $this->checkDirectory($this->relativeMysqlRepositoryPath); - $this->checkClassExist($this->repositoryNamespace, $this->mysqlRepositoryName, "MySql Repository"); - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + $this->checkClassExist($this->repositoryNamespace, $this->mysqlRepositoryName, self::OBJECT_NAME); + } + - $mysqlRepoCreator = new CreatorMySqlRepository($columns, + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + return $columns; + } + + + private function generateBaseContent(string $filenameWithPath): string + { + $mysqlRepoCreator = new CreatorMySqlRepository( + $this->getColumnsOf($this->tableName), $this->tableName, $this->entityName, $this->entityVariableName, @@ -58,9 +90,7 @@ public function handle(): void $this->mysqlRepositoryStubsPath, $this->detectForeignKeys ); - $creator = new BaseCreator($mysqlRepoCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); - $this->finalized($filenameWithPath, $this->mysqlRepositoryName, $baseContent); + return (new BaseCreator($mysqlRepoCreator))->createClass($filenameWithPath, $this); } } From 94667f5c7aeecdfbdf468d64095fd71938b49a97 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 6 Jan 2024 01:01:15 +0330 Subject: [PATCH 57/86] feat(Enum): create DataTypeEnum --- src/Models/Enums/DataTypeEnum.php | 82 +++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/Models/Enums/DataTypeEnum.php diff --git a/src/Models/Enums/DataTypeEnum.php b/src/Models/Enums/DataTypeEnum.php new file mode 100644 index 0000000..6de9165 --- /dev/null +++ b/src/Models/Enums/DataTypeEnum.php @@ -0,0 +1,82 @@ + self::BOOLEAN_TYPE, + + self::BIT, + self::JSON, + self::CHAR, + self::VARCHAR, + self::BINARY, + self::VARBINARY, + self::DATETIME, + self::TIME, + self::DATE, + self::ENUM, + self::LONGBLOB, + self::LONGTEXT, + self::MEDIUMBLOB, + self::MEDIUMTEXT, + self::BLOB, + self::TEXT, + self::TINYTEXT, + self::TINYBLOB, + self::TIMESTAMP, + self::POINT => self::STRING_TYPE, + + self::INT, + self::INTEGER, + self::TINYINT, + self::SMALLINT, + self::MEDIUMINT, + self::BIGINT => self::INTEGER_TYPE, + + self::FLOAT, + self::DOUBLE => self::FLOAT_TYPE, + }; + } +} From 3aaf4e98ae5516540551799032016a33abc219ca Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 6 Jan 2024 01:37:52 +0330 Subject: [PATCH 58/86] refactor(Stubs): convert is_null method to === null --- .../Redis/getAllBy/base.single_key_cache_strategy.stub | 2 +- .../Repositories/Redis/getOneBy/base.query_cache_strategy.stub | 2 +- .../Redis/getOneBy/base.single_key_cache_strategy.stub | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub index 8d10c3f..e653fb5 100644 --- a/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ $entity = $this->redisRepository->get(); - if (is_null($entity)) { + if ($entity === null) { $entities = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($entities); } diff --git a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub index 4477fc3..0641280 100644 --- a/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub @@ -5,7 +5,7 @@ $cacheKey = $this->redisRepository->makeKey([ $entity = $this->redisRepository->get($cacheKey); - if (is_null($entity)) { + if ($entity === null) { $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $entity); } diff --git a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub index 22cdd14..a9e94d5 100644 --- a/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub +++ b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub @@ -1,6 +1,6 @@ $entity = $this->redisRepository->get(); - if (is_null($entity)) { + if ($entity === null) { $entity = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($entity); } From fed5cbb4ec861a2b5d2556a2d9ed699679da8966 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 6 Jan 2024 01:39:29 +0330 Subject: [PATCH 59/86] refactor(Command): improvement code style , extract new methods in MakeInterfaceRepository command --- src/Commands/MakeInterfaceRepository.php | 218 +++++++++++++++++------ 1 file changed, 163 insertions(+), 55 deletions(-) diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index 675dc61..eb7cbbd 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -2,12 +2,15 @@ namespace Eghamat24\DatabaseRepository\Commands; +use Eghamat24\DatabaseRepository\Models\Enums\DataTypeEnum; +use Illuminate\Support\Collection; use Illuminate\Support\Str; use Eghamat24\DatabaseRepository\CustomMySqlQueries; -use Illuminate\Console\Command; class MakeInterfaceRepository extends BaseCommand { + use CustomMySqlQueries; + /** * The name and signature of the console command. * @@ -26,89 +29,194 @@ class MakeInterfaceRepository extends BaseCommand */ protected $description = 'Create a new interface for repository'; - use CustomMySqlQueries; + + public function handle(): void + { + $this->setArguments(); + $filenameWithPath = $this->relativeInterfacePath . $this->interfaceName . '.php'; + + $this->checkAndPrepare($filenameWithPath); + + [ + 'basedContent' => $baseContent, + 'getOneStub' => $getOneStub, + 'getAllStub' => $getAllStub, + 'createFunctionStub' => $createFunctionStub, + 'updateFunctionStub' => $updateFunctionStub, + 'deleteAndUndeleteStub' => $deleteAndUndeleteStub + ] = $this->getStubContents($this->interfaceRepositoryStubsPath); + + $baseContent = $this->writeFunctionOnBaseContent( + $baseContent, $this->writeGetOneFunction($getOneStub, 'id', DataTypeEnum::INTEGER_TYPE) + ); + + $baseContent = $this->writeFunctionOnBaseContent( + $baseContent, $this->writeGetAllFunction($getAllStub, 'id', DataTypeEnum::INTEGER_TYPE) + ); + + $columns = $this->getColumnsOf($this->tableName); + $indexes = $this->extractIndexes($this->tableName); + $baseContent = $this->writeGetFunctionByIndexColumnOnBaseContent($indexes, $columns, $baseContent, $getOneStub, $getAllStub); + $baseContent = $this->writeGetFunctionByForeignKeyOnBaseContent($baseContent, $getOneStub, $getAllStub); + + $allColumns = $columns->pluck('COLUMN_NAME')->toArray(); + $baseContent = $this->setTimestampsColumnOnBaseContent( + $allColumns, $baseContent, $createFunctionStub, $updateFunctionStub, $deleteAndUndeleteStub + ); + + $baseContent = $this->replaceDataOnInterfaceContent($baseContent); + + $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } + + private function writeFunctionOnBaseContent($baseContent, string $writeFunction): string|array + { + return substr_replace($baseContent, $writeFunction, -2, 0); + } + + private function writeFunction(string $stub, string $columnName, string $attributeType, array $placeHolders): array|string + { + $replaceValues = \array_map(function ($placeholder) use ($columnName, $attributeType) { + + return match ($placeholder) { + '{{ FunctionName }}' => ucfirst(Str::camel($columnName)), + '{{ ColumnName }}' => $columnName, + '{{ AttributeType }}' => $attributeType, + '{{ AttributeName }}' => Str::camel($columnName), + '{{ FunctionNamePlural }}' => ucfirst(Str::plural(Str::camel($columnName))), + '{{ AttributeNamePlural }}' => Str::plural(Str::camel($columnName)), + default => $placeholder, + }; + }, $placeHolders); + + return str_replace($placeHolders, $replaceValues, $stub); + } private function writeGetOneFunction(string $getOneStub, string $columnName, string $attributeType): string { - return str_replace(['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}'], - [ucfirst(Str::camel($columnName)), $columnName, $attributeType, Str::camel($columnName)], - $getOneStub); + $placeHolders = ['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}']; + return $this->writeFunction($getOneStub, $columnName, $attributeType, $placeHolders); } - private function writeGetAllFunction(string $getOneStub, string $columnName, string $attributeType): string + private function writeGetAllFunction(string $getAllStub, string $columnName, string $attributeType): string { - return str_replace(['{{ FunctionNamePlural }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}'], - [ucfirst(Str::plural(Str::camel($columnName))), $attributeType, Str::plural(Str::camel($columnName))], - $getOneStub); + $placeHolders = ['{{ FunctionNamePlural }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}']; + return $this->writeFunction($getAllStub, $columnName, $attributeType, $placeHolders); } - /** - * Execute the console command. - * - * @return int - */ - public function handle(): void + private function getColumnsOf(string $tableName): Collection { - $this->setArguments(); - $filenameWithPath = $this->relativeInterfacePath . $this->interfaceName . '.php'; + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); - $this->checkDelete($filenameWithPath, $this->interfaceName, "Interface"); + return $columns; + } + + private function checkAndPrepare(string $filenameWithPath): void + { + $this->checkDelete($filenameWithPath, $this->interfaceName, 'Interface'); $this->checkDirectory($this->relativeInterfacePath); - $this->checkClassExist($this->repositoryNamespace, $this->interfaceName, "Interface"); + $this->checkClassExist($this->repositoryNamespace, $this->interfaceName, 'Interface'); + } - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + private function setTimestampsColumnOnBaseContent( + array $allColumns, + array|string $baseContent, + bool|string $createFunctionStub, + bool|string $updateFunctionStub, + bool|string $deleteAndUndeleteStub): string|array + { + if (in_array('created_at', $allColumns, true)) { + $baseContent = substr_replace($baseContent, $createFunctionStub, -2, 0); + } + + if (in_array('updated_at', $allColumns, true)) { + $baseContent = substr_replace($baseContent, $updateFunctionStub, -2, 0); + } + + if (in_array('deleted_at', $allColumns, true)) { + $baseContent = substr_replace($baseContent, $deleteAndUndeleteStub, -2, 0); + } - if ($this->detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($this->tableName); + return $baseContent; + } + + private function getStubContents(string $basePath): array + { + $stubs = [ + 'basedContent' => 'class.stub', + 'getOneStub' => 'getOneBy.stub', + 'getAllStub' => 'getAllBy.stub', + 'createFunctionStub' => 'create.stub', + 'updateFunctionStub' => 'update.stub', + 'deleteAndUndeleteStub' => 'deleteAndUndelete.stub', + ]; + + $stubsContent = []; + + foreach ($stubs as $name => $endWith) { + $stubsContent[$name] = file_get_contents($basePath . $endWith); } - $baseContent = file_get_contents($this->interfaceRepositoryStubsPath . 'class.stub'); - $getOneStub = file_get_contents($this->interfaceRepositoryStubsPath . 'getOneBy.stub'); - $getAllStub = file_get_contents($this->interfaceRepositoryStubsPath . 'getAllBy.stub'); - $createFunctionStub = file_get_contents($this->interfaceRepositoryStubsPath . 'create.stub'); - $updateFunctionStub = file_get_contents($this->interfaceRepositoryStubsPath . 'update.stub'); - $deleteAndUndeleteStub = file_get_contents($this->interfaceRepositoryStubsPath . 'deleteAndUndelete.stub'); + return $stubsContent; + } - $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, 'id', 'int'), -2, 0); - $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, 'id', 'int'), -2, 0); - $columnsInfo = $this->getAllColumnsInTable($this->tableName); + private function replaceDataOnInterfaceContent(array|string $baseContent): string|array + { + $placeHolders = [ + '{{ EntityName }}' => $this->entityName, + '{{ EntityNamespace }}' => $this->entityNamespace, + '{{ EntityVariableName }}' => $this->entityVariableName, + '{{ InterfaceRepositoryName }}' => $this->interfaceName, + '{{ RepositoryNamespace }}' => $this->repositoryNamespace + ]; + + return \str_replace(\array_keys($placeHolders), \array_values($placeHolders), $baseContent); + } - $indexes = $this->extractIndexes($this->tableName); + private function writeGetFunctionByIndexColumnOnBaseContent(Collection $indexes, Collection $columns, mixed $baseContent, $getOneStub, $getAllStub): mixed + { foreach ($indexes as $index) { - $columnInfo = collect($columnsInfo)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); - $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)), -2, 0); + $columnInfo = collect($columns)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); + + $baseContent = $this->writeFunctionOnBaseContent($baseContent, + $this->writeGetOneFunction( + $getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE) + ) + ); if ($index->Non_unique == 1) { - $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getAllStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)), -2, 0); - } - } - if ($this->detectForeignKeys) { - foreach ($foreignKeys as $_foreignKey) { - $baseContent = substr_replace($baseContent, $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName), -2, 0); - $baseContent = substr_replace($baseContent, $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName), -2, 0); + $baseContent = $this->writeFunctionOnBaseContent($baseContent, + $this->writeGetOneFunction( + $getAllStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE) + ) + ); } } - $allColumns = $columns->pluck('COLUMN_NAME')->toArray(); + return $baseContent; + } - if (in_array('created_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $createFunctionStub, -2, 0); + public function writeGetFunctionByForeignKeyOnBaseContent(array|string $baseContent, $getOneStub, $getAllStub): string|array + { + if (empty($this->detectForeignKeys)) { + return $baseContent; } - if (in_array('updated_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $updateFunctionStub, -2, 0); - } + $foreignKeys = $this->extractForeignKeys($this->tableName); - if (in_array('deleted_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $deleteAndUndeleteStub, -2, 0); - } + foreach ($foreignKeys as $_foreignKey) { - $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ InterfaceRepositoryName }}', '{{ RepositoryNamespace }}'], - [$this->entityName, $this->entityNamespace, $this->entityVariableName, $this->interfaceName, $this->repositoryNamespace], - $baseContent); + $baseContent = $this->writeFunctionOnBaseContent( + $baseContent, $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName) + ); - $this->finalized($filenameWithPath, $this->entityName, $baseContent); + $baseContent = $this->writeFunctionOnBaseContent( + $baseContent, $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName) + ); + } + + return $baseContent; } } From d728061504b65928dee59b48c3aa4e2368563ef7 Mon Sep 17 00:00:00 2001 From: "S.H.Mahmoudzadeh" Date: Sat, 6 Jan 2024 17:12:52 +0330 Subject: [PATCH 60/86] fix(Command): resolve bug in generate repository:make-mysql-repository (MakAll command) --- src/Commands/MakeAll.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 3364b5b..07adebc 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -2,10 +2,9 @@ namespace Eghamat24\DatabaseRepository\Commands; -use Illuminate\Console\Command; use Eghamat24\DatabaseRepository\CustomMySqlQueries; -class MakeAll extends Command +class MakeAll extends BaseCommand { use CustomMySqlQueries; @@ -93,6 +92,7 @@ private function runCommandsWithArguments(array $arguments, bool|array|string|nu 'repository:make-factory' => array_diff_key($arguments, ['--foreign-keys' => null]), 'repository:make-resource' => $arguments, 'repository:make-interface-repository' => $arguments, + 'repository:make-mysql-repository' => $arguments, 'repository:make-redis-repository' => $arguments + ['strategy' => $strategy], 'repository:make-repository' => $arguments + ['strategy' => $strategy, 'selected_db' => $selectedDb] ]; From 9f25848a0de8d7bae5074bd48124d6b5aff37936 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sun, 7 Jan 2024 07:29:04 +0330 Subject: [PATCH 61/86] refactor(Command): add makeMySqlRepoCreator method to MakeMySqlRepository --- src/Commands/MakeMySqlRepository.php | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index 2a1754b..3cc4971 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -76,7 +76,17 @@ private function getColumnsOf(string $tableName): Collection private function generateBaseContent(string $filenameWithPath): string { - $mysqlRepoCreator = new CreatorMySqlRepository( + $mysqlRepoCreator = $this->makeMySqlRepoCreator(); + + return (new BaseCreator($mysqlRepoCreator))->createClass($filenameWithPath, $this); + } + + /** + * @return CreatorMySqlRepository + */ + private function makeMySqlRepoCreator(): CreatorMySqlRepository + { + return new CreatorMySqlRepository( $this->getColumnsOf($this->tableName), $this->tableName, $this->entityName, @@ -90,7 +100,5 @@ private function generateBaseContent(string $filenameWithPath): string $this->mysqlRepositoryStubsPath, $this->detectForeignKeys ); - - return (new BaseCreator($mysqlRepoCreator))->createClass($filenameWithPath, $this); } } From 688cf9fe9a06a98b6e3d4fce75e91787a2fe3ec2 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Tue, 9 Jan 2024 00:51:40 +0330 Subject: [PATCH 62/86] refactor(Stub): using === operator --- .../Repositories/Redis/getAllBy/base.query_cache_strategy.stub | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub index d8266c6..c6cd353 100644 --- a/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -5,7 +5,7 @@ $cacheKey = $this->redisRepository->makeKey([ $entities = $this->redisRepository->get($cacheKey); - if (is_null($entities)) { + if ($entities === null) { $entities = $this->repository->{{ FunctionName }}(${{ ColumnName }}); $this->redisRepository->put($cacheKey, $entities); } From 4636a3a40de9da1dcb553aa12f36506852034ba8 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Tue, 9 Jan 2024 00:52:26 +0330 Subject: [PATCH 63/86] refactor(Entity): improvement cod style and remove unused namespace in MakeEntity.php --- src/Commands/MakeEntity.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 8b39040..6cdc75f 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -2,17 +2,18 @@ namespace Eghamat24\DatabaseRepository\Commands; +use Illuminate\Support\Collection; use Illuminate\Support\Str; -use Eghamat24\DatabaseRepository\CreateEntity; use Eghamat24\DatabaseRepository\CustomMySqlQueries; use Eghamat24\DatabaseRepository\Creators\CreatorEntity; use Eghamat24\DatabaseRepository\Creators\BaseCreator; -use Illuminate\Support\Collection; class MakeEntity extends BaseCommand { use CustomMySqlQueries; + private const OBJECT_NAME = 'Entity'; + /** * The name and signature of the console command. * From ce2943f1d02e213f5c89b7271ec289c198e89baa Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Tue, 9 Jan 2024 00:53:46 +0330 Subject: [PATCH 64/86] refactor(Command): modify and refactor - improvement code style - extract method --- src/Commands/MakeEntity.php | 59 ++++++++++++++++++++++++++++++------- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 6cdc75f..751f083 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -40,28 +40,65 @@ public function handle(): void $this->setArguments(); $filenameWithPath = $this->relativeEntitiesPath . $this->entityName . '.php'; - $this->checkDelete($filenameWithPath, $this->entityName, "Entity"); - $this->checkDirectory($this->relativeEntitiesPath); - $this->checkClassExist($this->entityNamespace, $this->entityName, "Entity"); - - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + $this->checkAndPrepare($filenameWithPath); + $columns = $this->getColumnsOf($this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } - $entityCreator = new CreatorEntity($columns, + $entityCreator = $this->getCreatorEntity($columns); + $baseContent = $this->createBaseContent($entityCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } + + /** + * @param string $tableName + * @return Collection + */ + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + return $columns; + } + + /** + * @param string $filenameWithPath + * @return void + */ + private function checkAndPrepare(string $filenameWithPath): void + { + $this->checkDelete($filenameWithPath, $this->entityName, self::OBJECT_NAME); + $this->checkDirectory($this->relativeEntitiesPath); + $this->checkClassExist($this->entityNamespace, $this->entityName, self::OBJECT_NAME); + } + + /** + * @param Collection $columns + * @return CreatorEntity + */ + private function getCreatorEntity(Collection $columns): CreatorEntity + { + return new CreatorEntity($columns, $this->detectForeignKeys, $this->tableName, $this->entityName, $this->entityNamespace, $this->entityStubsPath ); - $creator = new BaseCreator($entityCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); - - $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } + /** + * @param CreatorEntity $entityCreator + * @param string $filenameWithPath + * @return string + */ + public function createBaseContent(CreatorEntity $entityCreator, string $filenameWithPath): string + { + $creator = new BaseCreator($entityCreator); + return $creator->createClass($filenameWithPath, $this); } } From 4d7b2504144f8efa865f64591f145aad45235875 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Tue, 9 Jan 2024 00:54:33 +0330 Subject: [PATCH 65/86] refactor(Command): modify and refactor makeEnum --- src/Commands/MakeEnum.php | 37 ++++++++++++++++++------ src/Commands/MakeInterfaceRepository.php | 2 +- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php index 4a3fa21..f68d7b8 100644 --- a/src/Commands/MakeEnum.php +++ b/src/Commands/MakeEnum.php @@ -12,6 +12,8 @@ class MakeEnum extends BaseCommand { use CustomMySqlQueries; + private const OBJECT_NAME = 'Enum'; + /** * The name and signature of the console command. * @@ -32,10 +34,7 @@ class MakeEnum extends BaseCommand public function handle(): void { $this->setArguments(); - $columns = $this->getAllColumnsInTable($this->tableName); - - $this->checkEmpty($columns, $this->tableName); - + $columns = $this->getColumnsOf($this->tableName); $enums = $this->extractEnumsFromColumns($columns); $attributeStub = file_get_contents($this->enumStubPath . 'attribute.stub'); @@ -43,9 +42,7 @@ public function handle(): void foreach ($enums as $enumName => $enum) { $filenameWithPath = $this->relativeEnumsPath . $enumName . '.php'; - $this->checkDirectory($this->enumNamespace); - $this->checkClassExist($this->relativeEnumsPath, $enumName, 'Enum'); - + $this->checkAndPrepare($enumName); $baseContent = $this->getBaseCreator($columns, $attributeStub, $enum, $enumName) ->createClass($filenameWithPath, $this); @@ -73,7 +70,7 @@ public function extractEnumsFromColumns(Collection $columns): array $this->checkDelete( $this->relativeEnumsPath . $enumClassName . '.php', $enumClassName, - 'Enum' + self::OBJECT_NAME ); } @@ -85,7 +82,7 @@ private function getEnumClassName(mixed $_column): string $tableName = ucfirst(Str::camel($_column->TABLE_NAME)); $columnName = $_column->COLUMN_NAME; - return Str::studly(Str::singular($tableName) . '_' . $columnName) . 'Enum'; + return Str::studly(Str::singular($tableName) . '_' . $columnName) . self::OBJECT_NAME; } private function extractEnumValues($columnType): array @@ -108,4 +105,26 @@ private function getBaseCreator(Collection $columns, bool|string $attributeStub, return new BaseCreator($enumCreator); } + + /** + * @param string $table + * @return Collection + */ + public function getColumnsOf(string $table): Collection + { + $columns = $this->getAllColumnsInTable($table); + $this->checkEmpty($columns, $table); + + return $columns; + } + + /** + * @param int|string $enumName + * @return void + */ + public function checkAndPrepare(int|string $enumName): void + { + $this->checkDirectory($this->enumNamespace); + $this->checkClassExist($this->relativeEnumsPath, $enumName, self::OBJECT_NAME); + } } diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index eb7cbbd..4fe5e84 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -71,7 +71,7 @@ public function handle(): void private function writeFunctionOnBaseContent($baseContent, string $writeFunction): string|array { - return substr_replace($baseContent, $writeFunction, -2, 0); + return \substr_replace($baseContent, $writeFunction, -2, 0); } private function writeFunction(string $stub, string $columnName, string $attributeType, array $placeHolders): array|string From f648a0ec6fb1373cba715ae12dcc345c0ec2466a Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Tue, 9 Jan 2024 00:55:36 +0330 Subject: [PATCH 66/86] refactor(Command): modify and refactor MakeRepository --- src/Commands/MakeRepository.php | 92 +++++++++++++++++++++++---------- 1 file changed, 64 insertions(+), 28 deletions(-) diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index d764fef..0f02aa3 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -2,14 +2,17 @@ namespace Eghamat24\DatabaseRepository\Commands; -//use Illuminate\Console\Command; -use Illuminate\Support\Str; +use Illuminate\Support\Collection; use Eghamat24\DatabaseRepository\Creators\BaseCreator; use Eghamat24\DatabaseRepository\Creators\CreatorRepository; use Eghamat24\DatabaseRepository\CustomMySqlQueries; class MakeRepository extends BaseCommand { + use CustomMySqlQueries; + + private const OBJECT_NAME = 'Repository'; + /** * The name and signature of the console command. * @@ -28,36 +31,36 @@ class MakeRepository extends BaseCommand */ protected $description = 'Create a new repository'; - use CustomMySqlQueries; - - /** - * Execute the console command. - * - * @return int - */ public function handle(): void { $this->checkDatabasesExist(); $this->checkStrategyName(); $this->setArguments(); - $repositoryName = $this->entityName . 'Repository'; -// $sqlRepositoryName = 'MySql'.$this->entityName.'Repository'; - $sqlRepositoryName = ucwords($this->selectedDb) . $this->entityName . 'Repository'; - $sqlRepositoryVariable = 'repository'; - $redisRepositoryVariable = 'redisRepository'; - $redisRepositoryName = 'Redis' . $this->entityName . 'Repository'; + $repositoryName = $this->entityName . self::OBJECT_NAME; $relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; - $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); + $filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php'; - $this->checkDelete($filenameWithPath, $repositoryName, "Repository"); - $this->checkDirectory($relativeRepositoryPath); - $this->checkClassExist($this->repositoryNamespace, $repositoryName, "Repository"); - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); - $RepoCreator = new CreatorRepository( - $columns, - $sqlRepositoryVariable, + $this->checkAndPrepare($filenameWithPath, $repositoryName, $relativeRepositoryPath); + + $repositoryCreator = $this->getRepositoryCreator($repositoryName); + $baseContent = $this->createBaseContent($repositoryCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $repositoryName, $baseContent); + } + + /** + * @param string $repositoryName + * @return CreatorRepository + */ + private function getRepositoryCreator(string $repositoryName): CreatorRepository + { + $sqlRepositoryName = ucwords($this->selectedDb) . $repositoryName; + $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); + + return new CreatorRepository( + $this->getColumnsOf($this->tableName), + 'repository', $sqlRepositoryName, $repositoryStubsPath, $this->detectForeignKeys, @@ -69,12 +72,45 @@ public function handle(): void $this->interfaceName, $this->repositoryNamespace, $this->selectedDb, - $redisRepositoryVariable, - $redisRepositoryName, + 'redisRepository', + 'Redis' . $repositoryName, $this->strategyName ); + } + + /** + * @param string $tableName + * @return Collection + */ + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + return $columns; + } + + /** + * @param CreatorRepository $RepoCreator + * @param string $filenameWithPath + * @return string + */ + private function createBaseContent(CreatorRepository $RepoCreator, string $filenameWithPath): string + { $creator = new BaseCreator($RepoCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); - $this->finalized($filenameWithPath, $repositoryName, $baseContent); + return $creator->createClass($filenameWithPath, $this); + } + + /** + * @param string $filenameWithPath + * @param string $repositoryName + * @param string $relativeRepositoryPath + * @return void + */ + private function checkAndPrepare(string $filenameWithPath, string $repositoryName, string $relativeRepositoryPath): void + { + $this->checkDelete($filenameWithPath, $repositoryName, self::OBJECT_NAME); + $this->checkDirectory($relativeRepositoryPath); + $this->checkClassExist($this->repositoryNamespace, $repositoryName, self::OBJECT_NAME); } } From c0cbfe2fc9227b221d3437220e807efb941df7c0 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Wed, 10 Jan 2024 00:08:32 +0330 Subject: [PATCH 67/86] refactor(Command): refactor MakeResource command --- src/Commands/MakeResource.php | 77 ++++++++++++++++++++++++++--------- 1 file changed, 58 insertions(+), 19 deletions(-) diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index 9ab6d31..9d04161 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -2,14 +2,17 @@ namespace Eghamat24\DatabaseRepository\Commands; -use Illuminate\Console\Command; -use Illuminate\Support\Str; use Eghamat24\DatabaseRepository\Creators\BaseCreator; use Eghamat24\DatabaseRepository\Creators\CreatorResource; use Eghamat24\DatabaseRepository\CustomMySqlQueries; +use Illuminate\Support\Collection; class MakeResource extends BaseCommand { + use CustomMySqlQueries; + + private const OBJECT_NAME = 'Resource'; + /** * The name and signature of the console command. * @@ -28,30 +31,59 @@ class MakeResource extends BaseCommand */ protected $description = 'Create new resource'; - use CustomMySqlQueries; - - /** - * Execute the console command. - * - * @return int - */ public function handle(): void { $this->setArguments(); - $resourceName = $this->entityName . "Resource"; + $resourceName = $this->entityName . self::OBJECT_NAME; $resourceNamespace = config('repository.path.namespace.resources'); $relativeResourcesPath = config('repository.path.relative.resources'); - $resourceStubsPath = __DIR__ . '/../../' . config('repository.path.stub.resources'); + $filenameWithPath = $relativeResourcesPath . $resourceName . '.php'; - $this->checkDelete($filenameWithPath, $resourceName, "Resource"); + $this->checkAndPrepare($filenameWithPath, $resourceName, $relativeResourcesPath, $resourceNamespace); + + $RepoCreator = $this->getResourceCreator($resourceNamespace, $resourceName); + $baseContent = $this->generateBaseContent($RepoCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $resourceName, $baseContent); + } + + /** + * @param string $filenameWithPath + * @param string $resourceName + * @param mixed $relativeResourcesPath + * @param mixed $resourceNamespace + * @return void + */ + private function checkAndPrepare(string $filenameWithPath, string $resourceName, mixed $relativeResourcesPath, mixed $resourceNamespace): void + { + $this->checkDelete($filenameWithPath, $resourceName, self::OBJECT_NAME); $this->checkDirectory($relativeResourcesPath); - $this->checkClassExist($resourceNamespace, $resourceName, "Resource"); + $this->checkClassExist($resourceNamespace, $resourceName, self::OBJECT_NAME); + } + + /** + * @param string $tableName + * @return Collection + */ + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + return $columns; + } + + /** + * @param mixed $resourceNamespace + * @param string $resourceName + * @return CreatorResource + */ + private function getResourceCreator(mixed $resourceNamespace, string $resourceName): CreatorResource + { + $resourceStubsPath = __DIR__ . '/../../' . config('repository.path.stub.resources'); - $RepoCreator = new CreatorResource($columns, + return new CreatorResource($this->getColumnsOf($this->tableName), $this->tableName, $this->entityName, $this->entityNamespace, @@ -60,10 +92,17 @@ public function handle(): void $resourceStubsPath, $this->detectForeignKeys, $this->entityVariableName); - $creator = new BaseCreator($RepoCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); - $this->finalized($filenameWithPath, $resourceName, $baseContent); + } + /** + * @param CreatorResource $RepoCreator + * @param string $filenameWithPath + * @return string + */ + private function generateBaseContent(CreatorResource $RepoCreator, string $filenameWithPath): string + { + $creator = new BaseCreator($RepoCreator); + return $creator->createClass($filenameWithPath, $this); } } From dbc9243319dfaf9d48bce2545680e13654e25379 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Wed, 10 Jan 2024 00:18:19 +0330 Subject: [PATCH 68/86] refactor(Command): refactor MakeRedisRepository --- src/Commands/MakeRedisRepository.php | 83 ++++++++++++++++++++-------- 1 file changed, 59 insertions(+), 24 deletions(-) diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index 3fb49cc..df63ef8 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -2,14 +2,17 @@ namespace Eghamat24\DatabaseRepository\Commands; -use Illuminate\Support\Str; +use Illuminate\Support\Collection; use Eghamat24\DatabaseRepository\Creators\BaseCreator; use Eghamat24\DatabaseRepository\Creators\CreatorRedisRepository; use Eghamat24\DatabaseRepository\CustomMySqlQueries; -use Illuminate\Console\Command; class MakeRedisRepository extends BaseCommand { + use CustomMySqlQueries; + + private const OBJECT_NAME = 'Redis Repository'; + /** * The name and signature of the console command. * @@ -28,37 +31,69 @@ class MakeRedisRepository extends BaseCommand */ protected $description = 'Create a new Redis repository class'; - use CustomMySqlQueries; - - /** - * Execute the console command. - * - * @return int - */ public function handle() { $this->checkStrategyName(); $this->setArguments(); - $redisRepositoryName = "Redis$this->entityName" . "Repository"; - $redisRepositoryNamespace = config('repository.path.namespace.repositories'); - $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; + $redisRepositoryName = "Redis$this->entityName" . 'Repository'; + $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . $this->entityName . DIRECTORY_SEPARATOR; $filenameWithPath = $relativeRedisRepositoryPath . $redisRepositoryName . '.php'; - $this->checkDelete($filenameWithPath, $redisRepositoryName, "Redis Repository"); - $this->checkDirectory($relativeRedisRepositoryPath); - $this->checkClassExist($this->repositoryNamespace, $redisRepositoryName, "Redis Repository"); - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + $this->checkAndPrepare($filenameWithPath, $redisRepositoryName, $relativeRedisRepositoryPath); + $this->getColumnsOf($this->tableName); - if ($this->detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($this->tableName); - } + $redisRepositoryCreator = $this->getRedisRepositoryCreator($redisRepositoryName); + $baseContent = $this->getBaseContent($redisRepositoryCreator, $filenameWithPath); - $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); - $mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName, $redisRepositoryNamespace, $this->entityName, $this->strategyName, $repositoryStubsPath); - $creator = new BaseCreator($mysqlRepoCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); $this->finalized($filenameWithPath, $redisRepositoryName, $baseContent); } + + + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + return $columns; + } + + + private function getRedisRepositoryCreator(string $redisRepositoryName): CreatorRedisRepository + { + $redisRepositoryNamespace = config('repository.path.namespace.repositories'); + $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); + + return new CreatorRedisRepository( + $redisRepositoryName, + $redisRepositoryNamespace, + $this->entityName, + $this->strategyName, + $repositoryStubsPath + ); + } + + /** + * @param CreatorRedisRepository $redisRepositoryCreator + * @param string $filenameWithPath + * @return string + */ + private function getBaseContent(CreatorRedisRepository $redisRepositoryCreator, string $filenameWithPath): string + { + $creator = new BaseCreator($redisRepositoryCreator); + return $creator->createClass($filenameWithPath, $this); + } + + /** + * @param string $filenameWithPath + * @param string $redisRepositoryName + * @param string $relativeRedisRepositoryPath + * @return void + */ + private function checkAndPrepare(string $filenameWithPath, string $redisRepositoryName, string $relativeRedisRepositoryPath): void + { + $this->checkDelete($filenameWithPath, $redisRepositoryName, self::OBJECT_NAME); + $this->checkDirectory($relativeRedisRepositoryPath); + $this->checkClassExist($this->repositoryNamespace, $redisRepositoryName, self::OBJECT_NAME); + } } From 8a6580a8ce4b96a2b4a81ea092866b01bcc4073d Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Wed, 10 Jan 2024 00:18:42 +0330 Subject: [PATCH 69/86] refactor(Command): refactor MakeFactory --- src/Commands/MakeFactory.php | 73 +++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 17 deletions(-) diff --git a/src/Commands/MakeFactory.php b/src/Commands/MakeFactory.php index 756c737..2bdc259 100644 --- a/src/Commands/MakeFactory.php +++ b/src/Commands/MakeFactory.php @@ -2,6 +2,7 @@ namespace Eghamat24\DatabaseRepository\Commands; +use Illuminate\Support\Collection; use Illuminate\Support\Str; use Eghamat24\DatabaseRepository\Creators\BaseCreator; use Eghamat24\DatabaseRepository\Creators\CreatorFactory; @@ -9,6 +10,10 @@ class MakeFactory extends BaseCommand { + use CustomMySqlQueries; + + private const OBJECT_NAME = 'Factory'; + /** * The name and signature of the console command. * @@ -26,8 +31,6 @@ class MakeFactory extends BaseCommand */ protected $description = 'Create a new factory.'; - use CustomMySqlQueries; - public function writeSetter(string $setterStub, string $columnName): string { return str_replace(['{{ SetterName }}', '{{ AttributeName }}'], @@ -35,23 +38,15 @@ public function writeSetter(string $setterStub, string $columnName): string $setterStub); } - /** - * Execute the console command. - * - * @return int - */ public function handle(): void { $this->setArguments(); $filenameWithPath = $this->relativeFactoriesPath . $this->factoryName . '.php'; - $this->checkDelete($filenameWithPath, $this->entityName, "Factory"); - $this->checkDirectory($this->relativeFactoriesPath); - $this->checkClassExist($this->factoryNamespace, $this->entityName, "Factory"); + $this->checkAndPrepare($filenameWithPath); - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + $columns = $this->getColumnsOf($this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); @@ -59,7 +54,43 @@ public function handle(): void $baseContent = file_get_contents($this->factoryStubsPath . 'class.stub'); - $factoryCreator = new CreatorFactory( + $factoryCreator = $this->getCreatorFactory($columns, $baseContent); + $baseContent = $this->generateBaseContent($factoryCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $this->factoryName, $baseContent); + } + + /** + * @param string $filenameWithPath + * @return void + */ + public function checkAndPrepare(string $filenameWithPath): void + { + $this->checkDelete($filenameWithPath, $this->entityName, self::OBJECT_NAME); + $this->checkDirectory($this->relativeFactoriesPath); + $this->checkClassExist($this->factoryNamespace, $this->entityName, self::OBJECT_NAME); + } + + /** + * @param string $tableName + * @return Collection + */ + public function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + return $columns; + } + + /** + * @param Collection $columns + * @param bool|string $baseContent + * @return CreatorFactory + */ + public function getCreatorFactory(Collection $columns, bool|string $baseContent): CreatorFactory + { + return new CreatorFactory( $columns, $this->entityName, $this->entityNamespace, @@ -67,10 +98,18 @@ public function handle(): void $this->factoryNamespace, $this->entityVariableName, $this->factoryName, - $baseContent); - $creator = new BaseCreator($factoryCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); + $baseContent + ); + } - $this->finalized($filenameWithPath, $this->factoryName, $baseContent); + /** + * @param CreatorFactory $factoryCreator + * @param string $filenameWithPath + * @return string + */ + public function generateBaseContent(CreatorFactory $factoryCreator, string $filenameWithPath): string + { + $creator = new BaseCreator($factoryCreator); + return $creator->createClass($filenameWithPath, $this); } } From dc894beeaa6a4089007b61f2b76006699cbbffa4 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Wed, 10 Jan 2024 00:25:28 +0330 Subject: [PATCH 70/86] refactor(Command): refactor MakeEntity --- src/Commands/MakeEntity.php | 61 ++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 8b39040..7a78130 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -13,6 +13,8 @@ class MakeEntity extends BaseCommand { use CustomMySqlQueries; + private const OBJECT_NAME = 'Entity'; + /** * The name and signature of the console command. * @@ -39,28 +41,65 @@ public function handle(): void $this->setArguments(); $filenameWithPath = $this->relativeEntitiesPath . $this->entityName . '.php'; - $this->checkDelete($filenameWithPath, $this->entityName, "Entity"); - $this->checkDirectory($this->relativeEntitiesPath); - $this->checkClassExist($this->entityNamespace, $this->entityName, "Entity"); - - $columns = $this->getAllColumnsInTable($this->tableName); - $this->checkEmpty($columns, $this->tableName); + $this->checkAndPrepare($filenameWithPath); + $columns = $this->getColumnsOf($this->tableName); foreach ($columns as $_column) { $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } - $entityCreator = new CreatorEntity($columns, + $entityCreator = $this->getEntityCreator($columns); + $baseContent = $this->getBaseContent($entityCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } + + /** + * @param string $tableName + * @return Collection + */ + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + return $columns; + } + + /** + * @param string $filenameWithPath + * @return void + */ + private function checkAndPrepare(string $filenameWithPath): void + { + $this->checkDelete($filenameWithPath, $this->entityName, self::OBJECT_NAME); + $this->checkDirectory($this->relativeEntitiesPath); + $this->checkClassExist($this->entityNamespace, $this->entityName, self::OBJECT_NAME); + } + + /** + * @param Collection $columns + * @return CreatorEntity + */ + private function getEntityCreator(Collection $columns): CreatorEntity + { + return new CreatorEntity($columns, $this->detectForeignKeys, $this->tableName, $this->entityName, $this->entityNamespace, $this->entityStubsPath ); - $creator = new BaseCreator($entityCreator); - $baseContent = $creator->createClass($filenameWithPath, $this); - - $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } + /** + * @param CreatorEntity $entityCreator + * @param string $filenameWithPath + * @return string + */ + private function getBaseContent(CreatorEntity $entityCreator, string $filenameWithPath): string + { + $creator = new BaseCreator($entityCreator); + return $creator->createClass($filenameWithPath, $this); } } From ca158b08a5f01ee0a43d007bc58496cb28eb6437 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Wed, 10 Jan 2024 00:25:55 +0330 Subject: [PATCH 71/86] refactor(Command): refactor MakeEntity --- src/Commands/MakeEntity.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 7a78130..d5edf22 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -3,7 +3,6 @@ namespace Eghamat24\DatabaseRepository\Commands; use Illuminate\Support\Str; -use Eghamat24\DatabaseRepository\CreateEntity; use Eghamat24\DatabaseRepository\CustomMySqlQueries; use Eghamat24\DatabaseRepository\Creators\CreatorEntity; use Eghamat24\DatabaseRepository\Creators\BaseCreator; From f87003b9bd016c80fc0890bd6f6250511f254cf4 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:08:24 +0330 Subject: [PATCH 72/86] refactor(Command): modify and refactor BaseCommand - convert BaseCommand class to abstract - remove unused namespace - improvement code style --- src/Commands/BaseCommand.php | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index 2ac62bf..d0a7717 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -2,15 +2,12 @@ namespace Eghamat24\DatabaseRepository\Commands; -use Illuminate\Container\Container; use Illuminate\Support\Collection; use Illuminate\Console\Command; -use Eghamat24\DatabaseRepository\CustomMySqlQueries; use Illuminate\Support\Str; -class BaseCommand extends Command +abstract class BaseCommand extends Command { -// use CustomMySqlQueries; public string $selectedDb; public string $tableName; public string $detectForeignKeys; @@ -74,7 +71,7 @@ public function setArguments() public function checkDelete(string $filenameWithPath, string $entityName, string $objectName): void { if (file_exists($filenameWithPath) && $this->option('delete')) { - unlink($filenameWithPath); + \unlink($filenameWithPath); $this->info("$objectName '$entityName' has been deleted."); } } @@ -125,19 +122,25 @@ public function getChoice(): null|string public function checkStrategyName() { - $strategyNames = array("ClearableTemporaryCacheStrategy", "QueryCacheStrategy", "SingleKeyCacheStrategy", "TemporaryCacheStrategy"); + $strategyNames = [ + 'ClearableTemporaryCacheStrategy', + 'QueryCacheStrategy', + 'SingleKeyCacheStrategy', + 'TemporaryCacheStrategy' + ]; + if (!in_array($this->argument('strategy'), $strategyNames)) { - $this->alert("This pattern strategy does not exist !!! "); + $this->alert('This pattern strategy does not exist !!! '); exit; } } public function checkDatabasesExist() { - $entityName = Str::singular(ucfirst(Str::camel($this->argument('table_name')))); - $mysql = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . "MySql" . $entityName . "Repository.php"; - $redis = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . "Redis" . $entityName . "Repository.php"; + $mysql = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . 'MySql' . $entityName . 'Repository.php'; + $redis = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . 'Redis' . $entityName . 'Repository.php'; + if (!(file_exists($mysql) && file_exists($redis))) { $this->alert("First create the class databases!!!"); exit; From d1890110ffe74d04bdfca1043af327f3b6354e23 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:09:29 +0330 Subject: [PATCH 73/86] refactor(Command): modify and refactor CreatorEntity (improvement code style) --- src/Creators/CreatorEntity.php | 69 ++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index 5346c5b..ed404c4 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -2,6 +2,7 @@ namespace Eghamat24\DatabaseRepository\Creators; +use Eghamat24\DatabaseRepository\Models\Enums\DataTypeEnum; use Illuminate\Support\Collection; use Eghamat24\DatabaseRepository\CustomMySqlQueries; @@ -31,13 +32,9 @@ public function getExtendSection(): string public function createAttributes(): array { - $columns = $this->columns; - $entityStubsPath = $this->entityStubsPath; - $detectForeignKeys = $this->detectForeignKeys; - $tableName = $this->tableName; $attributes = []; - foreach ($columns as $_column) { + foreach ($this->columns as $_column) { $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); @@ -45,11 +42,11 @@ public function createAttributes(): array if ($_column->COLUMN_DEFAULT !== null) { $defaultValue = $_column->COLUMN_DEFAULT; - if ($dataType == 'int') { + if ($dataType === DataTypeEnum::INTEGER_TYPE) { $defaultValue = intval($defaultValue); } - if ($dataType == self::BOOL_TYPE) { + if ($dataType === self::BOOL_TYPE) { if (in_array($defaultValue, [0, '', "''"])) { $defaultValue = 'false'; } elseif (in_array($defaultValue, [1, '1'])) { @@ -59,29 +56,31 @@ public function createAttributes(): array } $columnString = $_column->COLUMN_NAME; + if (!in_array($_column->COLUMN_DEFAULT, [null, 'NULL'])) { $columnString .= ' = ' . $defaultValue; } + if ($_column->IS_NULLABLE === 'YES') { $columnString .= ' = null'; } $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( - $entityStubsPath, + $this->entityStubsPath, $columnString, ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType ); } - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); // Create Additional Attributes from Foreign Keys foreach ($foreignKeys as $_foreignKey) { $attributes[$_column->COLUMN_NAME] = $this->writeAttribute( - $entityStubsPath, + $this->entityStubsPath, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE ); @@ -93,73 +92,85 @@ public function createAttributes(): array public function createUses(): array { - return ["use Eghamat24\DatabaseRepository\Models\Entity\Entity;"]; + return ['use Eghamat24\DatabaseRepository\Models\Entity\Entity;']; } public function createFunctions(): array { - $columns = $this->columns; - $entityStubsPath = $this->entityStubsPath; - $detectForeignKeys = $this->detectForeignKeys; - $tableName = $this->tableName; $settersAndGetters = []; - foreach ($columns as $_column) { + + foreach ($this->columns as $_column) { $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); $settersAndGetters['get' . ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( - $entityStubsPath, + $this->entityStubsPath, $_column->COLUMN_NAME, ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, 'getter' ); + $settersAndGetters['set' . ucwords($_column->COLUMN_NAME)] = $this->writeAccessors( - $entityStubsPath, + $this->entityStubsPath, $_column->COLUMN_NAME, ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, 'setter' ); } - if ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); + + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); // Create Additional Setters and Getters from Foreign keys foreach ($foreignKeys as $_foreignKey) { + $settersAndGetters['get' . ucwords($_foreignKey->COLUMN_NAME)] = $this->writeAccessors( - $entityStubsPath, + $this->entityStubsPath, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE, 'getter' ); + $settersAndGetters['set' . ucwords($_foreignKey->COLUMN_NAME)] = $this->writeAccessors( - $entityStubsPath, + $this->entityStubsPath, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE, 'setter' ); } } + return $settersAndGetters; } private function writeAttribute(string $entityStubsPath, string $attributeName, string $attributeType): string { $attributeStub = file_get_contents($entityStubsPath . 'attribute.stub'); - return str_replace(['{{ AttributeType }}', '{{ AttributeName }}'], - [$attributeType, $attributeName], - $attributeStub); + + $replaceMapping = [ + '{{ AttributeType }}' => $attributeType, + '{{ AttributeName }}' => $attributeName, + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $attributeStub); } private function writeAccessors(string $entityStubsPath, string $attributeName, string $attributeType, string $type): string { $accessorStub = file_get_contents($entityStubsPath . $type . '.stub'); - return str_replace(['{{ AttributeType }}', '{{ AttributeName }}', '{{ GetterName }}', '{{ SetterName }}'], - [$attributeType, $attributeName, ucfirst($attributeName), ucfirst($attributeName)], - $accessorStub); + + $replaceMapping = [ + '{{ AttributeType }}' => $attributeType, + '{{ AttributeName }}' => $attributeName, + '{{ GetterName }}' => ucfirst($attributeName), + '{{ SetterName }}' => ucfirst($attributeName) + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $accessorStub); } public function getNameSpace(): string From 8eddf4e606a3ba13712c69d89efccd898c7512f1 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:10:00 +0330 Subject: [PATCH 74/86] refactor(Command): modify and refactor CreatorFactory (improvement code style) --- src/Creators/CreatorFactory.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php index 58d736c..12d69fb 100644 --- a/src/Creators/CreatorFactory.php +++ b/src/Creators/CreatorFactory.php @@ -39,6 +39,7 @@ public function createFunctions(): array foreach ($this->columns as $_column) { $setterFunctions .= trim($this->writeSetter($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; } + return ['makeEntityFromStdClass' => str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityVariableName }}'], [$setterFunctions, $this->entityName, $this->entityVariableName], @@ -50,8 +51,8 @@ public function createUses(): array { return [ "use $this->entityNamespace\\$this->entityName;", - "use Eghamat24\DatabaseRepository\Models\Factories\Factory;", - "use stdClass;" + 'use Eghamat24\DatabaseRepository\Models\Factories\Factory;', + 'use stdClass;' ]; } @@ -63,9 +64,12 @@ public function getExtendSection(): string public function writeSetter(string $setterStub, string $columnName): string { - return str_replace(['{{ SetterName }}', '{{ AttributeName }}'], - [ucfirst($columnName), Str::snake($columnName)], - $setterStub); + $replacementTokens = [ + '{{ SetterName }}' => ucfirst($columnName), + '{{ AttributeName }}' => Str::snake($columnName) + ]; + + return str_replace(array_keys($replacementTokens), array_values($replacementTokens), $setterStub); } public function getClassName(): string From 055d02a1f4602cefeed66b0425d35e80b06f0c72 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:11:00 +0330 Subject: [PATCH 75/86] refactor(Command): modify and refactorCreatorMySqlRepository --- src/Creators/CreatorMySqlRepository.php | 156 +++++++++++++++--------- 1 file changed, 100 insertions(+), 56 deletions(-) diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index 725333a..ef74172 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -2,6 +2,7 @@ namespace Eghamat24\DatabaseRepository\Creators; +use Eghamat24\DatabaseRepository\Models\Enums\DataTypeEnum; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Eghamat24\DatabaseRepository\CustomMySqlQueries; @@ -38,8 +39,8 @@ public function createUses(): array return [ "use $this->entityNamespace\\$this->entityName;", "use $this->factoryNamespace\\$this->factoryName;", - "use Illuminate\Support\Collection;", - "use Eghamat24\DatabaseRepository\Models\Repositories\MySqlRepository;" + 'use Illuminate\Support\Collection;', + 'use Eghamat24\DatabaseRepository\Models\Repositories\MySqlRepository;' ]; } @@ -50,7 +51,7 @@ public function getClassName(): string public function getExtendSection(): string { - return "extends MySqlRepository implements " . $this->interfaceName; + return 'extends MySqlRepository implements ' . $this->interfaceName; } public function createAttributes(): array @@ -61,35 +62,46 @@ public function createAttributes(): array public function createFunctions(): array { - $baseContent = file_get_contents($this->mysqlRepositoryStubsPath . 'class.stub'); - $constructContent = file_get_contents($this->mysqlRepositoryStubsPath . 'construct.stub'); - $getOneStub = file_get_contents($this->mysqlRepositoryStubsPath . 'getOneBy.stub'); - $getAllStub = file_get_contents($this->mysqlRepositoryStubsPath . 'getAllBy.stub'); - $createFunctionStub = file_get_contents($this->mysqlRepositoryStubsPath . 'create.stub'); - $updateFunctionStub = file_get_contents($this->mysqlRepositoryStubsPath . 'update.stub'); - $deleteStub = file_get_contents($this->mysqlRepositoryStubsPath . 'delete.stub'); - $undeleteStub = file_get_contents($this->mysqlRepositoryStubsPath . 'undelete.stub'); - $getterStub = file_get_contents($this->mysqlRepositoryStubsPath . 'getter.stub'); - $setterStub = file_get_contents($this->mysqlRepositoryStubsPath . 'setter.stub'); - $timeFieldStub = file_get_contents($this->mysqlRepositoryStubsPath . 'timeField.stub'); + $stubList = [ + 'baseContent' => 'class.stub', + 'constructContent' => 'construct.stub', + 'getOneStub' => 'getOneBy.stub', + 'getAllStub' => 'getAllBy.stub', + 'createFunctionStub' => 'create.stub', + 'updateFunctionStub' => 'update.stub', + 'deleteStub' => 'delete.stub', + 'undeleteStub' => 'undelete.stub', + 'getterStub' => 'getter.stub', + 'setterStub' => 'setter.stub', + 'timeFieldStub' => 'timeField.stub', + ]; + + $stubContent = []; + foreach ($stubList as $stubKey => $stubName) { + $stubContent[$stubKey] = file_get_contents($this->mysqlRepositoryStubsPath . $stubName); + } - $functions = []; - // Initialize MySql Repository $hasSoftDelete = in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true); - $functions['__construct'] = $this->getConstruct($this->tableName, $this->factoryName, $hasSoftDelete, $constructContent); - $functions['getOneById'] = $this->writeGetOneFunction($getOneStub, 'id', 'int'); - $functions['getAllByIds'] = $this->writeGetAllFunction($getAllStub, 'id', 'int'); + + $functions = []; + $functions['__construct'] = $this->getConstruct($this->tableName, $this->factoryName, $hasSoftDelete, $stubContent['constructContent']); + $functions['getOneById'] = $this->writeGetOneFunction($stubContent['getOneStub'], 'id', DataTypeEnum::INTEGER_TYPE); + $functions['getAllByIds'] = $this->writeGetAllFunction($stubContent['getAllStub'], 'id', DataTypeEnum::INTEGER_TYPE); $columnsInfo = $this->getAllColumnsInTable($this->tableName); $indexes = $this->extractIndexes($this->tableName); foreach ($indexes as $index) { $columnInfo = collect($columnsInfo)->where('COLUMN_NAME', $index->COLUMN_NAME)->first(); $indx = 'getOneBy' . ucfirst(Str::camel($index->COLUMN_NAME)); - $functions[$indx] = $this->writeGetOneFunction($getOneStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE)); + $functions[$indx] = $this->writeGetOneFunction( + $stubContent['getOneStub'], + $index->COLUMN_NAME, + $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE) + ); if ($index->Non_unique == 1) { $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($index->COLUMN_NAME))); - $functions[$indx] = $this->writeGetAllFunction($getAllStub, $index->COLUMN_NAME, $this->entityName); + $functions[$indx] = $this->writeGetAllFunction($stubContent['getAllStub'], $index->COLUMN_NAME, $this->entityName); } } @@ -97,60 +109,33 @@ public function createFunctions(): array $foreignKeys = $this->extractForeignKeys($this->tableName); foreach ($foreignKeys as $_foreignKey) { $indx = 'getOneBy' . ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); - $functions[$indx] = $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName); + $functions[$indx] = $this->writeGetOneFunction($stubContent['getOneStub'], $_foreignKey->COLUMN_NAME, $this->entityName); $indx = 'getAllBy' . ucfirst(Str::plural(Str::camel($_foreignKey->COLUMN_NAME))); - $functions[$indx] = $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName); + $functions[$indx] = $this->writeGetAllFunction($stubContent['getAllStub'], $_foreignKey->COLUMN_NAME, $this->entityName); } } $getterFunctions = ''; $setterFunctions = ''; - // Create "create" function - foreach ($this->columns as $_column) { - if (!in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { - $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME)) . "\n\t\t\t\t"; - } - if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { - $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; - } - } - $createFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ SetterFunctions }}"], - [trim(substr($getterFunctions, 0, -1)), trim(substr($setterFunctions, 0, -1))], - $createFunctionStub - ); - - $functions['create'] = $createFunctionStub; + $functions = $this->makeCreateFunction($stubContent, $getterFunctions, $setterFunctions, $functions); $getterFunctions = ''; $setterFunctions = ''; - // Create "update" function - foreach ($this->columns as $_column) { - if (!in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { - $getterFunctions .= trim($this->writeGetterFunction($getterStub, $_column->COLUMN_NAME)) . "\n\t\t\t\t"; - } - if ($_column->COLUMN_NAME === 'updated_at') { - $setterFunctions .= trim($this->writeSetterFunction($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; - } - } - $updateFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ UpdateFieldSetter }}"], - [trim(substr($getterFunctions, 0, -1)), trim(substr($setterFunctions, 0, -1))], - $updateFunctionStub - ); - - $functions['update'] = $updateFunctionStub; + $functions = $this->makeUpdateFunction($stubContent, $getterFunctions, $setterFunctions, $functions); // Create "delete" and "undelete" functions if necessary if ($hasSoftDelete) { - $functions['remove'] = $deleteStub; - $functions['restore'] = $undeleteStub; + $functions['remove'] = $stubContent['deleteStub']; + $functions['restore'] = $stubContent['undeleteStub']; } foreach ($functions as &$func) { - $func = str_replace(["{{ EntityName }}", "{{ EntityVariableName }}"], + $func = str_replace(['{{ EntityName }}', '{{ EntityVariableName }}'], [$this->entityName, $this->entityVariableName], $func ); } + return $functions; } @@ -189,4 +174,63 @@ private function getConstruct(string $tableName, string $factoryName, bool $hasS [$tableName, $factoryName, $hasSoftDelete ? 'true' : 'false'], $constructContent); } + + /** + * @param array $stubContent + * @param string $getterFunctions + * @param string $setterFunctions + * @param array $functions + * @return array + */ + public function makeCreateFunction(array &$stubContent, string &$getterFunctions, string &$setterFunctions, array &$functions): array + { + foreach ($this->columns as $_column) { + if (!in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { + $getterFunctions .= trim($this->writeGetterFunction($stubContent['getterStub'], $_column->COLUMN_NAME)) . "\n\t\t\t\t"; + } + + if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { + $setterFunctions .= trim($this->writeSetterFunction($stubContent['setterStub'], $_column->COLUMN_NAME)) . "\n\t\t"; + } + } + + $createFunctionStub = str_replace(["{{ GetterFunctions }}", "{{ SetterFunctions }}"], + [trim(substr($getterFunctions, 0, -1)), trim(substr($setterFunctions, 0, -1))], + $stubContent['createFunctionStub'] + ); + + $functions['create'] = $createFunctionStub; + + return $functions; + } + + /** + * @param array $stubContent + * @param string $getterFunctions + * @param string $setterFunctions + * @param array $functions + * @return array + */ + public function makeUpdateFunction(array &$stubContent, string &$getterFunctions, string &$setterFunctions, array &$functions): array + { + foreach ($this->columns as $_column) { + + if (!in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { + $getterFunctions .= trim($this->writeGetterFunction($stubContent['getterStub'], $_column->COLUMN_NAME)) . "\n\t\t\t\t"; + } + + if ($_column->COLUMN_NAME === 'updated_at') { + $setterFunctions .= trim($this->writeSetterFunction($stubContent['setterStub'], $_column->COLUMN_NAME)) . "\n\t\t"; + } + } + + $updateFunctionStub = str_replace(['{{ GetterFunctions }}', '{{ UpdateFieldSetter }}'], + [trim(substr($getterFunctions, 0, -1)), trim(substr($setterFunctions, 0, -1))], + $stubContent['updateFunctionStub'] + ); + + $functions['update'] = $updateFunctionStub; + + return $functions; + } } From 40c6cb36c5aaf13f9abea01780d32c759d83ebf8 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:11:43 +0330 Subject: [PATCH 76/86] refactor(Command): modify and refactor CreatorRedisRepository --- src/Creators/CreatorRedisRepository.php | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php index 91edc8b..a9f7f94 100644 --- a/src/Creators/CreatorRedisRepository.php +++ b/src/Creators/CreatorRedisRepository.php @@ -2,9 +2,6 @@ namespace Eghamat24\DatabaseRepository\Creators; -use Illuminate\Support\Str; -use Eghamat24\DatabaseRepository\CustomMySqlQueries; - class CreatorRedisRepository implements IClassCreator { public function __construct( @@ -38,7 +35,7 @@ public function getClassName(): string public function getExtendSection(): string { - return "extends RedisRepository"; + return 'extends RedisRepository'; } public function createAttributes(): array @@ -54,9 +51,9 @@ public function createFunctions(): array return $functions; } - public function getConstructRedis(string $constructStub) + public function getConstructRedis(string $constructStub): array|string { - return str_replace("{{Strategy}}", $this->strategyName, $constructStub); + return str_replace('{{Strategy}}', $this->strategyName, $constructStub); } } From c6adf759e9cb0e815213189c773735ef96d569b6 Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:12:09 +0330 Subject: [PATCH 77/86] refactor(Command): modify and refactor CreatorResource --- src/Creators/CreatorResource.php | 33 +++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/src/Creators/CreatorResource.php b/src/Creators/CreatorResource.php index bcc0daa..1c58784 100644 --- a/src/Creators/CreatorResource.php +++ b/src/Creators/CreatorResource.php @@ -31,9 +31,11 @@ public function getNameSpace(): string public function createUses(): array { - return ["use $this->entityNamespace\\$this->entityName;", - "use Eghamat24\DatabaseRepository\Models\Entity\Entity;", - "use Eghamat24\DatabaseRepository\Models\Resources\Resource;"]; + return [ + "use $this->entityNamespace\\$this->entityName;", + 'use Eghamat24\DatabaseRepository\Models\Entity\Entity;', + 'use Eghamat24\DatabaseRepository\Models\Resources\Resource;' + ]; } public function getClassName(): string @@ -70,25 +72,34 @@ public function createFunctions(): array $foreignGetterFunctions .= $this->writeForeignGetter($foreignGetterStub, $_foreignKey->VARIABLE_NAME, $_foreignKey->ENTITY_DATA_TYPE); } } + $functions = []; $functions['toArray'] = str_replace(['{{ Getters }}'], [$getters], $getterFunStub); $functions['toArray'] = str_replace(['{{ EntityVariableName }}'], [$this->entityVariableName], $functions['toArray']); $functions['toArrayWithForeignKeys'] = str_replace(['{{ ForeignGetterFunctions }}'], [$foreignGetterFunctions], $foreignFunStub); $functions['toArrayWithForeignKeys'] = str_replace(['{{ EntityVariableName }}'], [$this->entityVariableName], $functions['toArrayWithForeignKeys']); + return $functions; } - public function writeGetter(string $getterStub, string $columnName, string $attributeName) + public function writeGetter(string $getterStub, string $columnName, string $attributeName): array|string { - return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], - [$columnName, ucfirst($attributeName)], - $getterStub); + $replaceMapping = [ + '{{ ColumnName }}' => $columnName, + '{{ GetterName }}' => ucfirst($attributeName), + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $getterStub); } - public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName) + public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName): array|string { - return str_replace(['{{ AttributeName }}', '{{ GetterName }}', '{{ AttributeType }}'], - [Str::snake($columnName), ucfirst($columnName), ucfirst($attributeName)], - $foreignGetterStub); + $replaceMapping = [ + '{{ AttributeName }}' => Str::snake($columnName), + '{{ GetterName }}' => ucfirst($columnName), + '{{ AttributeType }}' => ucfirst($attributeName) + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $foreignGetterStub); } } From 1906046b11114322d1c89f18dd479dc0e122c0ad Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:12:37 +0330 Subject: [PATCH 78/86] refactor(Command): modify and refactor CreatorEnum --- src/Creators/CreatorEnum.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Creators/CreatorEnum.php b/src/Creators/CreatorEnum.php index b6fb428..f03c3c1 100644 --- a/src/Creators/CreatorEnum.php +++ b/src/Creators/CreatorEnum.php @@ -3,7 +3,6 @@ namespace Eghamat24\DatabaseRepository\Creators; use Illuminate\Support\Collection; -use Eghamat24\DatabaseRepository\Commands\MakeEnum; class CreatorEnum implements IClassCreator { @@ -22,12 +21,14 @@ public function createAttributes(): array { $attributes = []; foreach ($this->enum as $_enum) { + $attributes[strtoupper($_enum)] = $this->writeAttribute( $this->attributeStub, strtoupper($_enum), $_enum ); } + return $attributes; } @@ -58,8 +59,11 @@ public function getClassName(): string private function writeAttribute(string $attributeStub, string $attributeName, string $attributeString): string { - return str_replace(['{{ AttributeName }}', '{{ AttributeString }}'], - [$attributeName, $attributeString], - $attributeStub); + $replaceMapping = [ + '{{ AttributeName }}' => $attributeName, + '{{ AttributeString }}' => $attributeString, + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $attributeStub); } } From c8d307dd2300b6fb7e68bf0003f60ce3cfb1c13b Mon Sep 17 00:00:00 2001 From: Mahmoudzadeh Date: Sat, 13 Jan 2024 02:13:08 +0330 Subject: [PATCH 79/86] refactor(Command): modify and refactor BaseCreator --- src/Creators/BaseCreator.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 25503cb..4a7ade5 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -2,11 +2,7 @@ namespace Eghamat24\DatabaseRepository\Creators; -use Illuminate\Support\Str; -use Illuminate\Console\Command; use Eghamat24\DatabaseRepository\Commands\BaseCommand; -use Eghamat24\DatabaseRepository\Utility; -use function Eghamat24\DatabaseRepository\Commands\config; class BaseCreator extends BaseCommand { @@ -17,10 +13,10 @@ class BaseCreator extends BaseCommand const SINGLE_KEY_CACHE_STRATEGY = 'SingleKeyCacheStrategy'; private $creator; - private null|string $choice = null; public function __construct(IClassCreator $creator) { + parent::__construct(); $this->creator = $creator; } From 79824aec7a00ba0d9f7c7376257b097f1f1d4646 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sun, 14 Apr 2024 19:44:35 +0330 Subject: [PATCH 80/86] support Laravel 11 --- composer.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index 5cde4a1..3c4d18f 100644 --- a/composer.json +++ b/composer.json @@ -13,13 +13,13 @@ "php": "^8.1", "ext-pdo": "*", "ext-json": "*", - "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0", - "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0", - "illuminate/cache": "^6.0|^7.0|^8.0|^9.0|^10.0", - "illuminate/database": "^6.0|^7.0|^8.0|^9.0|^10.0" + "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/cache": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "illuminate/database": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0" }, "require-dev": { - "laravel/framework": "^8.0|^9.0|^10.0" + "laravel/framework": "^8.0|^9.0|^10.0|^11.0" }, "autoload": { "psr-4": { From 7d894fc9a2ca069298732c639e6abb6ad4d19723 Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sun, 14 Apr 2024 19:50:36 +0330 Subject: [PATCH 81/86] Bug fix MakeEntity --- src/Commands/MakeEntity.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 0c10362..ff33083 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -97,6 +97,7 @@ private function getCreatorEntity(Collection $columns): CreatorEntity * @return string */ private function getBaseContent(CreatorEntity $entityCreator, string $filenameWithPath): string + { $creator = new BaseCreator($entityCreator); return $creator->createClass($filenameWithPath, $this); } From 135f2e3dc15208c045554a41da75eb6551d0498c Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sun, 12 May 2024 18:43:58 +0330 Subject: [PATCH 82/86] cache strategy name is optional --- src/Commands/MakeAll.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index 07adebc..69ed5e2 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -42,7 +42,9 @@ public function handle() 'TemporaryCacheStrategy' ]; - if (in_array($this->option('strategy_name'), $strategyNames) === false) { + $strategy = $this->option('strategy_name'); + + if ($strategy !== null && in_array($strategy, $strategyNames) === false) { $this->alert('This pattern strategy does not exist !!! '); exit; } @@ -53,7 +55,6 @@ public function handle() $delete = $this->option('delete'); $detectForeignKeys = $this->option('foreign-keys'); $addToGit = $this->option('add-to-git'); - $strategy = $this->option('strategy_name'); if ($this->option('all-tables')) { $tableNames = $this->getAllTableNames()->pluck('TABLE_NAME'); @@ -93,10 +94,13 @@ private function runCommandsWithArguments(array $arguments, bool|array|string|nu 'repository:make-resource' => $arguments, 'repository:make-interface-repository' => $arguments, 'repository:make-mysql-repository' => $arguments, - 'repository:make-redis-repository' => $arguments + ['strategy' => $strategy], 'repository:make-repository' => $arguments + ['strategy' => $strategy, 'selected_db' => $selectedDb] ]; + if ($strategy !== null) { + $commands['repository:make-redis-repository'] = $arguments + ['strategy' => $strategy]; + } + foreach ($commands as $command => $args) { $this->call($command, $args); } From 72557c9637e369b31fdbd9963758ffddc4263813 Mon Sep 17 00:00:00 2001 From: Amir Najmi Date: Sat, 14 Sep 2024 13:25:39 +0330 Subject: [PATCH 83/86] Add decimal data type --- src/CustomMySqlQueries.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/CustomMySqlQueries.php b/src/CustomMySqlQueries.php index 1192503..5c999d5 100644 --- a/src/CustomMySqlQueries.php +++ b/src/CustomMySqlQueries.php @@ -19,6 +19,7 @@ trait CustomMySqlQueries 'mediumint' => 'int', 'bigint' => 'int', 'float' => 'float', + 'decimal' => 'float', 'double' => 'float', 'json' => 'string', 'char' => 'string', From 84eaf9180afcb2466151d43d9bf345c5cb55db41 Mon Sep 17 00:00:00 2001 From: Amir Najmi Date: Sat, 14 Sep 2024 14:22:11 +0330 Subject: [PATCH 84/86] fix condition for create repository class --- src/Commands/BaseCommand.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Commands/BaseCommand.php b/src/Commands/BaseCommand.php index d0a7717..2930ed5 100644 --- a/src/Commands/BaseCommand.php +++ b/src/Commands/BaseCommand.php @@ -141,7 +141,7 @@ public function checkDatabasesExist() $mysql = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . 'MySql' . $entityName . 'Repository.php'; $redis = config('repository.path.relative.repositories') . DIRECTORY_SEPARATOR . $entityName . DIRECTORY_SEPARATOR . 'Redis' . $entityName . 'Repository.php'; - if (!(file_exists($mysql) && file_exists($redis))) { + if (!(file_exists($mysql) || file_exists($redis))) { $this->alert("First create the class databases!!!"); exit; } From d839a795833e4276f9abe7fffb80b77fde2a908e Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Sat, 2 Nov 2024 18:03:23 +0330 Subject: [PATCH 85/86] feat: remove set and get functions --- src/Creators/BaseCreator.php | 9 +++- src/Creators/CreatorEntity.php | 49 +------------------- src/Creators/CreatorFactory.php | 37 +++++++-------- src/Creators/CreatorMySqlRepository.php | 24 ++-------- src/Creators/CreatorResource.php | 8 ++-- src/Models/Entity/Entity.php | 18 ------- stubs/Entities/entity.attribute.stub | 2 +- stubs/Entities/entity.getter.stub | 4 -- stubs/Entities/entity.setter.stub | 4 -- stubs/Factories/factory.class.stub | 2 +- stubs/Factories/factory.set.stub | 1 + stubs/Factories/factory.setter.stub | 1 - stubs/Repositories/Mysql/mysql.create.stub | 2 +- stubs/Repositories/Mysql/mysql.getter.stub | 2 +- stubs/Repositories/Mysql/mysql.setter.stub | 2 +- stubs/Resources/resource.getter.default.stub | 2 +- 16 files changed, 40 insertions(+), 127 deletions(-) delete mode 100644 stubs/Entities/entity.getter.stub delete mode 100644 stubs/Entities/entity.setter.stub create mode 100644 stubs/Factories/factory.set.stub delete mode 100644 stubs/Factories/factory.setter.stub diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php index 4a7ade5..64e93ad 100644 --- a/src/Creators/BaseCreator.php +++ b/src/Creators/BaseCreator.php @@ -33,8 +33,13 @@ public function createClass(string $filenameWithPath, BaseCommand $command): str $attributesArray = $this->checkDiffrence($filenameWithPath, $attributesArray, $command, $specificPattern, $generalPattern); $attributes = trim(implode("\n\t", $attributesArray)); - $functions = trim(implode("\n", $functionsArray)); - $functions = (!empty($attributes)) ? "\n\n\t" . $functions : $functions; + + $functions = ''; + if (count($functionsArray) > 0) { + $functions = trim(implode("\n", $functionsArray)); + $functions = (!empty($attributes)) ? "\n\n\t" . $functions : $functions; + } + $uses = implode(PHP_EOL, $usesArray); $type = (isset($this->creator->enum)) ? self::ENUM_TYPE : self::CLASS_TYPE; diff --git a/src/Creators/CreatorEntity.php b/src/Creators/CreatorEntity.php index ed404c4..d6c2195 100644 --- a/src/Creators/CreatorEntity.php +++ b/src/Creators/CreatorEntity.php @@ -97,54 +97,7 @@ public function createUses(): array public function createFunctions(): array { - $settersAndGetters = []; - - foreach ($this->columns as $_column) { - $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); - - $settersAndGetters['get' . ucwords($_column->COLUMN_NAME)] = - $this->writeAccessors( - $this->entityStubsPath, - $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, - 'getter' - ); - - $settersAndGetters['set' . ucwords($_column->COLUMN_NAME)] = - $this->writeAccessors( - $this->entityStubsPath, - $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType, - 'setter' - ); - - } - - if ($this->detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($this->tableName); - - // Create Additional Setters and Getters from Foreign keys - foreach ($foreignKeys as $_foreignKey) { - - $settersAndGetters['get' . ucwords($_foreignKey->COLUMN_NAME)] = - $this->writeAccessors( - $this->entityStubsPath, - $_foreignKey->VARIABLE_NAME, - $_foreignKey->ENTITY_DATA_TYPE, - 'getter' - ); - - $settersAndGetters['set' . ucwords($_foreignKey->COLUMN_NAME)] = - $this->writeAccessors( - $this->entityStubsPath, - $_foreignKey->VARIABLE_NAME, - $_foreignKey->ENTITY_DATA_TYPE, - 'setter' - ); - } - } - - return $settersAndGetters; + return []; } private function writeAttribute(string $entityStubsPath, string $attributeName, string $attributeType): string diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php index 12d69fb..f7d7e6e 100644 --- a/src/Creators/CreatorFactory.php +++ b/src/Creators/CreatorFactory.php @@ -28,23 +28,28 @@ public function getNameSpace(): string public function createAttributes(): array { - // TODO: Implement createAttributs() method. - return []; - } - - public function createFunctions(): array - { - $setterStub = file_get_contents($this->factoryStubsPath . 'setter.stub'); - $setterFunctions = ''; + $setStub = file_get_contents($this->factoryStubsPath . 'set.stub'); + $sets = ''; foreach ($this->columns as $_column) { - $setterFunctions .= trim($this->writeSetter($setterStub, $_column->COLUMN_NAME)) . "\n\t\t"; + $replacementTokens = [ + '{{ AttributeName }}' => Str::camel($_column->COLUMN_NAME), + '{{ DatabaseAttributeName }}' => Str::snake($_column->COLUMN_NAME) + ]; + + $sets .= str_replace(array_keys($replacementTokens), array_values($replacementTokens), $setStub) . "\t\t"; } return ['makeEntityFromStdClass' => - str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityVariableName }}'], - [$setterFunctions, $this->entityName, $this->entityVariableName], + str_replace(['{{ Sets }}', '{{ EntityName }}', '{{ EntityVariableName }}'], + [$sets, $this->entityName, $this->entityVariableName], $this->baseContent) ]; + return []; + } + + public function createFunctions(): array + { + return []; } public function createUses(): array @@ -62,16 +67,6 @@ public function getExtendSection(): string return 'extends ' . self::PARENT_NAME; } - public function writeSetter(string $setterStub, string $columnName): string - { - $replacementTokens = [ - '{{ SetterName }}' => ucfirst($columnName), - '{{ AttributeName }}' => Str::snake($columnName) - ]; - - return str_replace(array_keys($replacementTokens), array_values($replacementTokens), $setterStub); - } - public function getClassName(): string { return $this->factoryName; diff --git a/src/Creators/CreatorMySqlRepository.php b/src/Creators/CreatorMySqlRepository.php index ef74172..d1e94c4 100644 --- a/src/Creators/CreatorMySqlRepository.php +++ b/src/Creators/CreatorMySqlRepository.php @@ -153,21 +153,7 @@ private function writeGetAllFunction(string $getOneStub, string $columnName, str $getOneStub); } - private function writeGetterFunction(string $getterStub, string $columnName): string - { - return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], - [$columnName, ucfirst(Str::camel($columnName))], - $getterStub); - } - - private function writeSetterFunction(string $setterStub, string $columnName): string - { - return str_replace('{{ SetterName }}', - ucfirst(Str::camel($columnName)), - $setterStub); - } - - private function getConstruct(string $tableName, string $factoryName, bool $hasSoftDelete, string $constructContent) + private function getConstruct(string $tableName, string $factoryName, bool $hasSoftDelete, string $constructContent) { return str_replace( ['{{ TableName }}', '{{ FactoryName }}', '{{ HasSoftDelete }}'], @@ -186,11 +172,11 @@ public function makeCreateFunction(array &$stubContent, string &$getterFunctions { foreach ($this->columns as $_column) { if (!in_array($_column->COLUMN_NAME, ['id', 'deleted_at'])) { - $getterFunctions .= trim($this->writeGetterFunction($stubContent['getterStub'], $_column->COLUMN_NAME)) . "\n\t\t\t\t"; + $getterFunctions .= trim(str_replace(['{{ ColumnName }}', '{{ AttributeName }}'], [$_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)], $stubContent['getterStub'])) . "\n\t\t\t\t"; } if (in_array($_column->COLUMN_NAME, ['created_at', 'updated_at'], true)) { - $setterFunctions .= trim($this->writeSetterFunction($stubContent['setterStub'], $_column->COLUMN_NAME)) . "\n\t\t"; + $setterFunctions .= trim(str_replace('{{ AttributeName }}', Str::camel($_column->COLUMN_NAME), $stubContent['setterStub'])) . "\n\t\t"; } } @@ -216,11 +202,11 @@ public function makeUpdateFunction(array &$stubContent, string &$getterFunctions foreach ($this->columns as $_column) { if (!in_array($_column->COLUMN_NAME, ['id', 'created_at', 'deleted_at'])) { - $getterFunctions .= trim($this->writeGetterFunction($stubContent['getterStub'], $_column->COLUMN_NAME)) . "\n\t\t\t\t"; + $getterFunctions .= trim(str_replace(['{{ ColumnName }}', '{{ AttributeName }}'], [$_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)], $stubContent['getterStub'])) . "\n\t\t\t\t";; } if ($_column->COLUMN_NAME === 'updated_at') { - $setterFunctions .= trim($this->writeSetterFunction($stubContent['setterStub'], $_column->COLUMN_NAME)) . "\n\t\t"; + $setterFunctions .= trim(str_replace('{{ AttributeName }}', Str::camel($_column->COLUMN_NAME), $stubContent['setterStub'])). "\n\t\t";; } } diff --git a/src/Creators/CreatorResource.php b/src/Creators/CreatorResource.php index 1c58784..3641637 100644 --- a/src/Creators/CreatorResource.php +++ b/src/Creators/CreatorResource.php @@ -55,14 +55,14 @@ public function createAttributes(): array public function createFunctions(): array { - $getterStub = file_get_contents($this->resourceStubsPath . 'getter.default.stub'); + $getsStub = file_get_contents($this->resourceStubsPath . 'getter.default.stub'); $foreignGetterStub = file_get_contents($this->resourceStubsPath . 'getter.foreign.stub'); $foreignFunStub = file_get_contents($this->resourceStubsPath . 'function.foreign.stub'); $getterFunStub = file_get_contents($this->resourceStubsPath . 'function.getter.stub'); $getters = ''; foreach ($this->columns as $_column) { - $getters .= $this->writeGetter($getterStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)) . "\t\t\t"; + $getters .= $this->writeGet($getsStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)) . "\t\t\t"; } $foreignGetterFunctions = ''; @@ -82,11 +82,11 @@ public function createFunctions(): array return $functions; } - public function writeGetter(string $getterStub, string $columnName, string $attributeName): array|string + public function writeGet(string $getterStub, string $columnName, string $attributeName): array|string { $replaceMapping = [ '{{ ColumnName }}' => $columnName, - '{{ GetterName }}' => ucfirst($attributeName), + '{{ AttributeName }}' => Str::camel($attributeName), ]; return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $getterStub); diff --git a/src/Models/Entity/Entity.php b/src/Models/Entity/Entity.php index 0e3d0a4..05c31ad 100644 --- a/src/Models/Entity/Entity.php +++ b/src/Models/Entity/Entity.php @@ -11,29 +11,11 @@ abstract class Entity implements JsonSerializable, Arrayable // contain originals value of attributes private $originals = []; - abstract public function getId(): int; - public function __construct() { } - public function __set($name, $value) - { - if (property_exists($this, $name)) { - $function = Str::camel('set_' . Str::snake($name)); - $this->$function($value); - } - } - - public function __get($name) - { - if (property_exists($this, $name)) { - $function = Str::camel('get_' . Str::snake($name)); - return $this->$function(); - } - } - public function __isset($name) { return property_exists($this, $name); diff --git a/stubs/Entities/entity.attribute.stub b/stubs/Entities/entity.attribute.stub index 47de060..7fddb47 100644 --- a/stubs/Entities/entity.attribute.stub +++ b/stubs/Entities/entity.attribute.stub @@ -1 +1 @@ -protected {{ AttributeType }} ${{ AttributeName }}; +public {{ AttributeType }} ${{ AttributeName }}; diff --git a/stubs/Entities/entity.getter.stub b/stubs/Entities/entity.getter.stub deleted file mode 100644 index a9a8bc5..0000000 --- a/stubs/Entities/entity.getter.stub +++ /dev/null @@ -1,4 +0,0 @@ - public function get{{ GetterName }}(): {{ AttributeType }} - { - return $this->{{ AttributeName }}; - } diff --git a/stubs/Entities/entity.setter.stub b/stubs/Entities/entity.setter.stub deleted file mode 100644 index 7865c08..0000000 --- a/stubs/Entities/entity.setter.stub +++ /dev/null @@ -1,4 +0,0 @@ - public function set{{ SetterName }}({{ AttributeType }} ${{ AttributeName }}): void - { - $this->{{ AttributeName }} = ${{ AttributeName }}; - } diff --git a/stubs/Factories/factory.class.stub b/stubs/Factories/factory.class.stub index c2d5c5f..351d8c1 100644 --- a/stubs/Factories/factory.class.stub +++ b/stubs/Factories/factory.class.stub @@ -2,6 +2,6 @@ { ${{ EntityVariableName }} = new {{ EntityName }}(); - {{ SetterFunctions }} + {{ Sets }} return ${{ EntityVariableName }}; } diff --git a/stubs/Factories/factory.set.stub b/stubs/Factories/factory.set.stub new file mode 100644 index 0000000..44d39cb --- /dev/null +++ b/stubs/Factories/factory.set.stub @@ -0,0 +1 @@ +${{ EntityVariableName }}->{{ AttributeName }} = $entity->{{ DatabaseAttributeName }}; diff --git a/stubs/Factories/factory.setter.stub b/stubs/Factories/factory.setter.stub deleted file mode 100644 index 657234c..0000000 --- a/stubs/Factories/factory.setter.stub +++ /dev/null @@ -1 +0,0 @@ -${{ EntityVariableName }}->set{{ SetterName }}($entity->{{ AttributeName }}); diff --git a/stubs/Repositories/Mysql/mysql.create.stub b/stubs/Repositories/Mysql/mysql.create.stub index c70bd9c..f7113c9 100644 --- a/stubs/Repositories/Mysql/mysql.create.stub +++ b/stubs/Repositories/Mysql/mysql.create.stub @@ -7,7 +7,7 @@ {{ GetterFunctions }} ]); - ${{ EntityVariableName }}->setId($id); + ${{ EntityVariableName }}->id = $id; return ${{ EntityVariableName }}; } diff --git a/stubs/Repositories/Mysql/mysql.getter.stub b/stubs/Repositories/Mysql/mysql.getter.stub index fccab8d..8862049 100644 --- a/stubs/Repositories/Mysql/mysql.getter.stub +++ b/stubs/Repositories/Mysql/mysql.getter.stub @@ -1 +1 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), + '{{ ColumnName }}' => ${{ EntityVariableName }}->{{ AttributeName }}, diff --git a/stubs/Repositories/Mysql/mysql.setter.stub b/stubs/Repositories/Mysql/mysql.setter.stub index 2b886d7..419d6c1 100644 --- a/stubs/Repositories/Mysql/mysql.setter.stub +++ b/stubs/Repositories/Mysql/mysql.setter.stub @@ -1 +1 @@ - ${{ EntityVariableName }}->set{{ SetterName }}(date('Y-m-d H:i:s')); + ${{ EntityVariableName }}->{{ AttributeName }} = date('Y-m-d H:i:s'); diff --git a/stubs/Resources/resource.getter.default.stub b/stubs/Resources/resource.getter.default.stub index dbbc815..ed6b4fa 100644 --- a/stubs/Resources/resource.getter.default.stub +++ b/stubs/Resources/resource.getter.default.stub @@ -1 +1 @@ -'{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), +'{{ ColumnName }}' => ${{ EntityVariableName }}->{{ AttributeName }}, From 1e09ae4077e8fd2aa62c89f266ff83136008cb6a Mon Sep 17 00:00:00 2001 From: Mahdi Bagheri Date: Wed, 5 Mar 2025 16:55:06 +0330 Subject: [PATCH 86/86] add Laravel 12 support --- composer.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index 3c4d18f..9f3d594 100644 --- a/composer.json +++ b/composer.json @@ -13,13 +13,13 @@ "php": "^8.1", "ext-pdo": "*", "ext-json": "*", - "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", - "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", - "illuminate/cache": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", - "illuminate/database": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0" + "illuminate/console": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0", + "illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0", + "illuminate/cache": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0", + "illuminate/database": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0" }, "require-dev": { - "laravel/framework": "^8.0|^9.0|^10.0|^11.0" + "laravel/framework": "^8.0|^9.0|^10.0|^11.0|^12.0" }, "autoload": { "psr-4": { pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy