Skip to content

add redis #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions src/Commands/BaseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Nanvaie\DatabaseRepository\Commands;

use Illuminate\Container\Container;
use Illuminate\Support\Collection;
use Illuminate\Console\Command;
use Nanvaie\DatabaseRepository\CustomMySqlQueries;
Expand Down Expand Up @@ -35,6 +36,8 @@ class BaseCommand extends Command
public string $relativeMysqlRepositoryPath;
public string $mysqlRepositoryStubsPath;

public string $strategyName;

public function setArguments()
{
$this->selectedDb = $this->hasArgument('selected_db') && $this->argument('selected_db') ? $this->argument('selected_db') : config('repository.default_db');
Expand Down Expand Up @@ -63,7 +66,9 @@ public function setArguments()
$this->mysqlRepositoryName = 'MySql' . $this->entityName . 'Repository';
$this->relativeMysqlRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR;
$this->mysqlRepositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.mysql');

if ($this->hasArgument('strategy')) {
$this->strategyName = $this->argument('strategy');
}
}

public function checkDelete(string $filenameWithPath, string $entityName, string $objectName): void
Expand Down Expand Up @@ -99,15 +104,13 @@ public function finalized(string $filenameWithPath, string $entityName, string $

$this->info("\"$entityName\" has been created.");
}

public function checkEmpty(Collection $columns, string $tableName): void
{
if ($columns->isEmpty()) {
$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]);
Expand All @@ -117,4 +120,24 @@ public function getChoice(): null|string
{
return \config('replacement.choice');
}

public function checkStrategyName()
{
$strategyNames = array("ClearableTemporaryCacheStrategy", "QueryCacheStrategy", "SingleKeyCacheStrategy", "TemporaryCacheStrategy");
if (!in_array($this->argument('strategy'), $strategyNames)) {
$this->alert("This pattern strategy does not exist !!! ");
exit;
}
}
public function checkDatabasesExist()
{
$entityName=Str::singular(ucfirst(Str::camel($this->argument('table_name'))));
$mysql ="App\Models\Repositories". "\\". $entityName. "\\"."MySql".$entityName."Repository.php";
$redis ="App\Models\Repositories". "\\". $entityName. "\\"."Redis".$entityName."Repository.php";
if(!file_exists($mysql) && !file_exists($redis)) {
$this->alert("First create the class databases!!!");
exit;
}
}

}
13 changes: 7 additions & 6 deletions src/Commands/MakeRedisRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MakeRedisRepository extends BaseCommand
*
* @var string
*/
protected $signature = 'repository:make-redis-repository {table_name}
protected $signature = 'repository:make-redis-repository {table_name} {strategy}
{--k|foreign-keys : Detect foreign keys}
{--d|delete : Delete resource}
{--f|force : Override/Delete existing redis repository}
Expand All @@ -35,9 +35,12 @@ class MakeRedisRepository extends BaseCommand
*
* @return int
*/
public function handle(): void
public function handle()
{

$this->checkStrategyName();
$this->setArguments();

$redisRepositoryName = "Redis$this->entityName"."Repository";
$redisRepositoryNamespace = config('repository.path.namespace.repositories');
$relativeRedisRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR;
Expand All @@ -46,19 +49,17 @@ public function handle(): void
$this->checkDelete($filenameWithPath,$redisRepositoryName,"Redis Repository");
$this->checkDirectory($relativeRedisRepositoryPath);
$this->checkClassExist($this->repositoryNamespace,$redisRepositoryName,"Redis Repository");

$columns = $this->getAllColumnsInTable($this->tableName);
$this->checkEmpty($columns,$this->tableName);

if ($this->detectForeignKeys) {
$foreignKeys = $this->extractForeignKeys($this->tableName);
}

$mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName,$redisRepositoryNamespace, $this->entityName);
$repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base');
$mysqlRepoCreator = new CreatorRedisRepository($redisRepositoryName,$redisRepositoryNamespace, $this->entityName,$this->strategyName,$repositoryStubsPath);
$creator = new BaseCreator($mysqlRepoCreator);
$baseContent = $creator->createClass($filenameWithPath,$this);

$this->finalized($filenameWithPath, $redisRepositoryName, $baseContent);

}
}
17 changes: 10 additions & 7 deletions src/Commands/MakeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MakeRepository extends BaseCommand
*
* @var string
*/
protected $signature = 'repository:make-repository {table_name} {selected_db?}
protected $signature = 'repository:make-repository {table_name} {strategy} {selected_db?}
{--k|foreign-keys : Detect foreign keys}
{--d|delete : Delete resource}
{--f|force : Override/Delete existing repository class}
Expand All @@ -37,23 +37,24 @@ class MakeRepository extends BaseCommand
*/
public function handle(): void
{
$this->checkDatabasesExist();
$this->checkStrategyName();

$this->setArguments();
// dd($this->selectedDb);
$repositoryName = $this->entityName.'Repository';
// $sqlRepositoryName = 'MySql'.$this->entityName.'Repository';
$sqlRepositoryName = ucwords($this->selectedDb).$this->entityName.'Repository';
$sqlRepositoryVariable = 'repository';
$redisRepositoryVariable ='redisRepository';
$redisRepositoryName = 'Redis'.$this->entityName.'Repository';
$relativeRepositoryPath = config('repository.path.relative.repositories') . "$this->entityName" . DIRECTORY_SEPARATOR;
$repositoryStubsPath = __DIR__ . '/../../' . config('repository.path.stub.repositories.base');
$filenameWithPath = $relativeRepositoryPath . $repositoryName . '.php';

$this->checkDelete($filenameWithPath,$repositoryName,"Repository");
$this->checkDirectory($relativeRepositoryPath);
$this->checkClassExist($this->repositoryNamespace,$repositoryName,"Repository");

$columns = $this->getAllColumnsInTable($this->tableName);
$this->checkEmpty($columns,$this->tableName);

$RepoCreator = new CreatorRepository(
$columns,
$sqlRepositoryVariable,
Expand All @@ -67,11 +68,13 @@ public function handle(): void
$repositoryName,
$this->interfaceName,
$this->repositoryNamespace,
$this->selectedDb
$this->selectedDb,
$redisRepositoryVariable,
$redisRepositoryName,
$this->strategyName
);
$creator = new BaseCreator($RepoCreator);
$baseContent = $creator->createClass($filenameWithPath,$this);

$this->finalized($filenameWithPath, $repositoryName, $baseContent);
}
}
1 change: 1 addition & 0 deletions src/Commands/MakeResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,5 @@ public function handle(): void
$this->finalized($filenameWithPath,$resourceName,$baseContent);

}

}
24 changes: 20 additions & 4 deletions src/Creators/CreatorRedisRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@

namespace Nanvaie\DatabaseRepository\Creators;

use Illuminate\Support\Str;
use Nanvaie\DatabaseRepository\CustomMySqlQueries;

class CreatorRedisRepository implements IClassCreator
{
public function __construct(
public string $redisRepositoryName,
public string $redisRepositoryNamespace,
public string $entityName
public string $entityName,
public string $strategyName,
public string $repositoryStubsPath,
)
{

Expand All @@ -18,22 +23,33 @@ public function getNameSpace(): string
}
public function createUses(): array
{
return ["use Nanvaie\DatabaseRepository\Models\Repositories\RedisRepository;"];
return [
"use Nanvaie\DatabaseRepository\Models\Repositories\RedisRepository;",
"use App\Models\Repositories\Redis"."\\".$this->strategyName.";"
];
}
public function getClassName(): string
{
return $this->redisRepositoryName;
}
public function getExtendSection(): string
{
return "extends RedisRepository implements IUserRepository";
return "extends RedisRepository";
}
public function createAttributs(): array
{
return [];
}
public function createFunctions(): array
{
return [];
$constructStub = file_get_contents($this->repositoryStubsPath . 'construct_redis.stub');
$functions = [];
$functions['__construct'] = $this->getConstructRedis($constructStub);
return $functions ;
}
public function getConstructRedis(string $constructStub)
{
return str_replace("{{Strategy}}",$this->strategyName,$constructStub);
}

}
85 changes: 73 additions & 12 deletions src/Creators/CreatorRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
use App\Models\Repositories\User\IUserRepository;
use Illuminate\Support\Collection;
use Nanvaie\DatabaseRepository\CustomMySqlQueries;
use Nanvaie\DatabaseRepository\Commands;
use Nanvaie\DatabaseRepository\Commands\MakeRedisRepository;
use Illuminate\Support\Str;


class CreatorRepository implements IClassCreator
{
public function __construct(
Expand All @@ -22,7 +25,10 @@ public function __construct(
public string $repositoryName,
public string $interfaceName,
public string $repositoryNamespace,
public string $selectedDb
public string $selectedDb,
public string $redisRepositoryVariable,
public string $redisRepositoryName,
public string $strategyName
)
{
}
Expand All @@ -35,27 +41,41 @@ private function writeFunction(string $functionStub, string $functionName, strin
$functionReturnType = 'null|{{ EntityName }}';
$functionName .= ucfirst(Str::camel($columnName));
$columnName = Str::camel($columnName);
$redisCashFunction = $this->getRedisCashFunctionGetOneBy($this->strategyName);


} elseif ($functionName === 'getAllBy') {
$functionReturnType = 'Collection';
$functionName .= ucfirst(Str::plural(Str::camel($columnName)));
$columnName = Str::plural(Str::camel($columnName));
$redisCashFunction = $this->getRedisCashFunctionGetAllBy($this->strategyName);


} elseif ($functionName === 'create') {
$functionReturnType = $attributeType;
$redisCashFunction = $this->getRedisCashFunctionCreate($this->strategyName);

} elseif (in_array($functionName, ['update', 'remove', 'restore'])) {
$functionReturnType = 'int';
}
$redisCashFunction = $this->getRedisCashFunctionUpdate($this->strategyName);

return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}'],
[$functionName, $attributeType, Str::camel($columnName), $functionReturnType],
}
return str_replace(['{{ FunctionName }}', '{{ AttributeType }}', '{{ AttributeName }}', '{{ FunctionReturnType }}','{{redisFunction}}'],
[$functionName, $attributeType, Str::camel($columnName), $functionReturnType,$redisCashFunction],
$functionStub);
}

private function writeSqlAttribute(string $attributeStub, string $sqlRepositoryVariable, string $sqlRepositoryName): string
{
return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'],
return str_replace(['{{ SqlRepositoryVariable }}', '{{ SqlRepositoryName }}'],
[$sqlRepositoryVariable, $sqlRepositoryName],
$attributeStub);
}
public function writeRedisAttribute(string $attributeStub,string $redisRepositoryVariable,string $redisRepositoryName):string
{
return str_replace(['{{ RedisRepositoryVariable }}', '{{ RedisRepositoryName }}'],
[$redisRepositoryVariable, $redisRepositoryName],
$attributeStub);
}

public function getNameSpace(): string
{
Expand Down Expand Up @@ -85,6 +105,7 @@ public function createAttributs(): array
$attributeSqlStub = file_get_contents($this->repositoryStubsPath . 'attribute.sql.stub');
$attributes = [];
$attributes['repository'] = 'private '.$this->interfaceName.' $repository;';
$attributes['redisRepository'] = 'private '.$this->redisRepositoryName.' $redisRepository;';
return $attributes;
}

Expand All @@ -93,9 +114,9 @@ public function createFunctions(): array
$constructStub = file_get_contents($this->repositoryStubsPath . 'construct.stub');
$functionStub = file_get_contents($this->repositoryStubsPath . 'function.stub');
$setterSqlStub = file_get_contents($this->repositoryStubsPath . 'setter.sql.stub');

$functions = [];
$functions['__construct'] = $this->getConstruct($setterSqlStub, $constructStub);
$functions['__construct'] = $this->getConstructRedis($setterSqlStub, $constructStub);
$functions['getOneById'] = $this->writeFunction($functionStub, 'getOneBy', 'id', 'int');
$functions['getAllByIds'] = $this->writeFunction($functionStub, 'getAllBy', 'id', 'array');
$indexes = $this->extractIndexes($this->tableName);
Expand All @@ -105,7 +126,6 @@ public function createFunctions(): array
$fun_name = ucfirst(Str::camel($index->COLUMN_NAME));
$functions['getOneBy' . $fun_name] = $this->writeFunction($functionStub, 'getOneBy', $index->COLUMN_NAME, 'int');
}

if ($this->detectForeignKeys) {
$foreignKeys = $this->extractForeignKeys($this->tableName);

Expand All @@ -116,14 +136,12 @@ public function createFunctions(): array
$functions['getAllBy' . $fun_name] = $this->writeFunction($functionStub, 'getAllBy', $_foreignKey->COLUMN_NAME, 'array');
}
}

$functions['create'] = $this->writeFunction($functionStub, 'create', $this->entityVariableName, $this->entityName);
$functions['update'] = $this->writeFunction($functionStub, 'update', $this->entityVariableName, $this->entityName);
if (in_array('deleted_at', $this->columns->pluck('COLUMN_NAME')->toArray(), true)) {
$functions['remove'] = $this->writeFunction($functionStub, 'remove', $this->entityVariableName, $this->entityName);
$functions['restore'] = $this->writeFunction($functionStub, 'restore', $this->entityVariableName, $this->entityName);
}

foreach ($functions as &$func) {
$func = str_replace(["{{ SqlRepositoryVariable }}", '{{ SqlRepositoryName }}', '{{ EntityName }}'],
[$this->sqlRepositoryVariable, $this->sqlRepositoryName, $this->entityName],
Expand All @@ -132,9 +150,52 @@ public function createFunctions(): array
}
return $functions;
}

public function getConstruct(string $setterSqlStub, string $constructStub)
{
return str_replace("{{ Setters }}", $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName), $constructStub);
return str_replace("{{ Setters }}", $this->writeSqlAttribute($setterSqlStub, $this->sqlRepositoryVariable, $this->sqlRepositoryName,$this->redisRepositoryVariable,$this->redisRepositoryName), $constructStub);
}
public function getConstructRedis(string $setterSqlStub, string $constructStub)
{
return str_replace("{{ Setters }}", $this->writeRedisAttribute($setterSqlStub,$this->redisRepositoryVariable,$this->redisRepositoryName), $constructStub);
}
private function getRedisCashFunctionGetOneBy($strategyName)
{
$repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/getOneBy/base.';
return match ($strategyName) {
'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'),
'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'),
'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'),
'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'),
};
}
private function getRedisCashFunctionGetAllBy($strategyName)
{
$repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/getAllBy/base.';
return match ($strategyName) {
'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'),
'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'),
'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'),
'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'),
};
}
private function getRedisCashFunctionCreate($strategyName)
{
$repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/create/base.';
return match ($strategyName) {
'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'),
'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'),
'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'),
'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'),
};
}
private function getRedisCashFunctionUpdate($strategyName)
{
$repositoryRedisStubsPath=__DIR__ . '/../../'.'stubs/Repositories/Redis/update/base.';
return match ($strategyName) {
'QueryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'query_cache_strategy.stub'),
'SingleKeyCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'single_key_cache_strategy.stub'),
'ClearableTemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'clearable_temporary_cache_strategy.stub'),
'TemporaryCacheStrategy' => file_get_contents($repositoryRedisStubsPath . 'base.temporary_cache_strategy.stub'),
};
}
}
Loading