From 9380bb309c1e0a868bc8c2930b178abdab16a1d0 Mon Sep 17 00:00:00 2001 From: Alf Drollinger Date: Wed, 24 Apr 2024 13:29:32 +0200 Subject: [PATCH] Remove Redis Model (see branch) --- .github/workflows/monorepo-split-packages.yml | 1 - composer.json | 1 - packages/page/src/Models/Page.php | 4 - packages/redis-model/.github/FUNDING.yml | 13 - packages/redis-model/.gitignore | 49 - packages/redis-model/CHANGELOG.md | 1 - packages/redis-model/FUNDING.yml | 13 - packages/redis-model/LICENSE.md | 21 - packages/redis-model/README.md | 53 - packages/redis-model/SECURITY.md | 13 - packages/redis-model/composer.json | 36 - packages/redis-model/config/redis-model.php | 28 - .../create_redis_models_table.php.stub | 32 - .../resources/lang/de/translations.php | 16 - .../resources/lang/en/translations.php | 16 - .../resources/lang/es/translations.php | 16 - .../resources/lang/hr/translations.php | 16 - .../resources/lang/nb_NO/translations.php | 16 - .../resources/lang/ru/translations.php | 16 - packages/redis-model/src/Builder.php | 350 ----- packages/redis-model/src/Collection.php | 331 ----- .../src/Commands/InstallCommand.php | 163 --- .../ErrorConnectToRedisException.php | 10 - .../Exceptions/ErrorTransactionException.php | 10 - .../src/Exceptions/KeyExistException.php | 9 - .../Exceptions/MassAssignmentException.php | 10 - .../Exceptions/MissingAttributeException.php | 9 - .../src/Exceptions/RedisModelException.php | 9 - packages/redis-model/src/Model.php | 1215 ----------------- .../redis-model/src/Models/RedisModel.php | 23 - packages/redis-model/src/RedisModelPlugin.php | 35 - .../src/RedisModelServiceProvider.php | 23 - packages/redis-model/src/RedisRepository.php | 340 ----- .../src/Resources/RedisModelResource.php | 121 -- .../RedisModelResource/Pages/ListPage.php | 41 - .../Widgets/RedisModelWidgets.php | 30 - packages/redis-model/src/UsesRedis.php | 84 -- 37 files changed, 3174 deletions(-) delete mode 100644 packages/redis-model/.github/FUNDING.yml delete mode 100644 packages/redis-model/.gitignore delete mode 100644 packages/redis-model/CHANGELOG.md delete mode 100644 packages/redis-model/FUNDING.yml delete mode 100644 packages/redis-model/LICENSE.md delete mode 100644 packages/redis-model/README.md delete mode 100644 packages/redis-model/SECURITY.md delete mode 100644 packages/redis-model/composer.json delete mode 100644 packages/redis-model/config/redis-model.php delete mode 100644 packages/redis-model/database/migrations/create_redis_models_table.php.stub delete mode 100644 packages/redis-model/resources/lang/de/translations.php delete mode 100644 packages/redis-model/resources/lang/en/translations.php delete mode 100644 packages/redis-model/resources/lang/es/translations.php delete mode 100644 packages/redis-model/resources/lang/hr/translations.php delete mode 100644 packages/redis-model/resources/lang/nb_NO/translations.php delete mode 100644 packages/redis-model/resources/lang/ru/translations.php delete mode 100644 packages/redis-model/src/Builder.php delete mode 100644 packages/redis-model/src/Collection.php delete mode 100644 packages/redis-model/src/Commands/InstallCommand.php delete mode 100644 packages/redis-model/src/Exceptions/ErrorConnectToRedisException.php delete mode 100644 packages/redis-model/src/Exceptions/ErrorTransactionException.php delete mode 100644 packages/redis-model/src/Exceptions/KeyExistException.php delete mode 100644 packages/redis-model/src/Exceptions/MassAssignmentException.php delete mode 100644 packages/redis-model/src/Exceptions/MissingAttributeException.php delete mode 100644 packages/redis-model/src/Exceptions/RedisModelException.php delete mode 100644 packages/redis-model/src/Model.php delete mode 100644 packages/redis-model/src/Models/RedisModel.php delete mode 100644 packages/redis-model/src/RedisModelPlugin.php delete mode 100644 packages/redis-model/src/RedisModelServiceProvider.php delete mode 100644 packages/redis-model/src/RedisRepository.php delete mode 100644 packages/redis-model/src/Resources/RedisModelResource.php delete mode 100644 packages/redis-model/src/Resources/RedisModelResource/Pages/ListPage.php delete mode 100644 packages/redis-model/src/Resources/RedisModelResource/Widgets/RedisModelWidgets.php delete mode 100644 packages/redis-model/src/UsesRedis.php diff --git a/.github/workflows/monorepo-split-packages.yml b/.github/workflows/monorepo-split-packages.yml index 6f83b6cab..e9e18831e 100644 --- a/.github/workflows/monorepo-split-packages.yml +++ b/.github/workflows/monorepo-split-packages.yml @@ -22,7 +22,6 @@ jobs: - user - sync - audit - - redis-model steps: - uses: actions/checkout@v4 diff --git a/composer.json b/composer.json index c61f1a132..761ef5dce 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,6 @@ "moox/user": "*", "moox/audit": "*", "moox/sync": "*", - "moox/redis-model": "*", "wikimedia/composer-merge-plugin": "^2.1" }, "require-dev": { diff --git a/packages/page/src/Models/Page.php b/packages/page/src/Models/Page.php index 8e9057489..68bf907d2 100644 --- a/packages/page/src/Models/Page.php +++ b/packages/page/src/Models/Page.php @@ -6,10 +6,6 @@ class Page extends Model { - use \Moox\RedisModel\UsesRedis; - - public $useRedis = true; - protected $table = 'page'; protected $fillable = [ diff --git a/packages/redis-model/.github/FUNDING.yml b/packages/redis-model/.github/FUNDING.yml deleted file mode 100644 index 0446fa42d..000000000 --- a/packages/redis-model/.github/FUNDING.yml +++ /dev/null @@ -1,13 +0,0 @@ -# These are supported funding model platforms - -github: [mooxphp] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/packages/redis-model/.gitignore b/packages/redis-model/.gitignore deleted file mode 100644 index 6a81cbb00..000000000 --- a/packages/redis-model/.gitignore +++ /dev/null @@ -1,49 +0,0 @@ -# Environment -.env -.env.backup - -# Composer -/vendor -composer.lock -auth.json - -# NPM / Node -/node_modules -npm-debug.log -package-lock.json - -# Laravel -/public/hot -/public/storage -/storage/*.key - -# PHPUnit -.phpunit.result.cache -phpunit.xml - -# Yarn -yarn-error.log - -# PHPStan -/build -phpstan.neon - -# Testbench -testbench.yaml - -# PHP CS Fixer -.php-cs-fixer.cache - -# Homestead -Homestead.json -Homestead.yaml - -# IDEs -/.idea -/.vscode - -# MacOS -.DS_Store - -# Windows -Thumbs.db diff --git a/packages/redis-model/CHANGELOG.md b/packages/redis-model/CHANGELOG.md deleted file mode 100644 index 825c32f0d..000000000 --- a/packages/redis-model/CHANGELOG.md +++ /dev/null @@ -1 +0,0 @@ -# Changelog diff --git a/packages/redis-model/FUNDING.yml b/packages/redis-model/FUNDING.yml deleted file mode 100644 index 0446fa42d..000000000 --- a/packages/redis-model/FUNDING.yml +++ /dev/null @@ -1,13 +0,0 @@ -# These are supported funding model platforms - -github: [mooxphp] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/packages/redis-model/LICENSE.md b/packages/redis-model/LICENSE.md deleted file mode 100644 index 7dfc5ad0b..000000000 --- a/packages/redis-model/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Moox - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/packages/redis-model/README.md b/packages/redis-model/README.md deleted file mode 100644 index 8b0a60b97..000000000 --- a/packages/redis-model/README.md +++ /dev/null @@ -1,53 +0,0 @@ -![Moox RedisModel](https://github.com/mooxphp/moox/raw/main/art/banner/redis-model.jpg) - -# Moox RedisModel - -This is my package redis-model - -## Quick Installation - -These two commmands are all you need to install the package: - -```bash -composer require moox/redis-model -php artisan mooxredis-model:install -``` - -Curious what the install command does? See manual installation below. - -## What it does - - - -Here are some things missing, like an overview with screenshots about this package, or simply a link to the package's docs. - - - -## Manual Installation - -Instead of using the install-command `php artisan mooxredis-model:install` you are able to install this package manually step by step: - -```bash -// Publish and run the migrations: -php artisan vendor:publish --tag="redis-model-migrations" -php artisan migrate - -// Publish the config file with: -php artisan vendor:publish --tag="redis-model-config" -``` - -## Changelog - -Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. - -## Security Vulnerabilities - -Please review [our security policy](https://github.com/mooxphp/moox/security/policy) on how to report security vulnerabilities. - -## Credits - -- [All Contributors](../../contributors) - -## License - -The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/packages/redis-model/SECURITY.md b/packages/redis-model/SECURITY.md deleted file mode 100644 index d672a2c1f..000000000 --- a/packages/redis-model/SECURITY.md +++ /dev/null @@ -1,13 +0,0 @@ -# Security Policy - -## Supported Versions - -We maintain the current version of `Moox RedisModel` actively. - -Do not expect security fixes for older versions. - -## Reporting a Vulnerability - -If you find any security-related bug, please report it to security@moox.org. - -Please do not use Github issues, to give us enough time to review and fix the issue, before others can use it, to do stupid things. diff --git a/packages/redis-model/composer.json b/packages/redis-model/composer.json deleted file mode 100644 index 6cd35c6be..000000000 --- a/packages/redis-model/composer.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "moox/redis-model", - "description": "This is my package redis-model", - "keywords": [ - "Laravel", - "Filament", - "Filament plugin", - "Laravel package" - ], - "homepage": "https://moox.org/", - "license": "MIT", - "authors": [ - { - "name": "Moox Developer", - "email": "dev@moox.org", - "role": "Developer" - } - ], - "require": { - "moox/core": "*" - }, - "autoload": { - "psr-4": { - "Moox\\RedisModel\\": "src" - } - }, - "extra": { - "laravel": { - "providers": [ - "Moox\\RedisModel\\RedisModelServiceProvider" - ] - } - }, - "minimum-stability": "stable", - "prefer-stable": true -} diff --git a/packages/redis-model/config/redis-model.php b/packages/redis-model/config/redis-model.php deleted file mode 100644 index 5289c73b9..000000000 --- a/packages/redis-model/config/redis-model.php +++ /dev/null @@ -1,28 +0,0 @@ - 2001, - - 'redis_model_options' => [ - 'database_default' => 'redis_model_default', - 'prefix' => env('REDIS_MODEL_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_redis_model_'), - ], - - 'commands' => [ - 'generate_path' => app_path('RedisModels'), - 'rootNamespace' => 'App\\RedisModels', - ], - - 'database' => [ - 'redis_model_default' => [ - 'url' => env('REDIS_URL'), - 'host' => env('REDIS_HOST', '127.0.0.1'), - 'username' => env('REDIS_USERNAME'), - 'password' => env('REDIS_PASSWORD'), - 'port' => env('REDIS_PORT', '6379'), - 'database' => env('REDIS_DB', '0'), - ], - ], -]; diff --git a/packages/redis-model/database/migrations/create_redis_models_table.php.stub b/packages/redis-model/database/migrations/create_redis_models_table.php.stub deleted file mode 100644 index 11479062c..000000000 --- a/packages/redis-model/database/migrations/create_redis_models_table.php.stub +++ /dev/null @@ -1,32 +0,0 @@ -id(); - $table->string('name')->nullable(); - $table->timestamp('started_at')->nullable()->index(); - $table->timestamp('finished_at')->nullable(); - $table->boolean('failed')->default(false)->index(); - $table->timestamps(); - }); - } - - /** - * Reverse the migrations. - */ - public function down(): void - - { - Schema::dropIfExists('redis-model'); - } -}; diff --git a/packages/redis-model/resources/lang/de/translations.php b/packages/redis-model/resources/lang/de/translations.php deleted file mode 100644 index 47744a2c4..000000000 --- a/packages/redis-model/resources/lang/de/translations.php +++ /dev/null @@ -1,16 +0,0 @@ - 'RedisModel', - 'plural' => 'RedisModels', - 'breadcrumb' => 'RedisModel', - 'title' => 'RedisModel', - 'navigation_label' => 'RedisModel', - 'navigation_group' => 'Moox RedisModel', - 'totalone' => 'RedisModel Eins', - 'totaltwo' => 'RedisModel Zwei', - 'totalthree' => 'RedisModel Drei', - 'name' => 'Name', - 'started_at' => 'Gestartet am', - 'failed' => 'failed', -]; diff --git a/packages/redis-model/resources/lang/en/translations.php b/packages/redis-model/resources/lang/en/translations.php deleted file mode 100644 index 2a2f9777c..000000000 --- a/packages/redis-model/resources/lang/en/translations.php +++ /dev/null @@ -1,16 +0,0 @@ - 'RedisModel', - 'plural' => 'RedisModels', - 'breadcrumb' => 'RedisModel', - 'title' => 'RedisModel', - 'navigation_label' => 'RedisModel', - 'navigation_group' => 'Moox RedisModel', - 'totalone' => 'RedisModel One', - 'totaltwo' => 'RedisModel Two', - 'totalthree' => 'RedisModel Three', - 'name' => 'Name', - 'started_at' => 'Started at', - 'failed' => 'failed', -]; diff --git a/packages/redis-model/resources/lang/es/translations.php b/packages/redis-model/resources/lang/es/translations.php deleted file mode 100644 index e7e6673f7..000000000 --- a/packages/redis-model/resources/lang/es/translations.php +++ /dev/null @@ -1,16 +0,0 @@ - 'Desarrollador', - 'plural' => 'Desarrolladores', - 'breadcrumb' => 'Desarrollador', - 'title' => 'Desarrollador', - 'navigation_label' => 'Desarrollador', - 'navigation_group' => 'Desarrollador de Moox', - 'totalone' => 'Desarrollador uno', - 'totaltwo' => 'Desarrollador dos', - 'totalthree' => 'Desarrollador tres', - 'name' => 'Nombre', - 'started_at' => 'Empezó a las', - 'failed' => 'failed', -]; diff --git a/packages/redis-model/resources/lang/hr/translations.php b/packages/redis-model/resources/lang/hr/translations.php deleted file mode 100644 index a145e7504..000000000 --- a/packages/redis-model/resources/lang/hr/translations.php +++ /dev/null @@ -1,16 +0,0 @@ - '', - 'plural' => '', - 'breadcrumb' => '', - 'title' => '', - 'navigation_label' => '', - 'navigation_group' => '', - 'totalone' => '', - 'totaltwo' => '', - 'totalthree' => '', - 'name' => 'Ime', - 'started_at' => 'Pokrenuto', - 'failed' => 'neuspjelo', -]; diff --git a/packages/redis-model/resources/lang/nb_NO/translations.php b/packages/redis-model/resources/lang/nb_NO/translations.php deleted file mode 100644 index 415f53ff0..000000000 --- a/packages/redis-model/resources/lang/nb_NO/translations.php +++ /dev/null @@ -1,16 +0,0 @@ - 'Bygger', - 'plural' => 'Byggers', - 'breadcrumb' => 'Bygger', - 'title' => 'Bygger', - 'navigation_label' => 'Bygger', - 'navigation_group' => 'Moox RedisModel', - 'totalone' => 'Bygger én', - 'totaltwo' => 'Bygger to', - 'totalthree' => 'Bygger tre', - 'name' => 'Navn', - 'started_at' => 'Startet', - 'failed' => 'mislyktes', -]; diff --git a/packages/redis-model/resources/lang/ru/translations.php b/packages/redis-model/resources/lang/ru/translations.php deleted file mode 100644 index 38cdbd13b..000000000 --- a/packages/redis-model/resources/lang/ru/translations.php +++ /dev/null @@ -1,16 +0,0 @@ - 'Сборщик', - 'plural' => 'Сборщики', - 'breadcrumb' => 'Сборщик', - 'title' => 'Сборщик', - 'navigation_label' => 'Сборщик', - 'navigation_group' => 'Сборщик Moox', - 'totalone' => 'Первый сборщик', - 'totaltwo' => 'Второй Сборщик', - 'totalthree' => 'Третий Сборщик', - 'name' => 'Имя', - 'started_at' => 'Начато в', - 'failed' => 'Неудача', -]; diff --git a/packages/redis-model/src/Builder.php b/packages/redis-model/src/Builder.php deleted file mode 100644 index f8eb4f522..000000000 --- a/packages/redis-model/src/Builder.php +++ /dev/null @@ -1,350 +0,0 @@ -connection = $connection; - $this->repository = new RedisRepository($connection); - } - - /** - * Get the model instance being queried. - * - * @return \Moox\RedisModel\RedisRepository|static - */ - public function getRepository() - { - return $this->repository; - } - - /** - * Get the model instance being queried. - * - * @return \Moox\RedisModel\Model|static - */ - public function getModel() - { - return $this->model; - } - - /** - * Set a model instance for the model being queried. - * - * - * @return $this - */ - public function setModel(Model $model) - { - $this->model = $model; - $this->setHashPattern($model->getTable().':*'); - - return $this; - } - - /** - * Set the hash pattern to search for in Redis - * - * @param string $hashPattern The hash pattern to search for - * @return $this - */ - public function setHashPattern(string $hashPattern) - { - $this->hashPattern = $hashPattern; - - return $this; - } - - /** - *Get the hash pattern that is being searched for in Redis - - * - * @return string The hash pattern being searched for - */ - public function getHashPattern() - { - return $this->hashPattern; - } - - /** - * Set the session condition for the search - * - * @param array $condition An array of conditions to search for - * @return void - */ - public function setConditionSession(array $condition) - { - $this->conditionSession = $condition; - } - - /** - * @return array - */ - public function getConditionSession() - { - return $this->conditionSession; - } - - /** - * Add a basic where clause to the query. - * - * @param string $value - * @return $this - */ - public function where(string|array $column, string|int|null $value = null) - { - if ($value && gettype($column) == 'string') { - $this->setConditionSession(array_merge($this->getConditionSession(), [$column => $value])); - } elseif (gettype($column) == 'array') { - $this->setConditionSession(array_merge($this->getConditionSession(), $column)); - } - - $this->setHashPattern($this->compileHashByFields($this->getConditionSession())); - - return $this; - } - - /** - * Add a where clause on the primary key to the query. - * - * @param string $id - * @return $this - */ - public function whereKey($id) - { - if ($id !== null && $this->model->getKeyType() === 'string') { - $id = (string) $id; - } - - return $this->where($this->model->getQualifiedKeyName(), $id); - } - - /** - * Add a basic where clause to the query, and return the first result. - * - * - * @param string $value - * @return \Moox\RedisModel\Model|static|null - */ - public function firstWhere(string|array $column, string|int|null $value = null) - { - return $this->where(...func_get_args())->first(); - } - - /** - * Execute the query and get the first result. - * - * @return \Moox\RedisModel\Model|null - */ - public function first() - { - return $this->get()->first(); - } - - /** - * Execute the destroy data for pattern keys. - * - * @return bool - */ - public function destroy() - { - $keys = $this->getRepository()->getHashByPattern($this->getHashPattern()); - - return $this->getRepository()->destroyHash($keys); - } - - /** - * Execute the fetch properties for keys. - * - * @return \Moox\RedisModel\Collection|static[] - */ - public function get() - { - $models = []; - - foreach ($this->getRepository()->fetchHashDataByPattern($this->getHashPattern()) as $hash => $attributes) { - $models[] = $this->model->newInstance($attributes, true, $hash, true)->syncOriginal(); - } - - return $this->getModel()->newCollection($models); - } - - /** - * Counts the number of records that match the hash pattern of the model. - * - * @return int The number of records that match the hash pattern. - */ - public function count() - { - return $this->getRepository()->countByPattern($this->getHashPattern()); - } - - /** - * Create a new Collection instance with the given models. - * - * - * @return \Moox\RedisModel\Collection - */ - public function newCollection(array $models = []) - { - return new Collection($models); - } - - /** - * Create a new instance of the model being queried. - * - * @param array $attributes - * @return \Moox\RedisModel\Model - */ - public function newModelInstance($attributes = []) - { - return $this->model->newInstance($attributes); - } - - /** - * Find a model by its primary key. - * - * @param mixed $id The primary key value of the model to find. - * @return \Moox\RedisModel\Model|null The found model or null if not found. - */ - public function find($id) - { - // Retrieves the first model that matches the specified primary key. - $model = $this->whereKey($id)->first(); - - // If the model is found, sync its original state and return a clone of it. - if ($model instanceof Model) { - $model->syncOriginal(); - - return clone $model; - } - - return null; - } - - /** - * Save a new model and return the instance. - * - * @param array $attributes - The attributes to create the model with. - * @return \Moox\RedisModel\Model|$this - The newly created model instance. - */ - public function create(array $attributes = []) - { - return tap($this->newModelInstance($attributes), function ($instance) { - $instance->save(); - }); - } - - /** - * Save a new model and return the instance. Allow mass-assignment. - * - * @param array $attributes The attributes to be saved. - * @return \Moox\RedisModel\Model|$this The created model instance. - */ - public function forceCreate(array $attributes) - { - return tap($this->newModelInstance($attributes), function ($instance) { - $instance->setPrioritizeForceSave(); - $instance->save(); - }); - } - - /** - * Chunk the results of the query. - * - * @param int $count The number of models to retrieve per chunk - * @param callable|null $callback Optional callback function to be executed on each chunk - * @return \Moox\RedisModel\Collection A collection of the retrieved models, chunked - */ - public function chunk($count, ?callable $callback = null) - { - $resultData = $this->newCollection([]); - - // Scan for the models in the Redis database, and execute the provided callback function (if any) on each chunk - $this->getRepository() - ->scanByHash( - $this->getHashPattern(), - $count, - function ($keys) use ($callback, $resultData) { - $modelsChunk = []; - - // Fetch the attributes of the models in the current chunk, and create new model instances with - // these attributes - foreach ($this->getRepository()->fetchProperByListHash($keys) as $hash => $attributes) { - $modelsChunk[] = $this->model->newInstance($attributes, true, $hash, true)->syncOriginal(); - } - - $resultData->push($modelsChunk); - - // Execute the provided callback function (if any) on the current chunk of models - $callback == null ?: $callback($modelsChunk); - } - ); - - return $resultData; - } - - /** - * Checks if a hash record exists in Redis based on the given model attributes. - * - * @param array $attributes The attributes to check in the hash record. - * @return bool Returns true if a hash record exists in Redis for the given attributes, false otherwise. - */ - public function isExists(array $attributes) - { - return empty($this->getRepository()->getHashByPattern($this->compileHashByFields($attributes))) ? false : true; - } - - /** - * Compile a hash key by fields of the given attributes array. - * - * @param array $attributes The array of attributes. - * @return string The compiled hash key. - */ - public function compileHashByFields(array $attributes) - { - $listKey = array_merge([$this->model->getKeyName()], $this->model->getSubKeys()); - $stringKey = ''; - - foreach ($listKey as $key) { - $attributeValue = $attributes[$key] ?? '*'; - $stringKey .= $key.':'.($attributeValue === '*' ? '*' : $this->model->castAttributeBeforeSave($key, $attributeValue)).':'; - } - - return $this->model->getTable().':'.rtrim($stringKey, ':'); - } -} diff --git a/packages/redis-model/src/Collection.php b/packages/redis-model/src/Collection.php deleted file mode 100644 index a290547b8..000000000 --- a/packages/redis-model/src/Collection.php +++ /dev/null @@ -1,331 +0,0 @@ -|TModel|TFindDefault - */ - public function find($key, $default = null) - { - if ($key instanceof Model) { - $key = $key->getKey(); - } - - if ($key instanceof Arrayable) { - $key = $key->toArray(); - } - - if (is_array($key)) { - if ($this->isEmpty()) { - return new static; - } - - return $this->whereIn($this->first()->getKeyName(), $key); - } - - return Arr::first($this->items, fn ($model) => $model->getKey() == $key, $default); - } - - /** - * Determine if a key exists in the collection. - * - * @param (callable(TModel, TKey): bool)|TModel|string|int $key - * @param mixed $operator - * @param mixed $value - * @return bool - */ - public function contains($key, $operator = null, $value = null) - { - if (func_num_args() > 1 || $this->useAsCallable($key)) { - return parent::contains(...func_get_args()); - } - - if ($key instanceof Model) { - return parent::contains(fn ($model) => $model->is($key)); - } - - return parent::contains(fn ($model) => $model->getKey() == $key); - } - - /** - * Get the array of primary keys. - * - * @return array - */ - public function modelKeys() - { - return array_map(fn ($model) => $model->getKey(), $this->items); - } - - /** - * Run a map over each of the items. - * - * @template TMapValue - * - * @param callable(TModel, TKey): TMapValue $callback - * @return \Illuminate\Support\Collection|static - */ - public function map(callable $callback) - { - $result = parent::map($callback); - - return $result->contains(fn ($item) => ! $item instanceof Model) ? $result->toBase() : $result; - } - - /** - * Run an associative map over each of the items. - * - * The callback should return an associative array with a single key / value pair. - * - * @template TMapWithKeysKey of array-key - * @template TMapWithKeysValue - * - * @param callable(TModel, TKey): array $callback - * @return \Illuminate\Support\Collection|static - */ - public function mapWithKeys(callable $callback) - { - $result = parent::mapWithKeys($callback); - - return $result->contains(fn ($item) => ! $item instanceof Model) ? $result->toBase() : $result; - } - - /** - * Diff the collection with the given items. - * - * @param iterable $items - * @return static - */ - public function diff($items) - { - $diff = new static; - - $dictionary = $this->getDictionary($items); - - foreach ($this->items as $item) { - if (! isset($dictionary[$this->getDictionaryKey($item->getKey())])) { - $diff->add($item); - } - } - - return $diff; - } - - /** - * Return only unique items from the collection. - * - * @param (callable(TModel, TKey): mixed)|string|null $key - * @param bool $strict - * @return static - */ - public function unique($key = null, $strict = false) - { - if ($key === null) { - return parent::unique($key, $strict); - } - - return new static(array_values($this->getDictionary())); - } - - /** - * Get a dictionary key attribute - casting it to a string if necessary. - * - * @param mixed $attribute - * @return mixed - * - * @throws \Doctrine\Instantiator\Exception\InvalidArgumentException - */ - protected function getDictionaryKey($attribute) - { - if (is_object($attribute)) { - if (method_exists($attribute, '__toString')) { - return $attribute->__toString(); - } - - if ($attribute instanceof UnitEnum) { - return $attribute instanceof BackedEnum ? $attribute->value : $attribute->name; - } - - throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.'); - } - - return $attribute; - } - - /** - * Returns only the models from the collection with the specified keys. - * - * @param array|null $keys - * @return static - */ - public function only($keys) - { - if ($keys === null) { - return new static($this->items); - } - - $dictionary = Arr::only($this->getDictionary(), array_map($this->getDictionaryKey(...), (array) $keys)); - - return new static(array_values($dictionary)); - } - - /** - * Returns all models in the collection except the models with specified keys. - * - * @param array|null $keys - * @return static - */ - public function except($keys) - { - $dictionary = Arr::except($this->getDictionary(), array_map($this->getDictionaryKey(...), (array) $keys)); - - return new static(array_values($dictionary)); - } - - /** - * Append an attribute across the entire collection. - * - * @param array|string $attributes - * @return $this - */ - public function append($attributes) - { - return $this->each->append($attributes); - } - - /** - * Get a dictionary keyed by primary keys. - * - * @param iterable|null $items - * @return array - */ - public function getDictionary($items = null) - { - $items = $items === null ? $this->items : $items; - - $dictionary = []; - - foreach ($items as $value) { - $dictionary[$this->getDictionaryKey($value->getKey())] = $value; - } - - return $dictionary; - } - - /** - * The following methods are intercepted to always return base collections. - */ - - /** - * Count the number of items in the collection by a field or using a callback. - * - * @param (callable(TModel, TKey): array-key)|string|null $countBy - * @return \Illuminate\Support\Collection - */ - public function countBy($countBy = null) - { - return $this->toBase()->countBy($countBy); - } - - /** - * Collapse the collection of items into a single array. - * - * @return \Illuminate\Support\Collection - */ - public function collapse() - { - return $this->toBase()->collapse(); - } - - /** - * Get a flattened array of the items in the collection. - * - * @param int $depth - * @return \Illuminate\Support\Collection - */ - public function flatten($depth = INF) - { - return $this->toBase()->flatten($depth); - } - - /** - * Flip the items in the collection. - * - * @return \Illuminate\Support\Collection - */ - public function flip() - { - return $this->toBase()->flip(); - } - - /** - * Get the keys of the collection items. - * - * @return \Illuminate\Support\Collection - */ - public function keys() - { - return $this->toBase()->keys(); - } - - /** - * Pad collection to the specified length with a value. - * - * @template TPadValue - * - * @param int $size - * @param TPadValue $value - * @return \Illuminate\Support\Collection - */ - public function pad($size, $value) - { - return $this->toBase()->pad($size, $value); - } - - /** - * Get an array with the values of a given key. - * - * @param string|array $value - * @param string|null $key - * @return \Illuminate\Support\Collection - */ - public function pluck($value, $key = null) - { - return $this->toBase()->pluck($value, $key); - } - - /** - * Zip the collection together with one or more arrays. - * - * @template TZipValue - * - * @param \Illuminate\Contracts\Support\Arrayable|iterable ...$items - * @return \Illuminate\Support\Collection> - */ - public function zip($items) - { - return $this->toBase()->zip(...func_get_args()); - } - - /** - * Get the comparison function to detect duplicates. - * - * @param bool $strict - * @return callable(TModel, TModel): bool - */ - protected function duplicateComparator($strict) - { - return fn ($a, $b) => $a->is($b); - } -} diff --git a/packages/redis-model/src/Commands/InstallCommand.php b/packages/redis-model/src/Commands/InstallCommand.php deleted file mode 100644 index 50f1cf84c..000000000 --- a/packages/redis-model/src/Commands/InstallCommand.php +++ /dev/null @@ -1,163 +0,0 @@ -art(); - $this->welcome(); - $this->publishConfiguration(); - $this->publishMigrations(); - $this->runMigrations(); - $this->registerPlugins(); - $this->finish(); - } - - public function art(): void - { - info(' - - ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ - ▓▓▒░░▒▓▓▒▒░░░░░░▒▒▓▓▓▒░░░░░░░▒▓▓ ▓▓▓▓▒░░░░░░░▒▓▓▓▓ ▓▓▓▓▓▒░░░░░░░▒▒▓▓▓▓▓▒▒▒▒▓▓ ▓▓▓▒▒▒▒▓▓ - ▓▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▓▓▓▓▓▒░░░░░░░░░░░░░▒▓▓▓ ▓▓▓▓▒░░░░░░░░░░░░░▒▓▓▓░░░░░▒▓▓ ▓▓▒░░░░░▓▓ - ▓▒░░░░░░▒▓▓▓▓▒░░░░░░░▒▓▓▓▓░░░░░▒▓▓▓░░░░░▒▓▓▓▓▒░░░░░░░▓▓▓▓░░░░░░▒▓▓▓▓▓░░░░░░▒▓▓░░░░░▒▓▓▓▓▓░░░░░▒▓▓ - ▓▒░░░░▓▓▓▓ ▓▓░░░░░▓▓▓ ▓▓▓░░░░▒▓▓░░░░▒▓▓▓ ▓▓▓▓░░░░░▓░░░░░░▓▓▓▓ ▓▓▓▒░░░░▓▓▓▒░░░░░▓▓▓░░░░░▓▓▓ - ▓▒░░░░▒▓ ▓▓░░░░░▓▓ ▓▓░░░░▒▓░░░░▒▓▓ ▓▓▓░░▒░░░░░▓▓▓ ▓▓░░░░▒▓▓▓▓░░░░░░░░░░░▓▓ - ▓▒░░░░▒▓ ▓▓░░░░░▓▓ ▓▓░░░░▒▓░░░░▒▓ ▓▓▓░░░░░▒▓▓ ▓▓▒░░░░▓ ▓▓▓░░░░░░░░░▓▓ - ▓▒░░░░▒▓ ▓▓░░░░░▓▓ ▓▓░░░░▒▓░░░░▒▓▓ ▓▓▒░░░░░▒░░▒▓▓ ▓▓░░░░▒▓▓▓▒░░░░░▒░░░░░▒▓ - ▓▒░░░░▒▓ ▓▓░░░░░▓▓ ▓▓░░░░▒▓▓░░░░▒▓▓▓ ▓▓▓▒░░░░░▒▒░░░░░▒▓▓▓ ▓▓▓░░░░░▓▓▓░░░░░▒▓▓▓░░░░░▒▓▓ - ▓▒░░░░▒▓ ▓▓░░░░░▓▓ ▓▓░░░░▒▓▓▓░░░░░░▒▒▓▓▒░░░░░░▒▓▓▓▓░░░░░░░▒▒▓▓▒░░░░░░▓▓▓░░░░░▒▓▓▓▓▓▒░░░░░▓▓ - ▓▒░░░░▒▓ ▓▓░░░░░▓▓ ▓▓░░░░▒▓▓▓▓▒░░░░░░░░░░░░░▒▓▓▓ ▓▓▓▓▒░░░░░░░░░░░░░▒▓▓▒░░░░░▓▓▓ ▓▓▒░░░░░▒▓ - ▓▓░░░▒▓▓ ▓▓▒░░░▒▓▓ ▓▓░░░░▓▓ ▓▓▓▓▒░░░░░░▒▒▓▓▓▓ ▓▓▓▓▓▒▒░░░░░▒▒▓▓▓▓▓░░░░▒▓▓ ▓▓▓░░░░▒▓ - ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓ - - '); - } - - public function welcome(): void - { - info('Welcome to Moox RedisModel Installer'); - } - - public function publishConfiguration(): void - { - if (confirm('Do you wish to publish the configuration?', true)) { - if (! File::exists('config/redis-model.php')) { - info('Publishing RedisModel Configuration...'); - $this->callSilent('vendor:publish', ['--tag' => 'redis-model-config']); - - return; - } - warning('The RedisModel config already exist. The config will not be published.'); - } - } - - public function publishMigrations(): void - { - if (confirm('Do you wish to publish the migrations?', true)) { - if (Schema::hasTable('redis_models')) { - warning('The redis_models table already exists. The migrations will not be published.'); - - return; - } - info('Publishing RedisModels Migrations...'); - $this->callSilent('vendor:publish', ['--tag' => 'redis-model-migrations']); - } - } - - public function runMigrations(): void - { - if (confirm('Do you wish to run the migrations?', true)) { - info('Running RedisModel Migrations...'); - $this->callSilent('migrate'); - } - } - - public function registerPlugins(): void - { - $providerPath = app_path('Providers/Filament/AdminPanelProvider.php'); - - if (File::exists($providerPath)) { - $content = File::get($providerPath); - - $intend = ' '; - - $namespace = "\Moox\RedisModel"; - - $pluginsToAdd = multiselect( - label: 'These plugins will be installed:', - options: ['RedisModelPlugin'], - default: ['RedisModelPlugin'], - ); - - $function = '::make(),'; - - $pattern = '/->plugins\(\[([\s\S]*?)\]\);/'; - $newPlugins = ''; - - foreach ($pluginsToAdd as $plugin) { - $searchPlugin = '/'.$plugin.'/'; - if (preg_match($searchPlugin, $content)) { - warning("$plugin already registered."); - } else { - $newPlugins .= $intend.$namespace.'\\'.$plugin.$function."\n"; - } - } - - if ($newPlugins) { - if (preg_match($pattern, $content)) { - info('Plugins section found. Adding new plugins...'); - - $replacement = "->plugins([$1\n$newPlugins\n ]);"; - $newContent = preg_replace($pattern, $replacement, $content); - } else { - info('Plugins section created. Adding new plugins...'); - - $pluginsSection = " ->plugins([\n$newPlugins\n ]);"; - $placeholderPattern = '/(\->authMiddleware\(\[.*?\]\))\s*\;/s'; - $replacement = "$1\n".$pluginsSection; - $newContent = preg_replace($placeholderPattern, $replacement, $content, 1); - } - - File::put($providerPath, $newContent); - } - } else { - alert('AdminPanelProvider not found. You need to add the plugins manually.'); - } - } - - public function finish(): void - { - note('Moox RedisModel installed successfully. Enjoy!'); - } -} diff --git a/packages/redis-model/src/Exceptions/ErrorConnectToRedisException.php b/packages/redis-model/src/Exceptions/ErrorConnectToRedisException.php deleted file mode 100644 index 733d7d88c..000000000 --- a/packages/redis-model/src/Exceptions/ErrorConnectToRedisException.php +++ /dev/null @@ -1,10 +0,0 @@ -incrementing; - } - - /** - * Set whether IDs are incrementing. - * - * @param bool $value - * @return $this - */ - public function setIncrementing($value) - { - $this->incrementing = $value; - - return $this; - } - - /** - * Get the value of the model's primary key. - * - * @return mixed - */ - public function getKey() - { - return $this->getAttribute($this->getKeyName()); - } - - /** - * Get the value of the model's primary key. - * - * @return $this - */ - public function setKey($value) - { - $this->setAttribute($this->getKeyName(), $value); - - return $this; - } - - /** - * @return array - */ - public function getSubKeys() - { - return $this->subKeys; - } - - /** - * set sub keys. - * - * @return $this - */ - public function setSubKeys(array $subKeys) - { - $this->subKeys = $subKeys; - - return $this; - } - - /** - * @return bool - */ - public function getPreventCreateForce() - { - return $this->preventCreateForce; - } - - /** - * @return $this - */ - public function initialInfoTable() - { - $this->setPrefixTable(); - $this->setTable(); - - return $this; - } - - /** - * Get the table associated with the model. - * - * @return mixed - */ - public function setPrefixTable() - { - $this->prefixTable = $this->prefixTable; - } - - /** - * Get the prefix table associated with the model. - * - * @return mixed - */ - public function getPrefixTable() - { - return $this->prefixTable; - } - - /** - * Get the table associated with the model. - * - * @return string - */ - public function getTable() - { - return $this->table; - } - - /** - * set the table associated with the model. - * - * @return $this - */ - public function setTable($table = null) - { - $defaultTableName = Str::snake(Str::pluralStudly(class_basename($this))); - - $this->table = $this->getPrefixTable().($table ?? $this->table ?? $defaultTableName); - - return $this; - } - - /** - * Get the primary key for the model. - * - * @return string - */ - public function getKeyName() - { - return $this->primaryKey; - } - - /** - * Set the primary key for the model. - * - * @param string $key - * @return $this - */ - public function setKeyName($key) - { - $this->primaryKey = $key; - - return $this; - } - - /** - * Get the data type for the primary key. - * - * @return string - */ - public function getKeyType() - { - return $this->keyType; - } - - /** - * Set the data type for the primary key. - * - * @param string $type - * @return $this - */ - public function setKeyType($type) - { - $this->keyType = $type; - - return $this; - } - - /** - * Get connection name - * - * @return string - */ - public function getConnectionName() - { - $defaultConnectionName = config('redis-model.redis_model_options.database_default', 'default'); - - return $this->connectionName = $this->connectionName ?? $defaultConnectionName; - } - - public function setPrefixConnector(): void - { - $this->getConnection()->client()->setOption(self::REDIS_CLIENT_PREFIX, $this->getRedisPrefix()); - } - - /** - * @return string - */ - public function getRedisPrefix() - { - $defaultPrefix = config('database.redis.options.prefix', 'redis_model_'); - - return config('redis-model.redis_model_options.prefix', $defaultPrefix); - } - - /** - * Set connection - * - * @param string|null $nameConnect - * @return $this - */ - public function setConnection(string $connectionName) - { - try { - $this->connection = RedisFacade::connection($connectionName); - $this->setPrefixConnector(); - } catch (Exception $e) { - throw new ErrorConnectToRedisException($e->getMessage()); - } - - return $this; - } - - /** - * Join a Redis transaction with the current connection. - * - * @param Redis $connection - * @return $this - */ - public function joinTransaction(Redis $clientTransaction) - { - tap($this->connection, function ($connect) use ($clientTransaction) { - $reflectionClass = new ReflectionClass(\get_class($connect)); - $client = $reflectionClass->getProperty('client'); - $client->setAccessible(true); - $client->setValue($connect, $clientTransaction); - $this->connection = $connect; - }); - - return $this; - } - - /** - * Get connection - * - * @return mixed - */ - public function getConnection() - { - return $this->connection; - } - - /** - * Fill the model with an array of attributes. - * - * @return self - * - * @throws \Moox\RedisModel\MassAssignmentException - */ - public function fill(array $attributes) - { - $totallyGuarded = $this->totallyGuarded(); - - $fillable = $this->fillableFromArray($attributes); - - foreach ($fillable as $key => $value) { - // The developers may choose to place some attributes in the "fillable" array - // which means only those attributes may be set through mass assignment to - // the model, and all others will just get ignored for security reasons. - if ($this->isFillable($key)) { - $this->setAttribute($key, $value); - } elseif ($totallyGuarded) { - - throw new MassAssignmentException(sprintf( - 'Add [%s] to fillable property to allow mass assignment on [%s].', - $key, get_class($this) - )); - } - } - - if (count($attributes) !== count($fillable)) { - $keys = array_diff(array_keys($attributes), array_keys($fillable)); - if ($this->flexibleFill) { - foreach ($keys as $key) { - $this->setAttribute($key, $attributes[$key]); - } - } else { - throw new MassAssignmentException(sprintf( - 'Add fillable property [%s] to allow mass assignment on [%s].', - implode(', ', $keys), - get_class($this) - )); - } - } - - return $this; - } - - /** - * Save the model to the database. - * - * @param array $options - * @return bool - */ - public function save() - { - $this->mergeAttributesFromCachedCasts(); - // If the model already exists in the database we can just update our record - // that is already in this database using the current IDs in this "where" - // clause to only update this model. Otherwise, we'll just insert them. - - $query = $this->newQuery(); - - if ($this->exists) { - $saved = $this->isDirty() ? - $this->performUpdate($query) : true; - } - - // If the model is brand new, we'll insert it into our database and set the - // ID attribute on the model to the value of the newly inserted row's ID - // which is typically an auto-increment value managed by the database. - else { - $saved = $this->performInsert($query); - } - - // If the model is successfully saved, we need to do a few more things once - // that is done. We will call the "saved" method here to run any actions - // we need to happen after a model gets successfully saved right here. - if ($saved) { - $this->finishSave(); - } - - return $saved; - } - - /** - * Perform any actions that are necessary after the model is saved. - * - * @param array $options - * @return self - */ - protected function finishSave() - { - $this->syncOriginal(); - } - - /** - * Perform a model update operation. - * - * @return bool - */ - protected function performUpdate(Builder $build) - { - // First we need to create a fresh query instance and touch the creation and - // update timestamp on the model which are maintained by us for developer - // convenience. Then we will just continue saving the model instances. - if ($this->usesTimestamps()) { - $this->updateTimestamps(); - } - - // Once we have run the update operation, we will fire the "updated" event for - // this model instance. This will allow developers to hook into these after - // models are updated, giving them a chance to do any special processing. - $dirty = $this->getDirty(); - - if (count($dirty) > 0) { - $attributes = $this->getAttributesForInsert(); - if ($this->isValidationKeyAndSubKeys($attributes)) { - $attributes = collect($attributes)->map(function ($item, $key) { - return (string) $this->castAttributeBeforeSave($key, $item); - })->toArray(); - - $keyOrigin = $build->compileHashByFields($this->parseAttributeKeyBooleanToInt(($this->getOriginal()))); - $keyNew = $build->compileHashByFields($this->parseAttributeKeyBooleanToInt($attributes)); - $build->getRepository()->updateRedisHashes($keyOrigin, $attributes, $keyNew); - - $this->exists = true; - $this->redisKey = $keyNew; - - return true; - } else { - throw new RedisModelException('Primary key and sub key values are required'); - } - } - - return false; - } - - /** - * Casts and prepares an attribute value before saving it to the database. - * - * @param string $key - * @param mixed $value - * @return mixed The - */ - public function castAttributeBeforeSave($key, $value) - { - // Cast the attribute if necessary - $value = $this->hasCast($key) ? $this->castAttribute($key, $value) : $value; - - // If the attribute is a Carbon instance, format it using the model's date format - if ($value instanceof Carbon) { - $value = $value->format($this->getDateFormat()); - } - - // If the attribute is an array, encode it to JSON - if (is_array($value)) { - $value = json_encode($value); - } - - // If the attribute is a boolean, cast it to an integer - if (is_bool($value)) { - $value = (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); - } - - // If the attribute is enum castable, extract its value - if ($this->isEnumCastable($key)) { - $value = $value->value; - } - - // Return the transformed and casted attribute value - return $value; - } - - /** - * Perform a model insert operation. - * - * @return bool - */ - protected function performInsert(Builder $build) - { - // First we'll need to create a fresh query instance and touch the creation and - // update timestamps on this model, which are maintained by us for developer - // convenience. After, we will just continue saving these model instances. - if ($this->usesTimestamps()) { - $this->updateTimestamps(); - } - - if ($this->getIncrementing() && $this->getKeyType() && $this->getKey() == null) { - $this->setKey(Str::uuid()); - } - - if (! $this->isPrioritizeForceSave()) { - if ($this->getPreventCreateForce() && $this->isKeyExist()) { - throw new KeyExistException( - 'Key '.$this->getKeyName().' '.$this->{$this->getKeyName()}.' already exists.' - ); - } - } - - // If the model has an incrementing key, we can use the "insertGetId" method on - // the query builder, which will give us back the final inserted ID for this - // table from the database. Not all tables have to be incrementing though. - $attributes = $this->getAttributesForInsert(); - - if (empty($attributes)) { - return true; - } - - if ($this->isValidationKeyAndSubKeys($attributes)) { - $attributes = collect($attributes)->map(function ($item, $key) { - return (string) $this->castAttributeBeforeSave($key, $item); - })->toArray(); - - $keyInsert = $build->compileHashByFields($this->parseAttributeKeyBooleanToInt($attributes)); - $build->getRepository()->insertRedisHashes($keyInsert, $attributes); - } else { - throw new RedisModelException('Primary key and sub key values are required'); - } - - // We will go ahead and set the exists property to true, so that it is set when - // the created event is fired, just in case the developer tries to update it - // during the event. This will allow them to do so and run an update here. - $this->exists = true; - $this->redisKey = $keyInsert; - - return true; - } - - /** - * Deletes the current model from Redis if the primary key and sub-keys are valid. - * If the delete operation is successful, it returns true. Otherwise, it returns false. - * - * @return bool Returns true if the deletion is successful; otherwise, false. - */ - public function performDeleteOnModel() - { - if ($this->isValidationKeyAndSubKeys($this->getOriginal())) { - $build = $this->query(); - $keyRemove = $build->compileHashByFields($this->getOriginal()); - $build->getRepository()->destroyHash($keyRemove); - } else { - return false; - } - - $this->exists = false; - - return true; - } - - /** - * Inserts multiple data into Redis hashes. - * - * @param array $dataInsert An array of data to insert into Redis hashes. - * @param Redis $hasTransaction a redis client. - * @return mixed Returns the result of inserting multiple Redis hashes, or false if the data is invalid. - */ - public static function insert(array $dataInsert, ?Redis $hasTransaction = null) - { - $inserts = []; - $build = static::query(); - $model = $build->getModel(); - - if ($hasTransaction) { - $model->joinTransaction($hasTransaction); - } - - foreach ($dataInsert as $attributes) { - if ($model->getIncrementing() && $model->getKeyType() && ! isset($attributes[$model->getKeyName()])) { - $attributes[$model->getKeyName()] = Str::uuid(); - } - - if ($model->isValidationKeyAndSubKeys($attributes)) { - $key = $build->compileHashByFields($attributes); - - // If the model uses timestamps, update them in the attributes - if ($model->usesTimestamps()) { - $model->updateTimestamps(); - $attributes = array_merge($attributes, $model->getAttributes()); - } - - $inserts[$key] = collect($attributes)->map(function ($item, $key) use ($model) { - return (string) $model->castAttributeBeforeSave($key, $item); - })->toArray(); - } else { - return false; - } - } - - return $build->getRepository()->insertMultipleRedisHashes($inserts); - } - - /** - * Update the model in the database. - * - * - * @return bool - */ - public function update(array $attributes = []) - { - if (! $this->exists) { - return false; - } - - return $this->fill($attributes)->save(); - } - - /** - * Set the number of seconds expire key model - * - * - * @return bool - */ - public function setExpire(int|Carbon $seconds) - { - if (! $this->exists) { - return false; - } - - if ($seconds instanceof Carbon) { - $seconds = now()->diffInSeconds($seconds); - } - - if ($this->isValidationKeyAndSubKeys($this->getOriginal())) { - $build = $this->query(); - $key = $build->compileHashByFields($this->getOriginal()); - - return $build->getRepository()->setExpireByHash($key, $seconds); - } else { - return false; - } - } - - /** - * Get the number of seconds expire key model - * - * @return bool - */ - public function getExpire() - { - if (! $this->exists) { - return false; - } - - if ($this->isValidationKeyAndSubKeys($this->getOriginal())) { - $build = $this->query(); - $key = $build->compileHashByFields($this->getOriginal()); - - return $build->getRepository()->getExpireByHash($key); - } else { - return false; - } - } - - /** - * Delete the model from the database. - * - * @return bool|null - * - * @throws \LogicException - */ - public function delete() - { - $this->mergeAttributesFromCachedCasts(); - - if ($this->getKeyName() === null) { - throw new LogicException('No primary key defined on model.'); - } - - // If the model doesn't exist, there is nothing to delete so we'll just return - // immediately and not do anything else. Otherwise, we will continue with a - // deletion process on the model, firing the proper events, and so forth. - if (! $this->exists) { - return; - } - - $this->performDeleteOnModel(); - - return true; - } - - /** - * Get all of the models from the database. - * - * @return \Moox\RedisModel\Collection - */ - public static function all() - { - return static::query()->get(); - } - - /** - * Create a new Eloquent Collection instance. - * - * @return \Moox\RedisModel\Collection - */ - public function newCollection(array $models = []) - { - return new Collection($models); - } - - /** - * Begin querying the model. - * - * @return \Moox\RedisModel\Builder - */ - public static function query() - { - return (new static)->newQuery(); - } - - /** - * Run a transaction with the given callback. - * - * - * @return mixed The result of the callback - */ - public static function transaction(callable $callback) - { - $build = static::query(); - - return $build->getRepository()->transaction($callback); - } - - /** - * Get a new query builder for the model's table. - * - * @return \Moox\RedisModel\Builder - */ - public function newQuery() - { - return $this->newBuilder($this->getConnection())->setModel($this); - } - - /** - * Create a new Eloquent query builder for the model. - * - * @param \Moox\RedisModel $query - * @return Moox\RedisModel\Builder - */ - public function newBuilder($connection) - { - return new Builder($connection); - } - - /** - * Create a new instance of the given model. - * - * @param array $attributes - * @param bool $exists - * @param bool $isCastAttribute - * @return static - */ - public function newInstance($attributes = [], $exists = false, ?string $redisKey = null, $isCastAttribute = false) - { - // This method just provides a convenient way for us to generate fresh model - // instances of this current model. It is particularly useful during the - // hydration of new objects via the Eloquent query builder instances. - $model = new static; - - $model->exists = $exists; - - $model->redisKey = $redisKey; - - $this->setDateFormat('Y-m-d\\TH:i:sP'); - - $model->setTable($this->getTable()); - - $model->mergeCasts($this->casts); - - if ($isCastAttribute) { - $castAttributes = collect($attributes)->mapWithKeys(function ($value, $key) use ($model) { - return [$key => $model->transformModelValue($key, $value)]; - })->all(); - - $model->fill((array) $castAttributes); - } else { - $model->fill((array) $attributes); - } - - return $model; - } - - /** - * Create a new Eloquent model instance. - * - * @return void - */ - public function __construct(array $attributes = []) - { - $this->setDateFormat('Y-m-d\\TH:i:sP'); - $this->initialInfoTable(); - $this->setConnection($this->getConnectionName()); - $this->syncOriginal(); - - $this->fill($attributes); - } - - /** - * Dynamically retrieve attributes on the model. - * - * @param string $key - * @return mixed - */ - public function __get($key) - { - return $this->getAttribute($key); - } - - /** - * Dynamically set attributes on the model. - * - * @param string $key - * @param mixed $value - * @return void - */ - public function __set($key, $value) - { - $this->setAttribute($key, $value); - } - - /** - * Determine if an attribute or relation exists on the model. - * - * @param string $key - * @return bool - */ - public function __isset($key) - { - return $this->offsetExists($key); - } - - /** - * Unset an attribute on the model. - * - * @param string $key - * @return void - */ - public function __unset($key) - { - $this->offsetUnset($key); - } - - /** - * Handle dynamic method calls into the model. - * - * @param string $method - * @param array $parameters - * @return mixed - */ - public function __call($method, $parameters) - { - return $this->forwardCallTo($this->query(), $method, $parameters); - } - - /** - * Handle dynamic static method calls into the model. - * - * @param string $method - * @param array $parameters - * @return mixed - */ - public static function __callStatic($method, $parameters) - { - return (new static)->$method(...$parameters); - } - - /** - * Convert the model to its string representation. - * - * @return string - */ - public function __toString() - { - return $this->escapeWhenCastingToString - ? e($this->toJson()) - : $this->toJson(); - } - - /** - * Indicate that the object's string representation should be escaped when __toString is invoked. - * - * @param bool $escape - * @return $this - */ - public function escapeWhenCastingToString($escape = true) - { - $this->escapeWhenCastingToString = $escape; - - return $this; - } - - /** - * Prepare the object for serialization. - * - * @return array - */ - public function __sleep() - { - $this->mergeAttributesFromCachedCasts(); - - $this->classCastCache = []; - $this->attributeCastCache = []; - - return array_keys(get_object_vars($this)); - } - - /** - * Convert the model instance to an array. - */ - public function toArray(): array - { - return $this->attributesToArray(); - } - - /** - * Convert the model instance to JSON. - * - * @param int $options - */ - public function toJson($options = 0): string - { - $json = json_encode($this->jsonSerialize(), $options); - - return $json; - } - - /** - * Convert the object into something JSON serializable. - * - * @return array - */ - public function jsonSerialize() - { - return $this->toArray(); - } - - /** - * When a model is being unserialized, check if it needs to be booted. - * - * @return void - */ - public function __wakeup() - { - } - - /** - * Determine if the given attribute exists. - * - * @param mixed $offset - */ - public function offsetExists($offset): bool - { - try { - return $this->getAttribute($offset) === null; - } catch (MissingAttributeException) { - return false; - } - } - - /** - * Get the value for a given offset. - * - * @param mixed $offset - */ - public function offsetGet($offset): mixed - { - return $this->getAttribute($offset); - } - - /** - * Set the value for a given offset. - * - * @param mixed $offset - * @param mixed $value - */ - public function offsetSet($offset, $value): void - { - $this->setAttribute($offset, $value); - } - - /** - * Unset the value for a given offset. - * - * @param mixed $offset - */ - public function offsetUnset($offset): void - { - unset($this->attributes[$offset]); - } - - /** - * Determine if the given key is a relationship method on the model. - * - * @param string $key - * @return bool - */ - public function isRelation($key) - { - return false; - } - - /** - * Determine if the given relation is loaded. - * - * @param string $key - * @return bool - */ - public function relationLoaded($key) - { - return false; - } - - /** - * Determine if two models are not the same. - * - * @param \Moox\RedisModel\Model|null $model - * @return bool - */ - public function isNot($model) - { - return ! $this->is($model); - } - - /** - * Get the table qualified key name. - * - * @return string - */ - public function getQualifiedKeyName() - { - return $this->qualifyColumn($this->getKeyName()); - } - - /** - * Qualify the given column name by the model's table. - * - * @param string $column - * @return string - */ - public function qualifyColumn($column) - { - if (str_contains($column, '.')) { - return $column; - } - - return $column; - } - - /** - * Qualify the given columns with the model's table. - * - * @param array $columns - * @return array - */ - public function qualifyColumns($columns) - { - return collect($columns)->map(function ($column) { - return $this->qualifyColumn($column); - })->all(); - } - - /** - * Set flag force insert of model - * - * @return self - */ - public function setPrioritizeForceSave() - { - $this->prioritizeForceSave = true; - - return $this; - } - - /** - * Get flag force insert of model - * - * @return bool - */ - protected function isPrioritizeForceSave() - { - if (isset($this->attributes['prioritizeForceSave'])) { - unset($this->attributes['prioritizeForceSave']); - - return true; - } - - return false; - } - - /** - * @return bool - */ - protected function isKeyExist() - { - return $this->query()->isExists($this->getAttributesForInsert()); - } - - /** - * @return bool - */ - protected function isValidationKeyAndSubKeys($attributes) - { - $listKey = array_merge([$this->getKeyName()], $this->getSubKeys()); - - foreach ($listKey as $key) { - if (! isset($attributes[$key]) || - (isset($this->getCasts()[$key]) && $this->getCasts()[$key] != 'boolean' && empty($attributes[$key]))) { - return false; - } - } - - return true; - } - - /** - * @param array $value - * @return int - */ - private function parseAttributeKeyBooleanToInt($attributes) - { - foreach ($attributes as $key => $value) { - if (isset($this->getCasts()[$key]) && $this->getCasts()[$key] == 'boolean') { - $attributes[$key] = (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); - } - } - - return $attributes; - } -} diff --git a/packages/redis-model/src/Models/RedisModel.php b/packages/redis-model/src/Models/RedisModel.php deleted file mode 100644 index a3af869a0..000000000 --- a/packages/redis-model/src/Models/RedisModel.php +++ /dev/null @@ -1,23 +0,0 @@ - 'bool', - 'started_at' => 'datetime', - 'finished_at' => 'datetime', - ]; -} diff --git a/packages/redis-model/src/RedisModelPlugin.php b/packages/redis-model/src/RedisModelPlugin.php deleted file mode 100644 index ce2bdd14c..000000000 --- a/packages/redis-model/src/RedisModelPlugin.php +++ /dev/null @@ -1,35 +0,0 @@ -resources([ - RedisModelResource::class, - ]); - } - - public function boot(Panel $panel): void - { - // - } - - public static function make(): static - { - return app(static::class); - } -} diff --git a/packages/redis-model/src/RedisModelServiceProvider.php b/packages/redis-model/src/RedisModelServiceProvider.php deleted file mode 100644 index 8bb6ad2d6..000000000 --- a/packages/redis-model/src/RedisModelServiceProvider.php +++ /dev/null @@ -1,23 +0,0 @@ -name('redis-model') - ->hasConfigFile() - ->hasViews() - ->hasTranslations() - ->hasMigrations(['create_redis_models_table']) - ->hasCommand(InstallCommand::class); - } -} diff --git a/packages/redis-model/src/RedisRepository.php b/packages/redis-model/src/RedisRepository.php deleted file mode 100644 index 7847e5027..000000000 --- a/packages/redis-model/src/RedisRepository.php +++ /dev/null @@ -1,340 +0,0 @@ -connection = $connection; - } - - /** - * Get connection - */ - public function getConnection(): PhpRedisConnection - { - return $this->connection; - } - - /** - *Gets the Redis prefix for keys used by the Redis model. - *The prefix is determined by looking at the redis_model_options.prefix configuration value first, - *Then falling back to the database.redis.options.prefix configuration value. - * - * @return string The Redis key prefix for this model. - */ - public function getRedisPrefix() - { - $defaultPrefix = config('database.redis.options.prefix', 'redis_model_'); - - return config('redis-model.redis_model_options.prefix', $defaultPrefix); - } - - /** - * Retrieves all Redis keys matching a given pattern, after removing the database prefix. - * - * @param string|null $hash The pattern to match the Redis keys against, or null to match all keys. - * @return array An array of Redis keys matching the pattern, with the database prefix removed. - */ - public function getHashByPattern(?string $hash) - { - return self::removeSlugDatabaseFromRedisKeys($this->getConnection()->keys($hash), $this->getRedisPrefix()); - } - - /** - * Counts the number of Redis hash keys that match the given pattern. - * - * @param string $pattern The Redis hash key pattern to match. - * @return int The number of Redis hash keys that match the given pattern - */ - public function countByPattern(string $pattern): int - { - return count($this->getHashByPattern($pattern)); - } - - /** - * Fetches all fields and their values for a given Redis hash key - * - * @param string $hash The Redis hash key - * @return array An array containing all fields and their corresponding values for the given Redis hash key - */ - public function fetchProperByHash($hash) - { - return $this->getConnection()->hGetAll($hash); - } - - /** - * Retrieves hash data from multiple Redis keys using a pipeline approach and returns it in an associative array - * - * @param array $keys An array of Redis keys - * @return array An associative array containing hash data retrieved from multiple Redis keys - */ - public function fetchProperByListHash(array $keys) - { - $result = []; - - $fetch = $this->getConnection()->pipeline(function ($pipe) use ($keys) { - foreach (self::removeSlugDatabaseFromRedisKeys($keys, $this->getRedisPrefix()) as $key) { - $pipe->hGetAll($key); - } - }); - - foreach ($keys as $cursor => $key) { - $result[$key] = $fetch[$cursor]; - } - - return $result; - } - - /** - * Retrieves all data from Redis hashes that match the given pattern. - * - * @param string $pattern The pattern to match against Redis hashes. - * @return array The data from Redis hashes that match the given pattern. - */ - public function fetchHashDataByPattern(string $pattern) - { - $keys = $this->getHashByPattern($pattern); - - foreach ($keys as $key) { - $data[$key] = $this->fetchProperByHash($key); - } - - return $data ?? []; - } - - /** - * Inserts a Redis hash with the given key and data. - * - * @param string $key The key of the Redis hash. - * @param array $data An associative array of fields and their values. - * @return bool|int Returns `true` on success, `false` on failure. - */ - public function insertRedisHashes(string $key, array $data) - { - return $this->getConnection()->hMSet($key, $data); - } - - /** - * Update the values of a Redis hash with the given data, and optionally rename the hash. - * - * @param string $oldHash The name of the Redis hash to update. - * @param string $newHash The new name for the Redis hash. If set, the old hash will be renamed to this new name. - * @return bool True on success, false on failure. - */ - public function renameRedisHash(string $oldHash, string $newHash) - { - return $this->getConnection()->rename($oldHash, $newHash); - } - - /** - * Update the data of a Redis hash. - * - * @param string $oldHash The old hash key to update. - * @param array $data An associative array containing the field-value pairs to update. - * @param string|null $newHash The new hash key to rename the old hash key to, if provided. - * @return bool Returns true if the update was successful, false otherwise. - */ - public function updateRedisHashes(string $oldHash, array $data, ?string $newHash = null) - { - return $this->transaction(function ($conTransaction) use ($oldHash, $newHash, $data) { - try { - if ($newHash != null && $oldHash != $newHash) { - $conTransaction->rename($oldHash, $newHash); - } - - $conTransaction->hMSet($newHash, $data); - - return true; - } catch (Exception $e) { - // Todo - //$transaction->discard(); - - return false; - } - }); - } - - /** - * Insert multiple Redis hashes with key-value pairs in bulk - * - * @param array $hashes Array of Redis hashes with key-value pairs to insert in bulk. - * Format: [Key => [Field => Value, ...], ...] - * @return bool Returns true if all hashes were inserted successfully, false otherwise. - */ - public function insertMultipleRedisHashes(array $hashes) - { - foreach ($hashes as $key => $data) { - $this->getConnection()->hMSet($key, $data); - } - - return true; - } - - /** - * Destroy a hash from Redis by given key or keys. - * - * @param string|array $keys The key or keys to delete from Redis. - * @return bool True if the hash was deleted successfully, false otherwise. - */ - public function destroyHash(string|array $keys) - { - if (is_string($keys)) { - $deleted = (bool) $this->getConnection()->del($keys); - } elseif (is_array($keys)) { - $deleted = (bool) $this->getConnection()->del($keys); - } else { - $deleted = false; - } - - return $deleted; - } - - /** - * Set a time-to-live on a hash key. - * - * @param string $keyHash The key to set the time-to-live. - * @param int $seconds The number of seconds until the key should expire. - * @return bool True if the timeout was set successfully, false otherwise. - */ - public function setExpireByHash(string $keyHash, int $seconds) - { - return (bool) $this->getConnection()->expire($keyHash, $seconds); - } - - /** - * Get the time-to-live of a hash key. - * - * @param string $keyHash The key of the hash to get the time-to-live for. - * @return int|null The number of seconds until the key will expire, or null if the key does not exist or has no timeout. - */ - public function getExpireByHash(string $keyHash) - { - return $this->getConnection()->ttl($keyHash); - } - - /** - * guaranteedScan function scans Redis keys matching the given pattern using the given cursor and retrieves a set number of keys. - * - * @param string $keyPattern The pattern to match Redis keys with - * @param int $take The number of keys to retrieve - * @param int $cursor The cursor used to continue a scan (default: 0) - * @param array $keyResultRemaining Array of remaining keys from a previous scan (default: empty array) - * @return array Returns an array containing the retrieved keys, cursor for the next scan, a boolean indicating if there are more keys available for scanning, and any remaining keys from the scan. - */ - public function guaranteedScan(string $keyPattern, int $take, int $cursor = 0, $keyResultRemaining = []) - { - $cursor = $cursor === 0 ? ((string) $cursor) : $cursor; - $keys = $keyResultRemaining; - - do { - [$cursor, $result] = $this->getConnection()->scan($cursor, [ - 'match' => $this->getRedisPrefix().$keyPattern, - 'count' => $take, - ]); - - $keys = array_merge($keys, ($result ?? [])); - - if (count($keys) > $take || $cursor == null) { - break; - } - } while ($cursor != '0'); - - // creates an array of the first $take keys from the $keys array. - $keyResult = array_slice($keys, 0, $take); - // creates an array of the remaining keys after the first $take keys in the $keys array. - $keyResultRemaining = array_slice($keys, $take); - - return [ - 'keys' => $keyResult, - 'cursorNext' => $cursor, - 'isNext' => $cursor != '0' ? true : false, - 'keyResultRemaining' => $keyResultRemaining, - ]; - } - - /** - * scanByHash function scans a Redis hash and retrieves its keys and values by calling a callback function for each batch of keys. - * - * @param string $keyHash The Redis hash to scan - * @param int $limit The maximum number of keys to retrieve per batch - * @param callable $callback A callback function to process each batch of keys - * @return bool Returns a boolean indicating if the scan was successful or not. - */ - public function scanByHash(string $keyHash, int $limit, callable $callback) - { - $amountOfDataCommit = $this->countByPattern($keyHash); - - //Check the total amount of data that can be retrieved with the hash pattern - if ($amountOfDataCommit == 0) { - call_user_func_array($callback, [[], false]); - } else { - $cursor = 0; - $scan = ['cursorNext' => 0, 'isNext' => false, 'keyResultRemaining' => []]; - - do { - $scan = $this->guaranteedScan($keyHash, $limit, $cursor, $scan['keyResultRemaining'] ?? []); - - call_user_func_array($callback, [$scan['keys'], $scan['isNext']]); - $cursor = $scan['cursorNext']; - } while ($scan['isNext']); - - // This will ensure that no callback function is missed with remaining data - // because when the guaranteedScan function notifies that the cursor has been fully iterated, - // the loop controlled by the while statement will stop and skip any remaining data. - if ($scan['cursorNext'] === 0 && $scan['isNext'] === false && ! empty($scan['keyResultRemaining'])) { - call_user_func_array($callback, [$scan['keyResultRemaining'], false]); - } - } - - return true; - } - - /** - * Run a Redis transaction with the given callback. - * - * @param callable $callback The closure to be executed as part of the transaction - * @return bool|array Returns a boolean indicating if the transaction was successful or not. - */ - public function transaction(callable $callback) - { - return $this->getConnection()->transaction(function ($conTransaction) use ($callback) { - try { - $callback($conTransaction); - $result = $conTransaction->exec(); - - if ($result === false) { - throw new ErrorTransactionException('Transaction failed to execute'); - } - } catch (Exception $e) { - $conTransaction->discard(); - - return false; - } - }); - } - - /** - * Removes the Redis prefix from an array of keys. - * - * @param array $keys An array of keys with Redis prefix - * @param string $prefix The Redis key prefix for this model. - * @return array An array of keys with Redis prefix removed - */ - public static function removeSlugDatabaseFromRedisKeys(array $keys, string $prefix) - { - return array_map(function ($key) use ($prefix) { - return str_replace($prefix, '', $key); - }, $keys); - } -} diff --git a/packages/redis-model/src/Resources/RedisModelResource.php b/packages/redis-model/src/Resources/RedisModelResource.php deleted file mode 100644 index 7545e184c..000000000 --- a/packages/redis-model/src/Resources/RedisModelResource.php +++ /dev/null @@ -1,121 +0,0 @@ -schema([ - TextInput::make('name') - ->maxLength(255), - DateTimePicker::make('started_at'), - DateTimePicker::make('finished_at'), - Toggle::make('failed') - ->required(), - ]); - } - - public static function table(Table $table): Table - { - return $table - ->columns([ - TextColumn::make('name') - ->label(__('redis-model::translations.name')) - ->sortable(), - TextColumn::make('started_at') - ->label(__('redis-model::translations.started_at')) - ->since() - ->sortable(), - TextColumn::make('failed') - ->label(__('redis-model::translations.failed')) - ->sortable(), - ]) - ->defaultSort('name', 'desc') - ->actions([ - EditAction::make(), - ]) - ->bulkActions([ - DeleteBulkAction::make(), - ]); - } - - public static function getRelations(): array - { - return [ - // - ]; - } - - public static function getPages(): array - { - return [ - 'index' => ListPage::route('/'), - ]; - } - - public static function getWidgets(): array - { - return [ - RedisModelWidgets::class, - ]; - } - - public static function getModelLabel(): string - { - return __('redis-model::translations.single'); - } - - public static function getPluralModelLabel(): string - { - return __('redis-model::translations.plural'); - } - - public static function getNavigationLabel(): string - { - return __('redis-model::translations.navigation_label'); - } - - public static function getBreadcrumb(): string - { - return __('redis-model::translations.breadcrumb'); - } - - public static function shouldRegisterNavigation(): bool - { - return true; - } - - public static function getNavigationBadge(): ?string - { - return number_format(static::getModel()::count()); - } - - public static function getNavigationGroup(): ?string - { - return __('redis-model::translations.navigation_group'); - } - - public static function getNavigationSort(): ?int - { - return config('redis-model.navigation_sort'); - } -} diff --git a/packages/redis-model/src/Resources/RedisModelResource/Pages/ListPage.php b/packages/redis-model/src/Resources/RedisModelResource/Pages/ListPage.php deleted file mode 100644 index ba32e4f14..000000000 --- a/packages/redis-model/src/Resources/RedisModelResource/Pages/ListPage.php +++ /dev/null @@ -1,41 +0,0 @@ -using(function (array $data, string $model): RedisModel { - return $model::create($data); - }), - ]; - } -} diff --git a/packages/redis-model/src/Resources/RedisModelResource/Widgets/RedisModelWidgets.php b/packages/redis-model/src/Resources/RedisModelResource/Widgets/RedisModelWidgets.php deleted file mode 100644 index dc13e6ac3..000000000 --- a/packages/redis-model/src/Resources/RedisModelResource/Widgets/RedisModelWidgets.php +++ /dev/null @@ -1,30 +0,0 @@ -select($aggregationColumns) - ->first(); - - return [ - Stat::make(__('redis-model::translations.totalone'), $aggregatedInfo->count ?? 0), - Stat::make(__('redis-model::translations.totaltwo'), $aggregatedInfo->count ?? 0), - Stat::make(__('redis-model::translations.totalthree'), $aggregatedInfo->count ?? 0), - ]; - } -} diff --git a/packages/redis-model/src/UsesRedis.php b/packages/redis-model/src/UsesRedis.php deleted file mode 100644 index 3e4ec896f..000000000 --- a/packages/redis-model/src/UsesRedis.php +++ /dev/null @@ -1,84 +0,0 @@ -useRedis === true; - } - - /** - * Save the model instance by storing it in Redis. - */ - public function save(array $options = []) - { - if (! $this->isRedisEnabled()) { - return parent::save($options); - } - - $key = $this->getRedisKey(); - Redis::set($key, json_encode($this->attributes)); - - return true; - } - - /** - * Delete the model instance by removing it from Redis. - */ - public function delete() - { - if (! $this->isRedisEnabled()) { - return parent::delete(); - } - - Redis::del($this->getRedisKey()); - - return true; - } - - /** - * Retrieve a model by its primary key. - */ - public static function find($id) - { - $instance = new static; - - if (! $instance->isRedisEnabled()) { - return parent::find($id); - } - - $key = $instance->getRedisKey($id); - $data = Redis::get($key); - - return $data ? new static(json_decode($data, true)) : null; - } - - /** - * Generate a Redis key for the model. - */ - protected function getRedisKey($id = null) - { - $id = $id ?: $this->{$this->getKeyName()}; - - return 'model:'.static::class.':'.$id; - } -}