diff --git a/Readme.md b/Readme.md index 56ff5bd..c2c292a 100644 --- a/Readme.md +++ b/Readme.md @@ -1,58 +1,94 @@ # 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 +composer require eghamat24/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. +Then run the following command in the console to publish the necessary assets in your project directory. ```bash -php artisan vendor:publish --provider=Nanvaie\DatabaseRepository\DatabaseRepositoryServiceProvider +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')) { - $app->register(Nanvaie\DatabaseRepository\DatabaseRepositoryServiceProvider::class); + $app->register(Eghamat24\DatabaseRepository\DatabaseRepositoryServiceProvider::class); } // 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 | -|----------------------------------------|-------------|----------------|-----------------------------------| -| `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, 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. - `-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 -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 an enabled foreign key option(this may be used for new projects). +```bash +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 +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 users customers -k +php artisan repository:make-all --table_names=users --strategy_name=QueryCacheStrategy ``` diff --git a/composer.json b/composer.json index 5684497..9f3d594 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", @@ -10,22 +10,26 @@ } ], "require": { - "php": "^7.0|^8.0", + "php": "^8.1", "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": "^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|^12.0" }, "autoload": { "psr-4": { - "Nanvaie\\DatabaseRepository\\": "src/" + "Eghamat24\\DatabaseRepository\\": "src/" } }, "extra": { "laravel": { "providers": [ - "Nanvaie\\DatabaseRepository\\DatabaseRepositoryServiceProvider" + "Eghamat24\\DatabaseRepository\\DatabaseRepositoryServiceProvider" ] } } diff --git a/config/repository.php b/config/repository.php index 9f5f1be..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', @@ -14,13 +16,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/BaseCommand.php b/src/Commands/BaseCommand.php new file mode 100644 index 0000000..2930ed5 --- /dev/null +++ b/src/Commands/BaseCommand.php @@ -0,0 +1,150 @@ +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))); + $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'); + if ($this->hasArgument('strategy')) { + $this->strategyName = $this->argument('strategy'); + } + } + + public function checkDelete(string $filenameWithPath, string $entityName, string $objectName): void + { + if (file_exists($filenameWithPath) && $this->option('delete')) { + \unlink($filenameWithPath); + $this->info("$objectName '$entityName' has been deleted."); + } + } + + public function checkDirectory(string $relativeEntitiesPath): void + { + if (!file_exists($relativeEntitiesPath) && !mkdir($relativeEntitiesPath, 0775, true) && !is_dir($relativeEntitiesPath)) { + $this->alert("Directory \"$relativeEntitiesPath\" was not created"); + exit; + } + } + + 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): void + { + file_put_contents($filenameWithPath, $baseContent); + if ($this->option('add-to-git')) { + shell_exec('git add ' . $filenameWithPath); + } + + $this->info("\"$entityName\" has been created."); + } + + 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."); + exit; + } + } + + public function setChoice($choice): void + { + \config(['replacement.choice' => $choice]); + } + + public function getChoice(): null|string + { + return \config('replacement.choice'); + } + + public function checkStrategyName() + { + $strategyNames = [ + '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 = 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; + } + } + +} diff --git a/src/Commands/MakeAll.php b/src/Commands/MakeAll.php index b6c2760..69ed5e2 100644 --- a/src/Commands/MakeAll.php +++ b/src/Commands/MakeAll.php @@ -1,21 +1,27 @@ argument('table_names'); + $strategyNames = [ + 'ClearableTemporaryCacheStrategy', + 'QueryCacheStrategy', + 'SingleKeyCacheStrategy', + 'TemporaryCacheStrategy' + ]; + + $strategy = $this->option('strategy_name'); + + if ($strategy !== null && in_array($strategy, $strategyNames) === false) { + $this->alert('This pattern strategy does not exist !!! '); + exit; + } + + $selectedDb = $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'); + 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, '--foreign-keys' => $detectForeignKeys, @@ -44,13 +75,34 @@ public function handle() '--add-to-git' => $addToGit ]; - $this->call('repository:make-entity', $arguments); - $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); + $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-mysql-repository' => $arguments, + '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); } } } diff --git a/src/Commands/MakeEntity.php b/src/Commands/MakeEntity.php index 868523b..ff33083 100644 --- a/src/Commands/MakeEntity.php +++ b/src/Commands/MakeEntity.php @@ -1,12 +1,19 @@ argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $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'; - - if ($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; - } - - $columns = $this->getAllColumnsInTable($tableName); - - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table \"$tableName\"! Perhaps table's name is misspelled."); - die; - } - - foreach ($columns as $_column) { - $_column->COLUMN_NAME = camel_case($_column->COLUMN_NAME); - } + $this->setArguments(); + $filenameWithPath = $this->relativeEntitiesPath . $this->entityName . '.php'; - $baseContent = file_get_contents($entityStubsPath.'class.stub'); - $attributeStub = file_get_contents($entityStubsPath.'attribute.stub'); - $accessorsStub = file_get_contents($entityStubsPath.'accessors.stub'); + $this->checkAndPrepare($filenameWithPath); + $columns = $this->getColumnsOf($this->tableName); - // Create Attributes - $attributes = ''; foreach ($columns as $_column) { - $attributes .= $this->writeAttribute( - $attributeStub, - $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? '?' : '') . $this->dataTypes[$_column->DATA_TYPE] - ); + $_column->COLUMN_NAME = Str::camel($_column->COLUMN_NAME); } - // Create Setters and Getters - $settersAndGetters = ''; - foreach ($columns as $_column) { - $settersAndGetters .= $this->writeAccessors( - $accessorsStub, - $_column->COLUMN_NAME, - ($_column->IS_NULLABLE === 'YES' ? '?' : '') . $this->dataTypes[$_column->DATA_TYPE] - ); - } + $entityCreator = $this->getCreatorEntity($columns); + $baseContent = $this->getBaseContent($entityCreator, $filenameWithPath); - 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 - ); - } - } + $this->finalized($filenameWithPath, $this->entityName, $baseContent); + } - $baseContent = str_replace(['{{ EntityNamespace }}', '{{ EntityName }}', '{{ Attributes }}', '{{ SettersAndGetters }}'], - [$entityNamespace, $entityName, $attributes, $settersAndGetters], - $baseContent); + /** + * @param string $tableName + * @return Collection + */ + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); - file_put_contents($filenameWithPath, $baseContent); + return $columns; + } - if ($this->option('add-to-git')) { - shell_exec('git add '.$filenameWithPath); - } + /** + * @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); + } - $this->info("Entity \"$entityName\" has been created."); + /** + * @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 + ); + } - return 0; + /** + * @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); } } diff --git a/src/Commands/MakeEnum.php b/src/Commands/MakeEnum.php new file mode 100644 index 0000000..f68d7b8 --- /dev/null +++ b/src/Commands/MakeEnum.php @@ -0,0 +1,130 @@ +setArguments(); + $columns = $this->getColumnsOf($this->tableName); + $enums = $this->extractEnumsFromColumns($columns); + + $attributeStub = file_get_contents($this->enumStubPath . 'attribute.stub'); + + foreach ($enums as $enumName => $enum) { + $filenameWithPath = $this->relativeEnumsPath . $enumName . '.php'; + + $this->checkAndPrepare($enumName); + $baseContent = $this->getBaseCreator($columns, $attributeStub, $enum, $enumName) + ->createClass($filenameWithPath, $this); + + $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, + self::OBJECT_NAME + ); + } + + 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) . self::OBJECT_NAME; + } + + private function extractEnumValues($columnType): array + { + $items = explode(',', str_replace(['enum(', '\'', ')'], ['', '', ''], $columnType)); + + 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); + } + + /** + * @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/MakeFactory.php b/src/Commands/MakeFactory.php index 5f5a3c0..2bdc259 100644 --- a/src/Commands/MakeFactory.php +++ b/src/Commands/MakeFactory.php @@ -1,12 +1,19 @@ argument('table_name'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($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'); - $phpVersion = config('repository.php_version'); - $filenameWithPath = $relativeFactoriesPath.$factoryName.'.php'; - - if ($this->option('delete')) { - unlink("$relativeFactoriesPath/$factoryName.php"); - $this->info("Factory \"$factoryName\" has been deleted."); - return 0; - } + $this->setArguments(); - 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->checkAndPrepare($filenameWithPath); - $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->getColumnsOf($this->tableName); 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'); - $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); - } + $factoryCreator = $this->getCreatorFactory($columns, $baseContent); + $baseContent = $this->generateBaseContent($factoryCreator, $filenameWithPath); - $baseContent = str_replace(['{{ SetterFunctions }}', '{{ EntityName }}', '{{ EntityNamespace }}', '{{ FactoryName }}', '{{ FactoryNamespace }}', '{{ EntityVariableName }}'], - [$setterFunctions, $entityName, $entityNamespace, $factoryName, $factoryNamespace, $entityVariableName], - $baseContent); + $this->finalized($filenameWithPath, $this->factoryName, $baseContent); + } - file_put_contents($filenameWithPath, $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); + } - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } + /** + * @param string $tableName + * @return Collection + */ + public function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); - $this->info("Factory \"$factoryName\" has been created."); + return $columns; + } - return 0; + /** + * @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, + $this->factoryStubsPath, + $this->factoryNamespace, + $this->entityVariableName, + $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); } -} \ No newline at end of file +} diff --git a/src/Commands/MakeInterfaceRepository.php b/src/Commands/MakeInterfaceRepository.php index 1f36379..4fe5e84 100644 --- a/src/Commands/MakeInterfaceRepository.php +++ b/src/Commands/MakeInterfaceRepository.php @@ -1,12 +1,16 @@ 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 writeGetAllFunction(string $getOneStub, string $columnName, string $attributeType): string + private function writeFunctionOnBaseContent($baseContent, string $writeFunction): string|array { - return str_replace(['{{ FunctionNamePlural }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}'], - [ucfirst(str_plural(camel_case($columnName))), $attributeType, str_plural(camel_case($columnName))], - $getOneStub); + return \substr_replace($baseContent, $writeFunction, -2, 0); } - /** - * Execute the console command. - * - * @return int - */ - public function handle(): int + private function writeFunction(string $stub, string $columnName, string $attributeType, array $placeHolders): array|string { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); - $interfaceName = "I$entityName"."Repository"; - $entityNamespace = config('repository.path.namespace.entities'); - $repositoryNamespace = config('repository.path.namespace.repositories'); - $relativeInterfacePath = config('repository.path.relative.repositories') . "$entityName"; - $interfaceRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.interface'); - $filenameWithPath = $relativeInterfacePath . '/' . $interfaceName.'.php'; - - if ($this->option('delete')) { - unlink("$relativeInterfacePath/$interfaceName.php"); - $this->info("Interface \"$interfaceName\" has been deleted."); - return 0; - } + $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); + } - if ( ! file_exists($relativeInterfacePath) && ! mkdir($relativeInterfacePath, 0775, true) && ! is_dir($relativeInterfacePath)) { - $this->alert("Directory \"$relativeInterfacePath\" was not created"); - return 0; - } + private function writeGetOneFunction(string $getOneStub, string $columnName, string $attributeType): string + { + $placeHolders = ['{{ FunctionName }}', '{{ ColumnName }}', '{{ AttributeType }}', '{{ AttributeName }}']; + return $this->writeFunction($getOneStub, $columnName, $attributeType, $placeHolders); + } - if (class_exists("$relativeInterfacePath\\$interfaceName") && ! $this->option('force')) { - $this->alert("Interface $interfaceName is already exist!"); - return 0; - } + private function writeGetAllFunction(string $getAllStub, string $columnName, string $attributeType): string + { + $placeHolders = ['{{ FunctionNamePlural }}', '{{ AttributeType }}', '{{ AttributeNamePlural }}']; + return $this->writeFunction($getAllStub, $columnName, $attributeType, $placeHolders); + } + private function getColumnsOf(string $tableName): Collection + { $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); + + 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'); + } - if ($columns->isEmpty()) { - $this->alert("Couldn't retrieve columns from table ".$tableName."! Perhaps table's name is misspelled."); - die; + 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 ($detectForeignKeys) { - $foreignKeys = $this->extractForeignKeys($tableName); + if (in_array('updated_at', $allColumns, true)) { + $baseContent = substr_replace($baseContent, $updateFunctionStub, -2, 0); } - $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) { - 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); - } + if (in_array('deleted_at', $allColumns, true)) { + $baseContent = substr_replace($baseContent, $deleteAndUndeleteStub, -2, 0); } - $allColumns = $columns->pluck('COLUMN_NAME')->toArray(); + return $baseContent; + } - if (in_array('created_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $createFunctionStub, -1, 0); + 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); } - if (in_array('updated_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $updateFunctionStub, -1, 0); + return $stubsContent; + } + + 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); + } + + private function writeGetFunctionByIndexColumnOnBaseContent(Collection $indexes, Collection $columns, mixed $baseContent, $getOneStub, $getAllStub): mixed + { + foreach ($indexes as $index) { + $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 = $this->writeFunctionOnBaseContent($baseContent, + $this->writeGetOneFunction( + $getAllStub, $index->COLUMN_NAME, $this->getDataType($columnInfo->COLUMN_TYPE, $columnInfo->DATA_TYPE) + ) + ); + } } - if (in_array('deleted_at', $allColumns, true)) { - $baseContent = substr_replace($baseContent, $deleteAndUndeleteStub, -1, 0); + return $baseContent; + } + + public function writeGetFunctionByForeignKeyOnBaseContent(array|string $baseContent, $getOneStub, $getAllStub): string|array + { + if (empty($this->detectForeignKeys)) { + return $baseContent; } - $baseContent = str_replace(['{{ EntityName }}', '{{ EntityNamespace }}', '{{ EntityVariableName }}', '{{ InterfaceRepositoryName }}', '{{ RepositoryNamespace }}'], - [$entityName, $entityNamespace, $entityVariableName, $interfaceName, $repositoryNamespace], - $baseContent); + $foreignKeys = $this->extractForeignKeys($this->tableName); - file_put_contents($filenameWithPath, $baseContent); + foreach ($foreignKeys as $_foreignKey) { - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } + $baseContent = $this->writeFunctionOnBaseContent( + $baseContent, $this->writeGetOneFunction($getOneStub, $_foreignKey->COLUMN_NAME, $this->entityName) + ); - $this->info("Interface \"$interfaceName\" has been created."); + $baseContent = $this->writeFunctionOnBaseContent( + $baseContent, $this->writeGetAllFunction($getAllStub, $_foreignKey->COLUMN_NAME, $this->entityName) + ); + } - return 0; + return $baseContent; } } diff --git a/src/Commands/MakeMySqlRepository.php b/src/Commands/MakeMySqlRepository.php index 25b40d6..3cc4971 100644 --- a/src/Commands/MakeMySqlRepository.php +++ b/src/Commands/MakeMySqlRepository.php @@ -1,12 +1,18 @@ setArguments(); - 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))], - $getOneStub); + $filenameWithPath = $this->getFileNameWithPath( + $this->relativeMysqlRepositoryPath, + $this->mysqlRepositoryName + ); + + $this->checkAndPrepare($filenameWithPath); + + $this->finalized( + $filenameWithPath, + $this->mysqlRepositoryName, + $this->generateBaseContent($filenameWithPath) + ); } - private function writeGetterFunction(string $getterStub, string $columnName): string + + private function getFileNameWithPath(string $relativePath, string $sectionName): string { - return str_replace(['{{ ColumnName }}', '{{ GetterName }}'], - [$columnName, ucfirst(camel_case($columnName))], - $getterStub); + return $relativePath . $sectionName . '.php'; } - private function writeSetterFunction(string $setterStub, string $columnName): string + + private function checkAndPrepare(string $filenameWithPath) { - return str_replace('{{ SetterName }}', - ucfirst(camel_case($columnName)), - $setterStub); + $this->checkDelete($filenameWithPath, $this->mysqlRepositoryName, self::OBJECT_NAME); + $this->checkDirectory($this->relativeMysqlRepositoryPath); + $this->checkClassExist($this->repositoryNamespace, $this->mysqlRepositoryName, self::OBJECT_NAME); } - /** - * Execute the console command. - * - * @return int - */ - 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'; - $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"; - $mysqlRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.mysql'); - $phpVersion = config('repository.php_version'); - $filenameWithPath = $relativeMysqlRepositoryPath . '/' . $mysqlRepositoryName.'.php'; - - if ($this->option('delete')) { - unlink("$relativeMysqlRepositoryPath/$mysqlRepositoryName.php"); - $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; - } + private function getColumnsOf(string $tableName): Collection + { $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $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 - ); - - $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); + return $columns; + } - file_put_contents($filenameWithPath, $baseContent); - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } + private function generateBaseContent(string $filenameWithPath): string + { + $mysqlRepoCreator = $this->makeMySqlRepoCreator(); - $this->info("MySql Repository \"$mysqlRepositoryName\" has been created."); + return (new BaseCreator($mysqlRepoCreator))->createClass($filenameWithPath, $this); + } - return 0; + /** + * @return CreatorMySqlRepository + */ + private function makeMySqlRepoCreator(): CreatorMySqlRepository + { + return new CreatorMySqlRepository( + $this->getColumnsOf($this->tableName), + $this->tableName, + $this->entityName, + $this->entityVariableName, + $this->factoryName, + $this->entityNamespace, + $this->factoryNamespace, + $this->mysqlRepositoryName, + $this->repositoryNamespace, + $this->interfaceName, + $this->mysqlRepositoryStubsPath, + $this->detectForeignKeys + ); } } diff --git a/src/Commands/MakeRedisRepository.php b/src/Commands/MakeRedisRepository.php index e4a24c1..df63ef8 100644 --- a/src/Commands/MakeRedisRepository.php +++ b/src/Commands/MakeRedisRepository.php @@ -1,18 +1,24 @@ 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"; + $this->checkStrategyName(); + $this->setArguments(); - if ($this->option('delete')) { - unlink("$relativeRedisRepositoryPath/$redisRepositoryName.php"); - $this->info("Redis Repository \"$redisRepositoryName\" has been deleted."); - return 0; - } + $redisRepositoryName = "Redis$this->entityName" . 'Repository'; + $relativeRedisRepositoryPath = config('repository.path.relative.repositories') . $this->entityName . DIRECTORY_SEPARATOR; + $filenameWithPath = $relativeRedisRepositoryPath . $redisRepositoryName . '.php'; - if ( ! file_exists($relativeRedisRepositoryPath) && ! mkdir($relativeRedisRepositoryPath, 0775, true) && ! is_dir($relativeRedisRepositoryPath)) { - $this->alert("Directory \"$relativeRedisRepositoryPath\" was not created"); - return 0; - } + $this->checkAndPrepare($filenameWithPath, $redisRepositoryName, $relativeRedisRepositoryPath); + $this->getColumnsOf($this->tableName); - if (class_exists("$relativeRedisRepositoryPath\\$redisRepositoryName") && ! $this->option('force')) { - $this->alert("Repository $redisRepositoryName is already exist!"); - return 0; - } + $redisRepositoryCreator = $this->getRedisRepositoryCreator($redisRepositoryName); + $baseContent = $this->getBaseContent($redisRepositoryCreator, $filenameWithPath); - $columns = $this->getAllColumnsInTable($tableName); + $this->finalized($filenameWithPath, $redisRepositoryName, $baseContent); + } - 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); - } + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); - // Initialize Redis Repository - $redisRepositoryContent = "option('add-to-git')) { - shell_exec("git add $relativeRedisRepositoryPath/$redisRepositoryName.php"); - } + 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 + ); + } - $this->info("Redis Repository \"$redisRepositoryName\" has been created."); + /** + * @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); + } - return 0; + /** + * @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); } } diff --git a/src/Commands/MakeRepository.php b/src/Commands/MakeRepository.php index 3f05afc..0f02aa3 100644 --- a/src/Commands/MakeRepository.php +++ b/src/Commands/MakeRepository.php @@ -1,18 +1,24 @@ checkDatabasesExist(); + $this->checkStrategyName(); - private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable): string - { - return str_replace(['{{ SqlRepositoryVariable }}'], - [$sqlRepositoryVariable], - $attributeStub); + $this->setArguments(); + $repositoryName = $this->entityName . self::OBJECT_NAME; + $relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR; + + $filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php'; + $this->checkAndPrepare($filenameWithPath, $repositoryName, $relativeRepositoryPath); + + $repositoryCreator = $this->getRepositoryCreator($repositoryName); + $baseContent = $this->createBaseContent($repositoryCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $repositoryName, $baseContent); } /** - * Execute the console command. - * - * @return int + * @param string $repositoryName + * @return CreatorRepository */ - public function handle(): int + private function getRepositoryCreator(string $repositoryName): CreatorRepository { - $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'; - $repositoryName = $entityName.'Repository'; - $sqlRepositoryName = 'MySql'.$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"; + $sqlRepositoryName = ucwords($this->selectedDb) . $repositoryName; $repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base'); - $filenameWithPath = $relativeRepositoryPath . DIRECTORY_SEPARATOR . $repositoryName . '.php'; - if ($this->option('delete')) { - unlink("$relativeRepositoryPath/$repositoryName.php"); - $this->info("Repository \"$repositoryName\" has been deleted."); - return 0; - } + return new CreatorRepository( + $this->getColumnsOf($this->tableName), + 'repository', + $sqlRepositoryName, + $repositoryStubsPath, + $this->detectForeignKeys, + $this->tableName, + $this->entityVariableName, + $this->entityName, + $this->entityNamespace, + $repositoryName, + $this->interfaceName, + $this->repositoryNamespace, + $this->selectedDb, + 'redisRepository', + 'Redis' . $repositoryName, + $this->strategyName + ); + } - if ( ! file_exists($relativeRepositoryPath) && ! mkdir($relativeRepositoryPath, 0775, true) && ! is_dir($relativeRepositoryPath)) { - $this->alert("Directory \"$relativeRepositoryPath\" was not created"); - return 0; - } + /** + * @param string $tableName + * @return Collection + */ + private function getColumnsOf(string $tableName): Collection + { + $columns = $this->getAllColumnsInTable($tableName); + $this->checkEmpty($columns, $tableName); - if (class_exists("$relativeRepositoryPath\\$repositoryName") && ! $this->option('force')) { - $this->alert("Repository $repositoryName is already exist!"); - return 0; - } + return $columns; + } - $columns = $this->getAllColumnsInTable($tableName); + /** + * @param CreatorRepository $RepoCreator + * @param string $filenameWithPath + * @return string + */ + private function createBaseContent(CreatorRepository $RepoCreator, string $filenameWithPath): string + { + $creator = new BaseCreator($RepoCreator); + return $creator->createClass($filenameWithPath, $this); + } - 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; + /** + * @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); } } diff --git a/src/Commands/MakeResource.php b/src/Commands/MakeResource.php index 64bab0f..9d04161 100644 --- a/src/Commands/MakeResource.php +++ b/src/Commands/MakeResource.php @@ -1,12 +1,18 @@ setArguments(); + $resourceName = $this->entityName . self::OBJECT_NAME; + $resourceNamespace = config('repository.path.namespace.resources'); + $relativeResourcesPath = config('repository.path.relative.resources'); + + $filenameWithPath = $relativeResourcesPath . $resourceName . '.php'; + + $this->checkAndPrepare($filenameWithPath, $resourceName, $relativeResourcesPath, $resourceNamespace); + + $RepoCreator = $this->getResourceCreator($resourceNamespace, $resourceName); + $baseContent = $this->generateBaseContent($RepoCreator, $filenameWithPath); + + $this->finalized($filenameWithPath, $resourceName, $baseContent); } - public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName) + /** + * @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 { - return str_replace(['{{ AttributeName }}', '{{ GetterName }}', '{{ AttributeType }}'], - [snake_case($columnName), ucfirst($columnName), ucfirst($attributeName)], - $foreignGetterStub); + $this->checkDelete($filenameWithPath, $resourceName, self::OBJECT_NAME); + $this->checkDirectory($relativeResourcesPath); + $this->checkClassExist($resourceNamespace, $resourceName, self::OBJECT_NAME); } /** - * Execute the console command. - * - * @return int + * @param string $tableName + * @return Collection */ - public function handle(): int + private function getColumnsOf(string $tableName): Collection { - $tableName = $this->argument('table_name'); - $detectForeignKeys = $this->option('foreign-keys'); - $entityName = str_singular(ucfirst(camel_case($tableName))); - $entityVariableName = camel_case($entityName); - $entityNamespace = config('repository.path.namespace.entities'); - $resourceName = $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 ($this->option('delete')) { - unlink("$relativeResourcesPath/$resourceName.php"); - $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); + $this->checkEmpty($columns, $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, camel_case($_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); + return $columns; + } - if ($this->option('add-to-git')) { - shell_exec("git add $filenameWithPath"); - } + /** + * @param mixed $resourceNamespace + * @param string $resourceName + * @return CreatorResource + */ + private function getResourceCreator(mixed $resourceNamespace, string $resourceName): CreatorResource + { + $resourceStubsPath = __DIR__ . '/../../' . config('repository.path.stub.resources'); - $this->info("Resource \"$resourceName\" has been created."); + return new CreatorResource($this->getColumnsOf($this->tableName), + $this->tableName, + $this->entityName, + $this->entityNamespace, + $resourceNamespace, + $resourceName, + $resourceStubsPath, + $this->detectForeignKeys, + $this->entityVariableName); + } - return 0; + /** + * @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); } + } diff --git a/src/Creators/BaseCreator.php b/src/Creators/BaseCreator.php new file mode 100644 index 0000000..64e93ad --- /dev/null +++ b/src/Creators/BaseCreator.php @@ -0,0 +1,113 @@ +creator = $creator; + } + + 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); + $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 = trim(implode("\n\t", $attributesArray)); + + $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; + $basePath = __DIR__ . "/../../stubs/base.$type.stub"; + + $this->creator->baseContent = str_replace(['{{ Namespace }}', '{{ UseSection }}', '{{ ClassName }}', '{{ ExtendSection }}', '{{ Parameters }}', '{{ Functions }}', '{{ CacheTag }}'], + [ + $this->creator->getNameSpace(), + $uses, + $this->creator->getClassName(), + $this->creator->getExtendSection(), + $attributes, + $functions, + $this->setCachetag($command) + ], + 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; $i < count($attributMatches['name']); $i++) { + if (array_search($this->getChoice(), 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->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] . "', "); + } + } + } + } + } + } + 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/CreatorEntity.php b/src/Creators/CreatorEntity.php new file mode 100644 index 0000000..d6c2195 --- /dev/null +++ b/src/Creators/CreatorEntity.php @@ -0,0 +1,138 @@ +columns as $_column) { + + $dataType = $this->getDataType($_column->COLUMN_TYPE, $_column->DATA_TYPE); + + $defaultValue = null; + if ($_column->COLUMN_DEFAULT !== null) { + $defaultValue = $_column->COLUMN_DEFAULT; + + if ($dataType === DataTypeEnum::INTEGER_TYPE) { + $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( + $this->entityStubsPath, + $columnString, + ($_column->IS_NULLABLE === 'YES' ? 'null|' : '') . $dataType + ); + } + + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); + + // Create Additional Attributes from Foreign Keys + foreach ($foreignKeys as $_foreignKey) { + $attributes[$_column->COLUMN_NAME] = + $this->writeAttribute( + $this->entityStubsPath, + $_foreignKey->VARIABLE_NAME, + $_foreignKey->ENTITY_DATA_TYPE + ); + } + } + + return $attributes; + } + + public function createUses(): array + { + return ['use Eghamat24\DatabaseRepository\Models\Entity\Entity;']; + } + + public function createFunctions(): array + { + return []; + } + + private function writeAttribute(string $entityStubsPath, string $attributeName, string $attributeType): string + { + $attributeStub = file_get_contents($entityStubsPath . 'attribute.stub'); + + $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'); + + $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 + { + 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..f03c3c1 --- /dev/null +++ b/src/Creators/CreatorEnum.php @@ -0,0 +1,69 @@ +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 []; + } + + public function getExtendSection(): string + { + return ''; + } + + public function getNameSpace(): string + { + return $this->enumNamespace; + } + + public function getClassName(): string + { + return $this->enumName . ' : string'; + } + + private function writeAttribute(string $attributeStub, string $attributeName, string $attributeString): string + { + $replaceMapping = [ + '{{ AttributeName }}' => $attributeName, + '{{ AttributeString }}' => $attributeString, + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $attributeStub); + } +} diff --git a/src/Creators/CreatorFactory.php b/src/Creators/CreatorFactory.php new file mode 100644 index 0000000..f7d7e6e --- /dev/null +++ b/src/Creators/CreatorFactory.php @@ -0,0 +1,74 @@ +factoryNamespace; + } + + public function createAttributes(): array + { + $setStub = file_get_contents($this->factoryStubsPath . 'set.stub'); + $sets = ''; + foreach ($this->columns as $_column) { + $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(['{{ Sets }}', '{{ EntityName }}', '{{ EntityVariableName }}'], + [$sets, $this->entityName, $this->entityVariableName], + $this->baseContent) + ]; + return []; + } + + public function createFunctions(): array + { + return []; + } + + public function createUses(): array + { + return [ + "use $this->entityNamespace\\$this->entityName;", + 'use Eghamat24\DatabaseRepository\Models\Factories\Factory;', + 'use stdClass;' + ]; + + } + + public function getExtendSection(): string + { + return 'extends ' . self::PARENT_NAME; + } + + 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..d1e94c4 --- /dev/null +++ b/src/Creators/CreatorMySqlRepository.php @@ -0,0 +1,222 @@ +repositoryNamespace . '\\' . $this->entityName; + } + + 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;' + ]; + } + + 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 + { + + $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); + } + + $hasSoftDelete = in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true); + + $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( + $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($stubContent['getAllStub'], $index->COLUMN_NAME, $this->entityName); + } + } + + if ($this->detectForeignKeys) { + $foreignKeys = $this->extractForeignKeys($this->tableName); + foreach ($foreignKeys as $_foreignKey) { + $indx = 'getOneBy' . ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); + $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($stubContent['getAllStub'], $_foreignKey->COLUMN_NAME, $this->entityName); + } + } + + $getterFunctions = ''; + $setterFunctions = ''; + $functions = $this->makeCreateFunction($stubContent, $getterFunctions, $setterFunctions, $functions); + + $getterFunctions = ''; + $setterFunctions = ''; + $functions = $this->makeUpdateFunction($stubContent, $getterFunctions, $setterFunctions, $functions); + + // Create "delete" and "undelete" functions if necessary + if ($hasSoftDelete) { + $functions['remove'] = $stubContent['deleteStub']; + $functions['restore'] = $stubContent['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 getConstruct(string $tableName, string $factoryName, bool $hasSoftDelete, string $constructContent) + { + return str_replace( + ['{{ TableName }}', '{{ FactoryName }}', '{{ HasSoftDelete }}'], + [$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(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(str_replace('{{ AttributeName }}', Str::camel($_column->COLUMN_NAME), $stubContent['setterStub'])) . "\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(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(str_replace('{{ AttributeName }}', Str::camel($_column->COLUMN_NAME), $stubContent['setterStub'])). "\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; + } +} diff --git a/src/Creators/CreatorRedisRepository.php b/src/Creators/CreatorRedisRepository.php new file mode 100644 index 0000000..a9f7f94 --- /dev/null +++ b/src/Creators/CreatorRedisRepository.php @@ -0,0 +1,59 @@ +redisRepositoryNamespace . '\\' . $this->entityName; + } + + public function createUses(): array + { + return [ + '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 createAttributes(): array + { + return []; + } + + public function createFunctions(): array + { + $constructStub = file_get_contents($this->repositoryStubsPath . 'construct_redis.stub'); + $functions = []; + $functions['__construct'] = $this->getConstructRedis($constructStub); + return $functions; + } + + public function getConstructRedis(string $constructStub): array|string + { + return str_replace('{{Strategy}}', $this->strategyName, $constructStub); + } + +} diff --git a/src/Creators/CreatorRepository.php b/src/Creators/CreatorRepository.php new file mode 100644 index 0000000..d81f307 --- /dev/null +++ b/src/Creators/CreatorRepository.php @@ -0,0 +1,222 @@ +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); + + $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); + } + + private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable, string $sqlRepositoryName): string + { + 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 + { + return $this->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 createAttributes(): 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; + } + + 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'); + $columnsInfo = $this->getAllColumnsInTable($this->tableName); + + $indexes = $this->extractIndexes($this->tableName); + foreach ($indexes as $index) { + $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, $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); + + foreach ($foreignKeys as $_foreignKey) { + $fun_name = ucfirst(Str::camel($_foreignKey->COLUMN_NAME)); + $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); + } + 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) + { + 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); + } + + 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 . '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 . '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 . '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 . 'temporary_cache_strategy.stub'), + }; + } +} diff --git a/src/Creators/CreatorResource.php b/src/Creators/CreatorResource.php new file mode 100644 index 0000000..3641637 --- /dev/null +++ b/src/Creators/CreatorResource.php @@ -0,0 +1,105 @@ +resourceNamespace; + } + + public function createUses(): array + { + return [ + "use $this->entityNamespace\\$this->entityName;", + 'use Eghamat24\DatabaseRepository\Models\Entity\Entity;', + 'use Eghamat24\DatabaseRepository\Models\Resources\Resource;' + ]; + } + + public function getClassName(): string + { + return $this->resourceName; + } + + public function getExtendSection(): string + { + return 'extends Resource'; + } + + public function createAttributes(): array + { + return []; + } + + public function createFunctions(): array + { + $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->writeGet($getsStub, $_column->COLUMN_NAME, Str::camel($_column->COLUMN_NAME)) . "\t\t\t"; + } + + $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 writeGet(string $getterStub, string $columnName, string $attributeName): array|string + { + $replaceMapping = [ + '{{ ColumnName }}' => $columnName, + '{{ AttributeName }}' => Str::camel($attributeName), + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $getterStub); + } + + public function writeForeignGetter(string $foreignGetterStub, string $columnName, string $attributeName): array|string + { + $replaceMapping = [ + '{{ AttributeName }}' => Str::snake($columnName), + '{{ GetterName }}' => ucfirst($columnName), + '{{ AttributeType }}' => ucfirst($attributeName) + ]; + + return str_replace(array_keys($replaceMapping), array_values($replaceMapping), $foreignGetterStub); + } +} diff --git a/src/Creators/IClassCreator.php b/src/Creators/IClassCreator.php new file mode 100644 index 0000000..2099cc8 --- /dev/null +++ b/src/Creators/IClassCreator.php @@ -0,0 +1,22 @@ + 'bool', 'boolean' => 'bool', 'bit' => 'string', @@ -18,6 +19,7 @@ trait CustomMySqlQueries 'mediumint' => 'int', 'bigint' => 'int', 'float' => 'float', + 'decimal' => 'float', 'double' => 'float', 'json' => 'string', 'char' => 'string', @@ -37,12 +39,15 @@ trait CustomMySqlQueries 'time' => 'string', 'datetime' => 'string', 'timestamp' => 'string', + 'point' => 'string', + ]; + + protected array $columnTypes = [ + 'tinyint(1)' => 'bool' ]; /** * Extract all columns from a given table. - * @param string $tableName - * @return Collection */ public function getAllColumnsInTable(string $tableName): Collection { @@ -53,10 +58,20 @@ public function getAllColumnsInTable(string $tableName): Collection ->get(); } + /** + * Extract all table names. + */ + 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 - * @return Collection */ public function extractForeignKeys(string $tableName): Collection { @@ -68,10 +83,43 @@ 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; } + + /** + * 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(); + + $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)) { + return $this->columnTypes[$columnType]; + } + + return $this->dataTypes[$dataType]; + } } diff --git a/src/DatabaseRepositoryServiceProvider.php b/src/DatabaseRepositoryServiceProvider.php index 7c9eeee..22f4700 100644 --- a/src/DatabaseRepositoryServiceProvider.php +++ b/src/DatabaseRepositoryServiceProvider.php @@ -1,15 +1,17 @@ baseModelStubPath = __DIR__ . '/../stubs/Models/PHP' .env('REPOSITORY_PHP_VERSION', '8.0'); } /** @@ -46,77 +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 +63,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,12 +94,15 @@ private function registerCommands(): void $this->commands([ MakeAll::class, MakeEntity::class, + MakeEnum::class, MakeFactory::class, MakeInterfaceRepository::class, MakeMySqlRepository::class, MakeRedisRepository::class, MakeRepository::class, - MakeResource::class + MakeResource::class, + + ]); } } diff --git a/stubs/Models/PHP8.0/Entity/Entity.stub b/src/Models/Entity/Entity.php similarity index 77% rename from stubs/Models/PHP8.0/Entity/Entity.stub rename to src/Models/Entity/Entity.php index 08af3bf..05c31ad 100644 --- a/stubs/Models/PHP8.0/Entity/Entity.stub +++ b/src/Models/Entity/Entity.php @@ -1,8 +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); @@ -43,7 +23,6 @@ public function __isset($name) /** * Make all variables of the object as null - * @return $this */ public function clearVariables(): self { @@ -54,9 +33,6 @@ public function clearVariables(): self return $this; } - /** - * @return int - */ public function getPrimaryKey(): int { return $this->getId(); @@ -90,16 +66,23 @@ public function storeOriginals() $this->originals = $this->toArray(); } + /** + * empty an array of attributes original value + */ + public function emptyOriginals() + { + $this->originals = []; + } + /** * get an Array of Changed Attributes - * @return array */ 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; } } @@ -108,7 +91,6 @@ public function changedAttributesName(): array /** * get an Array of Changed Attributes with new values - * @return array */ public function getDirty(): array { @@ -124,7 +106,6 @@ public function getDirty(): array /** * get an Array of Changed Attributes with original values - * @return array */ public function getChanges(): array { @@ -139,7 +120,6 @@ public function getChanges(): array /** * is any attribute changed? - * @return bool */ public function isDirty(): bool { @@ -150,4 +130,4 @@ public function jsonSerialize() { return $this->toArray(); } -} \ No newline at end of file +} 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, + }; + } +} diff --git a/stubs/Models/PHP8.0/Enums/Enum.stub b/src/Models/Enums/Enum.php similarity index 85% rename from stubs/Models/PHP8.0/Enums/Enum.stub rename to src/Models/Enums/Enum.php index 291fe58..000c6fc 100644 --- a/stubs/Models/PHP8.0/Enums/Enum.stub +++ b/src/Models/Enums/Enum.php @@ -1,6 +1,6 @@ getConstants(); } - public function getValue(int|string $key): ?string + public function getValue(int|string $key): null|string { $list = $this->getList(); $keys = array_keys($list); @@ -33,4 +33,4 @@ public function indexOf(int|string $value): false|int|string return array_search($value, $values, true); } -} \ No newline at end of file +} diff --git a/stubs/Models/PHP8.0/Enums/GriewFilterOperator.stub b/src/Models/Enums/GriewFilterOperator.php similarity index 95% rename from stubs/Models/PHP8.0/Enums/GriewFilterOperator.stub rename to src/Models/Enums/GriewFilterOperator.php index a9c5439..a973d89 100644 --- a/stubs/Models/PHP8.0/Enums/GriewFilterOperator.stub +++ b/src/Models/Enums/GriewFilterOperator.php @@ -1,6 +1,6 @@ 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); + } +} diff --git a/stubs/Models/PHP7.4/Repository/MySqlRepository.stub b/src/Models/Repositories/MySqlRepository.php similarity index 85% rename from stubs/Models/PHP7.4/Repository/MySqlRepository.stub rename to src/Models/Repositories/MySqlRepository.php index 78a62b8..366b2df 100644 --- a/stubs/Models/PHP7.4/Repository/MySqlRepository.stub +++ b/src/Models/Repositories/MySqlRepository.php @@ -1,18 +1,18 @@ 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,16 +141,7 @@ 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, ?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); @@ -207,7 +182,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; diff --git a/src/Models/Repositories/RedisRepository.php b/src/Models/Repositories/RedisRepository.php new file mode 100644 index 0000000..6e16c97 --- /dev/null +++ b/src/Models/Repositories/RedisRepository.php @@ -0,0 +1,128 @@ +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/Models/PHP8.0/Resource/IResource.stub b/src/Models/Resources/IResource.php similarity index 62% rename from stubs/Models/PHP8.0/Resource/IResource.stub rename to src/Models/Resources/IResource.php index a44a374..22a39d8 100644 --- a/stubs/Models/PHP8.0/Resource/IResource.stub +++ b/src/Models/Resources/IResource.php @@ -1,9 +1,9 @@ {{ AttributeName }} = $entity->{{ DatabaseAttributeName }}; diff --git a/stubs/Models/PHP7.0/Entity/Entity.stub b/stubs/Models/PHP7.0/Entity/Entity.stub deleted file mode 100644 index 86999b0..0000000 --- a/stubs/Models/PHP7.0/Entity/Entity.stub +++ /dev/null @@ -1,158 +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(): 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/Repository/RedisRepository.stub b/stubs/Models/PHP8.0/Repository/RedisRepository.stub deleted file mode 100644 index 7fa67b1..0000000 --- a/stubs/Models/PHP8.0/Repository/RedisRepository.stub +++ /dev/null @@ -1,20 +0,0 @@ -cache = app('cache'); - } - - protected function getCache(): CacheManager - { - return $this->cache; - } -} \ No newline at end of file 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 @@ -set{{ SetterName }}($entity->{{ AttributeName }}); diff --git a/stubs/PHP7.0/repository.mysql.getAllBy.stub b/stubs/PHP7.0/repository.mysql.getAllBy.stub deleted file mode 100644 index 710504d..0000000 --- a/stubs/PHP7.0/repository.mysql.getAllBy.stub +++ /dev/null @@ -1,13 +0,0 @@ - - /** - * @param array ${{ AttributeNamePlural }} - * @return Collection - */ - public function getAllBy{{ FunctionNamePlural }}(${{ AttributeNamePlural }}) - { - ${{ EntityVariableName }} = $this->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.accessors.stub b/stubs/PHP7.4/repository.entity.accessors.stub deleted file mode 100644 index 91814b6..0000000 --- a/stubs/PHP7.4/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/PHP7.4/repository.entity.attribute.stub b/stubs/PHP7.4/repository.entity.attribute.stub deleted file mode 100644 index 6df2dec..0000000 --- a/stubs/PHP7.4/repository.entity.attribute.stub +++ /dev/null @@ -1 +0,0 @@ - protected {{ AttributeType }} ${{ AttributeName }}; 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.interface.getOneBy.stub b/stubs/PHP7.4/repository.interface.getOneBy.stub deleted file mode 100644 index b0ffcfa..0000000 --- a/stubs/PHP7.4/repository.interface.getOneBy.stub +++ /dev/null @@ -1,2 +0,0 @@ - - public function getOneBy{{ FunctionName }}(int ${{ AttributeName }}): ?{{ EntityName }}; 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.getAllBy.stub b/stubs/PHP7.4/repository.mysql.getAllBy.stub deleted file mode 100644 index c63e3da..0000000 --- a/stubs/PHP7.4/repository.mysql.getAllBy.stub +++ /dev/null @@ -1,13 +0,0 @@ - - /** - * @param array ${{ AttributeNamePlural }} - * @return Collection - */ - public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection - { - ${{ EntityVariableName }} = $this->newQuery() - ->whereIn('{{ ColumnName }}', ${{ AttributeNamePlural }}) - ->get(); - - return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); - } 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.timeField.stub b/stubs/PHP7.4/repository.mysql.timeField.stub deleted file mode 100644 index 1f24763..0000000 --- a/stubs/PHP7.4/repository.mysql.timeField.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ ColumnName }}' => date('Y-m-d H:i:s'), 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/PHP7.4/repository.resource.class.stub b/stubs/PHP7.4/repository.resource.class.stub deleted file mode 100644 index 02ebe56..0000000 --- a/stubs/PHP7.4/repository.resource.class.stub +++ /dev/null @@ -1,31 +0,0 @@ -toArray(${{ EntityVariableName }}) + [ -{{ ForeignGetterFunctions }} - ]; - } -} \ No newline at end of file diff --git a/stubs/PHP7.4/repository.resource.getter.default.stub b/stubs/PHP7.4/repository.resource.getter.default.stub deleted file mode 100644 index 7c12036..0000000 --- a/stubs/PHP7.4/repository.resource.getter.default.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), diff --git a/stubs/PHP7.4/repository.resource.getter.foreign.stub b/stubs/PHP7.4/repository.resource.getter.foreign.stub deleted file mode 100644 index 42c3769..0000000 --- a/stubs/PHP7.4/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/PHP8.0/repository.base.attribute.sql.stub deleted file mode 100644 index 99fe387..0000000 --- a/stubs/PHP8.0/repository.base.attribute.sql.stub +++ /dev/null @@ -1 +0,0 @@ - private {{ SqlRepositoryName }} ${{ SqlRepositoryVariable }}; diff --git a/stubs/PHP8.0/repository.base.class.stub b/stubs/PHP8.0/repository.base.class.stub deleted file mode 100644 index 31fd83a..0000000 --- a/stubs/PHP8.0/repository.base.class.stub +++ /dev/null @@ -1,16 +0,0 @@ -{{ SqlRepositoryVariable }}->{{ FunctionName }}(${{ AttributeName }}); - } diff --git a/stubs/PHP8.0/repository.base.setter.sql.stub b/stubs/PHP8.0/repository.base.setter.sql.stub deleted file mode 100644 index 97331ca..0000000 --- a/stubs/PHP8.0/repository.base.setter.sql.stub +++ /dev/null @@ -1 +0,0 @@ - $this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); \ No newline at end of file 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.entity.class.stub b/stubs/PHP8.0/repository.entity.class.stub deleted file mode 100644 index f01693a..0000000 --- a/stubs/PHP8.0/repository.entity.class.stub +++ /dev/null @@ -1,8 +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 @@ -table = '{{ TableName }}'; - $this->primaryKey = 'id'; - $this->softDelete = {{ HasSoftDelete }}; - $this->factory = new {{ FactoryName }}(); - - parent::__construct(); - } -{{ Functions }} -} \ No newline at end of file diff --git a/stubs/PHP8.0/repository.mysql.create.stub b/stubs/PHP8.0/repository.mysql.create.stub deleted file mode 100644 index e9ffbc4..0000000 --- a/stubs/PHP8.0/repository.mysql.create.stub +++ /dev/null @@ -1,18 +0,0 @@ - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return {{ EntityName }} - */ - public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} - { -{{ SetterFunctions }} - - $id = $this->newQuery() - ->insertGetId([ -{{ GetterFunctions }} - ]); - - ${{ EntityVariableName }}->setId($id); - - return ${{ EntityVariableName }}; - } diff --git a/stubs/PHP8.0/repository.mysql.deleteAndUndelete.stub b/stubs/PHP8.0/repository.mysql.deleteAndUndelete.stub deleted file mode 100644 index bdfdff8..0000000 --- a/stubs/PHP8.0/repository.mysql.deleteAndUndelete.stub +++ /dev/null @@ -1,26 +0,0 @@ - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ - public function remove({{ 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 restore({{ EntityName }} ${{ EntityVariableName }}): int - { - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ - 'deleted_at' => null, - ]); - } diff --git a/stubs/PHP8.0/repository.mysql.getAllBy.stub b/stubs/PHP8.0/repository.mysql.getAllBy.stub deleted file mode 100644 index c63e3da..0000000 --- a/stubs/PHP8.0/repository.mysql.getAllBy.stub +++ /dev/null @@ -1,13 +0,0 @@ - - /** - * @param array ${{ AttributeNamePlural }} - * @return Collection - */ - public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection - { - ${{ EntityVariableName }} = $this->newQuery() - ->whereIn('{{ ColumnName }}', ${{ AttributeNamePlural }}) - ->get(); - - return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); - } diff --git a/stubs/PHP8.0/repository.mysql.getOneBy.stub b/stubs/PHP8.0/repository.mysql.getOneBy.stub deleted file mode 100644 index 1091972..0000000 --- a/stubs/PHP8.0/repository.mysql.getOneBy.stub +++ /dev/null @@ -1,13 +0,0 @@ - - /** - * @param int ${{ 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/PHP8.0/repository.mysql.getter.stub b/stubs/PHP8.0/repository.mysql.getter.stub deleted file mode 100644 index 3886dce..0000000 --- a/stubs/PHP8.0/repository.mysql.getter.stub +++ /dev/null @@ -1 +0,0 @@ - '{{ ColumnName }}' => ${{ EntityVariableName }}->get{{ GetterName }}(), diff --git a/stubs/PHP8.0/repository.mysql.setter.stub b/stubs/PHP8.0/repository.mysql.setter.stub deleted file mode 100644 index 5bdf5ba..0000000 --- a/stubs/PHP8.0/repository.mysql.setter.stub +++ /dev/null @@ -1 +0,0 @@ - ${{ EntityVariableName }}->set{{ SetterName }}(date('Y-m-d H:i:s')); 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.mysql.update.stub b/stubs/PHP8.0/repository.mysql.update.stub deleted file mode 100644 index 1a694fe..0000000 --- a/stubs/PHP8.0/repository.mysql.update.stub +++ /dev/null @@ -1,15 +0,0 @@ - - /** - * @param {{ EntityName }} ${{ EntityVariableName }} - * @return int - */ - public function update({{ EntityName }} ${{ EntityVariableName }}): int - { -{{ UpdateFieldSetter }} - - return $this->newQuery() - ->where($this->primaryKey, ${{ EntityVariableName }}->getPrimaryKey()) - ->update([ -{{ GetterFunctions }} - ]); - } 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/Repositories/Base/base.attribute.sql.stub b/stubs/Repositories/Base/base.attribute.sql.stub new file mode 100644 index 0000000..2ef4512 --- /dev/null +++ b/stubs/Repositories/Base/base.attribute.sql.stub @@ -0,0 +1,2 @@ +private {{ SqlRepositoryName }} ${{ SqlRepositoryVariable }}; +private {{ RedisRepositoryVariable }} ${{ RedisRepositoryName }}; diff --git a/stubs/Repositories/Base/base.construct.stub b/stubs/Repositories/Base/base.construct.stub new file mode 100644 index 0000000..414e264 --- /dev/null +++ b/stubs/Repositories/Base/base.construct.stub @@ -0,0 +1,4 @@ + public function __construct() + { + {{ Setters }} + } diff --git a/stubs/Repositories/Base/base.construct_redis.stub b/stubs/Repositories/Base/base.construct_redis.stub new file mode 100644 index 0000000..23d3b45 --- /dev/null +++ b/stubs/Repositories/Base/base.construct_redis.stub @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000..f0002e5 --- /dev/null +++ b/stubs/Repositories/Base/base.function.stub @@ -0,0 +1,5 @@ + public function {{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): {{ FunctionReturnType }} + { + {{redisFunction}} + {{returnResult}} + } diff --git a/stubs/Repositories/Base/base.setter.sql.stub b/stubs/Repositories/Base/base.setter.sql.stub new file mode 100644 index 0000000..94901a9 --- /dev/null +++ b/stubs/Repositories/Base/base.setter.sql.stub @@ -0,0 +1,2 @@ +$this->{{ SqlRepositoryVariable }} = new {{ SqlRepositoryName }}(); + $this->{{ RedisRepositoryVariable }} = new {{ RedisRepositoryName }}(); diff --git a/stubs/PHP7.4/repository.interface.class.stub b/stubs/Repositories/Interface/interface.class.stub similarity index 98% rename from stubs/PHP7.4/repository.interface.class.stub rename to stubs/Repositories/Interface/interface.class.stub index cb9a94d..9ca3e56 100644 --- a/stubs/PHP7.4/repository.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 +{ +} \ No newline at end of file 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/Repositories/Interface/interface.deleteAndUndelete.stub b/stubs/Repositories/Interface/interface.deleteAndUndelete.stub new file mode 100644 index 0000000..314223d --- /dev/null +++ b/stubs/Repositories/Interface/interface.deleteAndUndelete.stub @@ -0,0 +1,4 @@ + + public function remove({{ EntityName }} ${{ EntityVariableName }}): int; + + public function restore({{ EntityName }} ${{ EntityVariableName }}): int; 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/Repositories/Interface/interface.getOneBy.stub b/stubs/Repositories/Interface/interface.getOneBy.stub new file mode 100644 index 0000000..a3ff008 --- /dev/null +++ b/stubs/Repositories/Interface/interface.getOneBy.stub @@ -0,0 +1,2 @@ + + public function getOneBy{{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): null|{{ EntityName }}; 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/PHP7.4/repository.mysql.class.stub b/stubs/Repositories/Mysql/mysql.class.stub similarity index 84% rename from stubs/PHP7.4/repository.mysql.class.stub rename to stubs/Repositories/Mysql/mysql.class.stub index 3a48556..60f3415 100644 --- a/stubs/PHP7.4/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 Eghamat24\DatabaseRepository\Models\Repositories\MySqlRepository; class {{ MySqlRepositoryName }} extends MySqlRepository implements {{ RepositoryInterfaceName }} { @@ -18,4 +18,6 @@ class {{ MySqlRepositoryName }} extends MySqlRepository implements {{ Repository parent::__construct(); } -} \ No newline at end of file + + {{ Functions }} +} diff --git a/stubs/Repositories/Mysql/mysql.construct.stub b/stubs/Repositories/Mysql/mysql.construct.stub new file mode 100644 index 0000000..406fe80 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.construct.stub @@ -0,0 +1,9 @@ +public function __construct() + { + $this->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 new file mode 100644 index 0000000..f7113c9 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.create.stub @@ -0,0 +1,13 @@ + public function create({{ EntityName }} ${{ EntityVariableName }}): {{ EntityName }} + { + {{ SetterFunctions }} + + $id = $this->newQuery() + ->insertGetId([ + {{ GetterFunctions }} + ]); + + ${{ EntityVariableName }}->id = $id; + + return ${{ EntityVariableName }}; + } diff --git a/stubs/Repositories/Mysql/mysql.delete.stub b/stubs/Repositories/Mysql/mysql.delete.stub new file mode 100644 index 0000000..5a99837 --- /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.deleteAndUndelete.stub b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub new file mode 100644 index 0000000..725ee00 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.deleteAndUndelete.stub @@ -0,0 +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 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 new file mode 100644 index 0000000..0c6d435 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.getAllBy.stub @@ -0,0 +1,8 @@ + public function getAllBy{{ FunctionNamePlural }}(array ${{ AttributeNamePlural }}): Collection + { + ${{ EntityVariableName }} = $this->newQuery() + ->whereIn('{{ ColumnName }}', ${{ AttributeNamePlural }}) + ->get(); + + return $this->factory->makeCollectionOfEntities(${{ EntityVariableName }}); + } diff --git a/stubs/Repositories/Mysql/mysql.getOneBy.stub b/stubs/Repositories/Mysql/mysql.getOneBy.stub new file mode 100644 index 0000000..f8e44e2 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.getOneBy.stub @@ -0,0 +1,8 @@ + public function getOneBy{{ FunctionName }}({{ AttributeType }} ${{ AttributeName }}): null|{{ EntityName }} + { + ${{ EntityVariableName }} = $this->newQuery() + ->where('{{ ColumnName }}', ${{ AttributeName }}) + ->first(); + + return ${{ EntityVariableName }} ? $this->factory->makeEntityFromStdClass(${{ EntityVariableName }}) : null; + } diff --git a/stubs/Repositories/Mysql/mysql.getter.stub b/stubs/Repositories/Mysql/mysql.getter.stub new file mode 100644 index 0000000..8862049 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.getter.stub @@ -0,0 +1 @@ + '{{ ColumnName }}' => ${{ EntityVariableName }}->{{ AttributeName }}, diff --git a/stubs/Repositories/Mysql/mysql.setter.stub b/stubs/Repositories/Mysql/mysql.setter.stub new file mode 100644 index 0000000..419d6c1 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.setter.stub @@ -0,0 +1 @@ + ${{ EntityVariableName }}->{{ AttributeName }} = date('Y-m-d H:i:s'); diff --git a/stubs/Repositories/Mysql/mysql.timeField.stub b/stubs/Repositories/Mysql/mysql.timeField.stub new file mode 100644 index 0000000..f5b27ac --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.timeField.stub @@ -0,0 +1 @@ + '{{ ColumnName }}' => 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..54238af --- /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/Repositories/Mysql/mysql.update.stub b/stubs/Repositories/Mysql/mysql.update.stub new file mode 100644 index 0000000..7671962 --- /dev/null +++ b/stubs/Repositories/Mysql/mysql.update.stub @@ -0,0 +1,10 @@ + public function update({{ EntityName }} ${{ EntityVariableName }}): int + { + {{ UpdateFieldSetter }} + + 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 new file mode 100644 index 0000000..e67fa83 --- /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..6eac59f --- /dev/null +++ b/stubs/Repositories/Redis/create/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,6 @@ + $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..e67fa83 --- /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..e67fa83 --- /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..05b3d7a --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => '{{ FunctionName }}', + '{{ ColumnNameSingle }}' => ${{ ColumnName }}, + ]); + + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $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 new file mode 100644 index 0000000..c6cd353 --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.query_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => '{{ FunctionName }}', + '{{ ColumnNameSingle }}' => ${{ ColumnName }}, + ]); + + $entities = $this->redisRepository->get($cacheKey); + + if ($entities === null) { + $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 new file mode 100644 index 0000000..e653fb5 --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.single_key_cache_strategy.stub @@ -0,0 +1,6 @@ +$entity = $this->redisRepository->get(); + + if ($entity === null) { + $entities = $this->repository->{{ FunctionName }}(${{ ColumnName }}); + $this->redisRepository->put($entities); + } 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..0a45aff --- /dev/null +++ b/stubs/Repositories/Redis/getAllBy/base.temporary_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => '{{ FunctionName }}', + '{{ ColumnNameSingle }}' => ${{ ColumnName }}, + ]); + + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $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 new file mode 100644 index 0000000..6f55216 --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,11 @@ + $cacheKey = $this->redisRepository->makeKey([ + 'function_name' => '{{ FunctionName }}', + '{{ ColumnName }}' => ${{ ColumnName }}, + ]); + + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $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 new file mode 100644 index 0000000..0641280 --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.query_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => '{{ FunctionName }}', + '{{ ColumnName }}' => ${{ ColumnName }}, + ]); + + $entity = $this->redisRepository->get($cacheKey); + + 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 new file mode 100644 index 0000000..a9e94d5 --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.single_key_cache_strategy.stub @@ -0,0 +1,6 @@ + $entity = $this->redisRepository->get(); + + if ($entity === null) { + $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 new file mode 100644 index 0000000..2565c67 --- /dev/null +++ b/stubs/Repositories/Redis/getOneBy/base.temporary_cache_strategy.stub @@ -0,0 +1,11 @@ +$cacheKey = $this->redisRepository->makeKey([ + 'function_name' => '{{ FunctionName }}', + '{{ ColumnName }}' => ${{ ColumnName }}, + ]); + + $data = $this->redisRepository->get($cacheKey); + + if (is_null($data)) { + $data = $this->repository->{{ FunctionName }}(${{ ColumnName }}); + $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..ead52a7 --- /dev/null +++ b/stubs/Repositories/Redis/update/base.clearable_temporary_cache_strategy.stub @@ -0,0 +1,6 @@ +$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..e67fa83 --- /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..e67fa83 --- /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 diff --git a/stubs/PHP8.0/repository.resource.class.stub b/stubs/Resources/resource.class.stub similarity index 57% rename from stubs/PHP8.0/repository.resource.class.stub rename to stubs/Resources/resource.class.stub index 02ebe56..2526ab3 100644 --- a/stubs/PHP8.0/repository.resource.class.stub +++ b/stubs/Resources/resource.class.stub @@ -2,30 +2,23 @@ namespace {{ ResourceNamespace }}; -use {{ EntityNamespace }}\Entity; use {{ EntityNamespace }}\{{ EntityName }}; +use Eghamat24\DatabaseRepository\Models\Entity\Entity; +use Eghamat24\DatabaseRepository\Models\Resources\Resource; class {{ ResourceName }} extends Resource { - /** - * @param Entity|{{ EntityName }} ${{ EntityVariableName }} - * @return array - */ public function toArray(${{ EntityVariableName }}): array { return [ -{{ GetterFunctions }} + {{ GetterFunctions }} ]; } - /** - * @param Entity|{{ EntityName }} ${{ EntityVariableName }} - * @return array - */ public function toArrayWithForeignKeys(${{ EntityVariableName }}): array { return $this->toArray(${{ EntityVariableName }}) + [ -{{ ForeignGetterFunctions }} + {{ ForeignGetterFunctions }} ]; } -} \ No newline at end of file +} diff --git a/stubs/Resources/resource.function.foreign.stub b/stubs/Resources/resource.function.foreign.stub new file mode 100644 index 0000000..4e0825d --- /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..ced9819 --- /dev/null +++ b/stubs/Resources/resource.function.getter.stub @@ -0,0 +1,6 @@ + public function toArray(${{ EntityVariableName }}): array + { + return [ + {{ Getters }} + ]; + } diff --git a/stubs/Resources/resource.getter.default.stub b/stubs/Resources/resource.getter.default.stub new file mode 100644 index 0000000..ed6b4fa --- /dev/null +++ b/stubs/Resources/resource.getter.default.stub @@ -0,0 +1 @@ +'{{ ColumnName }}' => ${{ EntityVariableName }}->{{ AttributeName }}, diff --git a/stubs/Resources/resource.getter.foreign.stub b/stubs/Resources/resource.getter.foreign.stub new file mode 100644 index 0000000..abb8705 --- /dev/null +++ b/stubs/Resources/resource.getter.foreign.stub @@ -0,0 +1 @@ + '{{ AttributeName }}' => ${{ EntityVariableName }}->get{{ GetterName }}() ? (new {{ AttributeType }}Resource())->toArray(${{ EntityVariableName }}->get{{ GetterName }}()) : null, 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 @@ + 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