[增添]添加了datasource的setting数据库以及默认值

This commit is contained in:
makotocc0107
2024-08-27 09:57:44 +08:00
parent d111dfaea4
commit 72eb990970
10955 changed files with 978898 additions and 0 deletions

View File

@@ -0,0 +1,262 @@
# Changelog
All notable changes to `laravel-settings` will be documented in this file
# Unreleased
- Make `spatie/data-transfer-object` dependency optional. (#160)
## 3.3.1 - 2024-03-13
### What's Changed
* fix when base path is app path by @mvenghaus in https://github.com/spatie/laravel-settings/pull/259
**Full Changelog**: https://github.com/spatie/laravel-settings/compare/3.3.0...3.3.1
## 3.3.0 - 2024-02-19
### What's Changed
* Update composer.json to use Larastan Org by @arnebr in https://github.com/spatie/laravel-settings/pull/252
* Add support for laravel 11 by @shuvroroy in https://github.com/spatie/laravel-settings/pull/256
* Added settings driven custom encoder/decoder by @naxvog in https://github.com/spatie/laravel-settings/pull/250
**Full Changelog**: https://github.com/spatie/laravel-settings/compare/3.2.3...3.3.0
## 3.2.3 - 2023-12-04
- Revert "Use Illuminate\Database\Eloquent\Casts\Json if possible" (#249)
## 3.2.2 - 2023-12-01
- Use Illuminate\Database\Eloquent\Casts\Json if possible (#241)
## 3.2.1 - 2023-09-15
- Change provider tag name for config (#233)
## 3.2.0 - 2023-07-05
- Add support for database-less fakes
## 3.1.0 - 2023-05-11
- Add support for nullable enum properties
- Updates to the upgrade guide
## 3.0.0 - 2023-04-28
- Allow repositories to update multiple settings at once (#213 )
- The default location where searching for settings happens is now `app_path('Settings')` instead of `app_path()`
- The default `discovered_settings_cache_path` is changed
## 2.8.3 - 2023-03-30
- Remove doctrine as a dependency
## 2.8.2 - 2023-03-10
- Fix remigration problems with anonymous settings migrations
## 2.8.1 - 2023-03-02
- Show message and target path after setting migration created (#203)
- Follow Laravel's namespace convention in MakeSettingCommand (#200)
- Update MakeSettingsMigrationCommand.php (#205)
- Revert "Add support for structure discoverer"( #207)
## 2.8.0 - 2023-02-10
- Drop Laravel 8 support
- Drop PHP 8.0 support
- Use spatie/structures-discoverer for finding settings
## 2.7.0 - 2023-02-01
- Add Laravel 10 Support (#192)
- Update make:settings migration class as anonymous class (#189)
- Use correct namespace in make:settings command (#190)
## 2.6.1 - 2023-01-06
- Add current date to the settings migration file (#178)
- Add command to make new settings (#181)
## 1.6.1 - 2022-12-21
- create settings migration with current date (#179)
## 2.6.0 - 2022-11-24
- Add support for caching on repository level
## 2.5.0 - 2022-11-10
- Remove deprecated package
- Add laravel data cast
- Add support for PHP 8.2
- Remove PHP 7.4 support
- Remove dto cast from default config
## 2.4.5 - 2022-09-28
- Add deleteIfExists() method to migrator (#154)
## 2.4.4 - 2022-09-07
- cache encrypted settings
Please, be sure to clear your cache since settings classes with encrypted properties will crash due to the cached versions missing a proper encrypted version of the property. Clearing and caching again after installing this version resolves this problem and is something you probably should always do when deploying to production!
## 2.4.3 - 2022-08-10
- add rollback to migration
## 2.4.2 - 2022-06-17
- use Facade imports instead of aliases (#132)
## 2.4.1 - 2022-04-07
- Switch to using scoped instances instead of singletons (#129)
## 2.4.0 - 2022-03-22
## What's Changed
- Add TTL config for settings cache by @AlexVanderbist in https://github.com/spatie/laravel-settings/pull/122
## New Contributors
- @AlexVanderbist made their first contribution in https://github.com/spatie/laravel-settings/pull/122
**Full Changelog**: https://github.com/spatie/laravel-settings/compare/2.3.3...2.4.0
## 2.3.3 - 2022-03-18
- fix debug info method
- convert PHPUnit to Pest (#118)
## 2.3.2 - 2022-02-25
- Allow migrations without a value (#113)
## 2.3.1 - 2022-02-04
- Add support for Laravel 9
- Fix cache implementation with casts
- Remove Psalm
- Add PHPStan
## 2.2.0 - 2021-10-22
- add support for multiple migration paths (#92)
## 2.1.12 - 2021-10-14
- add possibility to check if setting is locked or unlocked (#89)
## 2.1.11 - 2021-08-23
- ignore abstract classes when discovering settings (#84)
## 2.1.10 - 2021-08-17
- add support for `null` in DateTime casts
## 2.1.9 - 2021-07-08
- fix `empty` call not working when properties weren't loaded
## 2.1.8 - 2021-06-21
- fix fake settings not working with `Arrayable`
## 2.1.7 - 2021-06-08
- add support for refreshing settings
## 2.1.6 - 2021-06-03
- add support for defining the database connection table
## 2.1.5 - 2021-05-21
- fix some casting problems
- update php-cs-fixer
## 2.1.4 - 2021-04-28
- added fallback for settings.auto_discover_settings (#63)
- add support for spatie/data-transfer-object v3 (#62)
## 2.1.3 - 2021-04-14
- add support for spatie/temporary-directory v2
## 2.1.2 - 2021-04-08
- skip classes with errors when discovering settings
## 2.1.1 - 2021-04-07
- add better support for nullable types in docblocks
## 2.1.0 - 2021-04-07
- add casts to migrations (#53)
- add original properties to `SavingSettings` event (#57)
## 2.0.1 - 2021-03-05
- add support for lumen
## 2.0.0 - 2021-03-03
- settings classes:
- properties won't be loaded when constructed but when requested
- receive a `SettingsMapper` when constructed
- faking settings will now only request non-given properties from the repository
- rewritten `SettingsMapper` from scratch
- removed `SettingsPropertyData` and `ettingsPropertyDataCollection`
- changed signatures of `SavingSettings` and `LoadingSettings` events
- added support for caching settings
- renamed `cache_path` in settings.php to `discovered_settings_cache_path`
## 1.0.8 - 2021-03-03
- fix for properties without defined type
## 1.0.7 - 2021-02-19
- fix correct 'Event' facade (#30)
## 1.0.6 - 2021-02-05
- add support for restoring settings after a Laravel schema:dump
## 1.0.5 - 2021-01-29
- bump the `doctrine/dbal` dependency
## 1.0.4 - 2021-01-08
- add support for getting the locked settings
## 1.0.3 - 2020-11-26
- add PHP 8 support
## 1.0.2 - 2020-11-26
- fix package namespace within migrations (#9)
## 1.0.1 - 2020-11-18
- fix config file tag (#4)
- fix database migration path exists (#7)
## 1.0.0 - 2020-11-09
- initial release

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie bvba <info@spatie.be>
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.

1134
vendor/spatie/laravel-settings/README.md vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,50 @@
# Upgrading
Because there are many breaking changes an upgrade is not that easy. There are many edge cases this guide does not cover. We accept PRs to improve this guide.
## From v2 to v3
This should be a quick update:
- When creating a new project, the default search location for settings classes will be in the `app_path('Settings')` directory. If you want to keep the old location, then you can set the `auto_discover_settings` option to `app_path()`. For applications which already have published their config, nothing changes.
- If you're implementing custom repositories, then update them according to the interface. The method `updatePropertyPayload` is renamed to `updatePropertiesPayload` and should now update multiple properties at once.
- Add a new migration with the following content
```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('settings', function (Blueprint $table): void {
$table->boolean('locked')->default(false)->change();
$table->unique(['group', 'name']);
$table->dropIndex(['group']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('settings', function (Blueprint $table): void {
$table->boolean('locked')->default(null)->change();
$table->dropUnique(['group', 'name']);
$table->index('group');
});
}
};
```

View File

@@ -0,0 +1,75 @@
{
"name" : "spatie/laravel-settings",
"description" : "Store your application settings",
"keywords" : [
"spatie",
"laravel-settings"
],
"homepage" : "https://github.com/spatie/laravel-settings",
"license" : "MIT",
"authors" : [
{
"name" : "Ruben Van Assche",
"email" : "ruben@spatie.be",
"homepage" : "https://spatie.be",
"role" : "Developer"
}
],
"require" : {
"php" : "^7.4|^8.0",
"ext-json" : "*",
"illuminate/database" : "^8.73|^9.0|^10.0|^11.0",
"phpdocumentor/type-resolver" : "^1.5",
"spatie/temporary-directory" : "^1.3|^2.0"
},
"require-dev" : {
"ext-redis": "*",
"mockery/mockery": "^1.4",
"larastan/larastan": "^2.0",
"orchestra/testbench": "^6.23|^7.0|^8.0|^9.0",
"pestphp/pest": "^1.21|^2.0",
"pestphp/pest-plugin-laravel": "^1.2|^2.0",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan-deprecation-rules": "^1.0",
"phpstan/phpstan-phpunit": "^1.0",
"phpunit/phpunit": "^9.5|^10.0",
"spatie/laravel-data": "^1.0.0|^2.0.0|^4.0.0",
"spatie/pest-plugin-snapshots": "^1.1|^2.0",
"spatie/phpunit-snapshot-assertions": "^4.2|^5.0",
"spatie/ray": "^1.36"
},
"suggest" : {
"spatie/data-transfer-object" : "Allows for DTO casting to settings. (deprecated)"
},
"autoload" : {
"psr-4" : {
"Spatie\\LaravelSettings\\" : "src"
}
},
"autoload-dev" : {
"psr-4" : {
"Spatie\\LaravelSettings\\Tests\\" : "tests"
}
},
"scripts" : {
"analyse" : "vendor/bin/phpstan analyse",
"test" : "vendor/bin/pest",
"test-coverage" : "vendor/bin/pest --coverage"
},
"config" : {
"sort-packages" : true,
"allow-plugins" : {
"pestphp/pest-plugin" : true,
"phpstan/extension-installer" : true
}
},
"extra" : {
"laravel" : {
"providers" : [
"Spatie\\LaravelSettings\\LaravelSettingsServiceProvider"
]
}
},
"minimum-stability" : "dev",
"prefer-stable" : true
}

View File

@@ -0,0 +1,94 @@
<?php
return [
/*
* Each settings class used in your application must be registered, you can
* put them (manually) here.
*/
'settings' => [
],
/*
* The path where the settings classes will be created.
*/
'setting_class_path' => app_path('Settings'),
/*
* In these directories settings migrations will be stored and ran when migrating. A settings
* migration created via the make:settings-migration command will be stored in the first path or
* a custom defined path when running the command.
*/
'migrations_paths' => [
database_path('settings'),
],
/*
* When no repository was set for a settings class the following repository
* will be used for loading and saving settings.
*/
'default_repository' => 'database',
/*
* Settings will be stored and loaded from these repositories.
*/
'repositories' => [
'database' => [
'type' => Spatie\LaravelSettings\SettingsRepositories\DatabaseSettingsRepository::class,
'model' => null,
'table' => null,
'connection' => null,
],
'redis' => [
'type' => Spatie\LaravelSettings\SettingsRepositories\RedisSettingsRepository::class,
'connection' => null,
'prefix' => null,
],
],
/*
* The encoder and decoder will determine how settings are stored and
* retrieved in the database. By default, `json_encode` and `json_decode`
* are used.
*/
'encoder' => null,
'decoder' => null,
/*
* The contents of settings classes can be cached through your application,
* settings will be stored within a provided Laravel store and can have an
* additional prefix.
*/
'cache' => [
'enabled' => env('SETTINGS_CACHE_ENABLED', false),
'store' => null,
'prefix' => null,
'ttl' => null,
],
/*
* These global casts will be automatically used whenever a property within
* your settings class isn't a default PHP type.
*/
'global_casts' => [
DateTimeInterface::class => Spatie\LaravelSettings\SettingsCasts\DateTimeInterfaceCast::class,
DateTimeZone::class => Spatie\LaravelSettings\SettingsCasts\DateTimeZoneCast::class,
// Spatie\DataTransferObject\DataTransferObject::class => Spatie\LaravelSettings\SettingsCasts\DtoCast::class,
Spatie\LaravelData\Data::class => Spatie\LaravelSettings\SettingsCasts\DataCast::class,
],
/*
* The package will look for settings in these paths and automatically
* register them.
*/
'auto_discover_settings' => [
app_path('Settings'),
],
/*
* Automatically discovered settings classes can be cached, so they don't
* need to be searched each time the application boots up.
*/
'discovered_settings_cache_path' => base_path('bootstrap/cache'),
];

View File

@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::create('settings', function (Blueprint $table): void {
$table->id();
$table->string('group');
$table->string('name');
$table->boolean('locked')->default(false);
$table->json('payload');
$table->timestamps();
$table->unique(['group', 'name']);
});
}
};

View File

@@ -0,0 +1,36 @@
<?php
namespace Spatie\LaravelSettings\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Spatie\LaravelSettings\SettingsContainer;
class CacheDiscoveredSettingsCommand extends Command
{
protected $signature = 'settings:discover';
protected $description = 'Cache all auto discovered settings';
public function handle(SettingsContainer $container, Filesystem $files): void
{
$this->info('Caching registered settings...');
$container
->clearCache()
->getSettingClasses()
->pipe(function (Collection $settingClasses) use ($files) {
$cachePath = config('settings.discovered_settings_cache_path');
$files->makeDirectory($cachePath, 0755, true, true);
$files->put(
$cachePath . '/settings.php',
'<?php return ' . var_export($settingClasses->toArray(), true) . ';'
);
});
$this->info('All done!');
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Spatie\LaravelSettings\Console;
use Illuminate\Console\Command;
use Spatie\LaravelSettings\Support\SettingsCacheFactory;
class ClearCachedSettingsCommand extends Command
{
protected $signature = 'settings:clear-cache';
protected $description = 'Clear cached settings';
public function handle(SettingsCacheFactory $settingsCacheFactory): void
{
foreach ($settingsCacheFactory->all() as $settingsCache) {
$settingsCache->clear();
}
$this->info('Cached settings cleared!');
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Spatie\LaravelSettings\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class ClearDiscoveredSettingsCacheCommand extends Command
{
protected $signature = 'settings:clear-discovered';
protected $description = 'Clear cached auto discovered registered settings classes';
public function handle(Filesystem $files): void
{
$files->delete(config('settings.discovered_settings_cache_path') . '/settings.php');
$this->info('Cached discovered settings cleared!');
}
}

View File

@@ -0,0 +1,134 @@
<?php
namespace Spatie\LaravelSettings\Console;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use InvalidArgumentException;
class MakeSettingCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:setting {name : The name of the setting class} {--group=default : The group name} {--path= : Path to write the setting class file to}';
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:setting';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Settings Class';
/**
* @var Filesystem
*/
protected Filesystem $files;
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
public function handle()
{
$name = trim($this->input->getArgument('name'));
$group = trim($this->input->getOption('group'));
$path = trim($this->input->getOption('path'));
if (empty($path)) {
$path = $this->resolveSettingsPath();
}
$this->ensureSettingClassDoesntAlreadyExist($name, $path);
$this->files->ensureDirectoryExists($path);
$this->files->put(
$this->getPath($name, $path),
$this->getContent($name, $group, $path)
);
}
protected function getStub(): string
{
return <<<EOT
<?php
namespace {{ namespace }};
use Spatie\LaravelSettings\Settings;
class {{ class }} extends Settings
{
public static function group(): string
{
return '{{ group }}';
}
}
EOT;
}
protected function getContent($name, $group, $path)
{
return str_replace(
['{{ namespace }}', '{{ class }}', '{{ group }}'],
[$this->getNamespace($path), $name, $group],
$this->getStub()
);
}
protected function ensureSettingClassDoesntAlreadyExist($name, $path): void
{
if ($this->files->exists($this->getPath($name, $path))) {
throw new InvalidArgumentException(sprintf('%s already exists!', $name));
}
}
protected function resolveSettingsPath(): string
{
return config('settings.setting_class_path', app_path('Settings'));
}
protected function getPath($name, $path): string
{
return $path . '/' . $name . '.php';
}
protected function getNamespace($path): string
{
$path = preg_replace(
[
'/^(' . preg_quote(base_path(), '/') . ')/',
'/\//',
],
[
'',
'\\',
],
$path
);
$namespace = implode('\\', array_map(fn ($directory) => ucfirst($directory), explode('\\', $path)));
// Remove leading backslash if present
if (substr($namespace, 0, 1) === '\\') {
$namespace = substr($namespace, 1);
}
return $namespace;
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace Spatie\LaravelSettings\Console;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use InvalidArgumentException;
class MakeSettingsMigrationCommand extends Command
{
protected $signature = 'make:settings-migration {name : The name of the migration} {path? : Path to write migration file to}';
protected $description = 'Create a new settings migration file';
protected Filesystem $files;
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
public function handle(): void
{
$name = trim($this->input->getArgument('name'));
$path = trim($this->input->getArgument('path'));
// If path is still empty we get the first path from new settings.migrations_paths config
if (empty($path)) {
$path = $this->resolveMigrationPaths()[0];
}
$this->ensureMigrationDoesntAlreadyExist($name, $path);
$this->files->ensureDirectoryExists($path);
$this->files->put(
$file = $this->getPath($name, $path),
$this->getStub()
);
$this->info(sprintf('Setting migration [%s] created successfully.', $file));
}
protected function getStub(): string
{
return <<<EOT
<?php
use Spatie\LaravelSettings\Migrations\SettingsMigration;
return new class extends SettingsMigration
{
public function up(): void
{
}
};
EOT;
}
protected function ensureMigrationDoesntAlreadyExist($name, $migrationPath = null): void
{
if (! empty($migrationPath)) {
$migrationFiles = $this->files->glob($migrationPath . '/*.php');
foreach ($migrationFiles as $migrationFile) {
$this->files->requireOnce($migrationFile);
}
}
if (class_exists($className = Str::studly($name))) {
throw new InvalidArgumentException("A {$className} class already exists.");
}
}
protected function getPath($name, $path): string
{
return $path . '/' . Carbon::now()->format('Y_m_d_His') . '_' . Str::snake($name) . '.php';
}
protected function resolveMigrationPaths(): array
{
return ! empty(config('settings.migrations_path'))
? [config('settings.migrations_path')]
: config('settings.migrations_paths');
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Spatie\LaravelSettings\Events;
use Illuminate\Support\Collection;
class LoadingSettings
{
public string $settingsClass;
public Collection $properties;
public function __construct(string $settingsClass, Collection $properties)
{
$this->settingsClass = $settingsClass;
$this->properties = $properties;
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Spatie\LaravelSettings\Events;
use Illuminate\Support\Collection;
use Spatie\LaravelSettings\Settings;
class SavingSettings
{
public Settings $settings;
public Collection $properties;
public ?Collection $originalValues;
public function __construct(
Collection $properties,
?Collection $originalValues,
Settings $settings
) {
$this->properties = $properties;
$this->originalValues = $originalValues;
$this->settings = $settings;
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Spatie\LaravelSettings\Events;
use Spatie\LaravelSettings\Settings;
class SettingsLoaded
{
public Settings $settings;
public function __construct(Settings $settings)
{
$this->settings = $settings;
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Spatie\LaravelSettings\Events;
use Spatie\LaravelSettings\Settings;
class SettingsSaved
{
public Settings $settings;
public function __construct(Settings $settings)
{
$this->settings = $settings;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
use ReflectionProperty;
class CouldNotResolveDocblockType extends Exception
{
public static function create(
string $type,
ReflectionProperty $reflectionProperty
): self {
return new self("Could not resolve type in docblock: `{$type}` of property `{$reflectionProperty->getDeclaringClass()->getName()}::{$reflectionProperty->getName()}`");
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
class CouldNotUnserializeSettings extends Exception
{
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
class InvalidSettingName extends Exception
{
public static function create(string $property): self
{
return new self("Setting {$property} is invalid, it should be formatted as such: group.name");
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
class MissingSettings extends Exception
{
public static function create(string $settingsClass, array $missingProperties, string $operation): self
{
$missing = implode(', ', $missingProperties);
return new self("Tried {$operation} settings '{$settingsClass}', and following properties were missing: {$missing}");
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
class SettingAlreadyExists extends Exception
{
public static function whenAdding(string $property): self
{
throw new self("Could not create setting {$property} because it already exists");
}
public static function whenRenaming(string $from, string $to): self
{
return new self("Could not rename setting {$from} to {$to} because it already exists");
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
class SettingDoesNotExist extends Exception
{
public static function whenDeleting(string $property): self
{
return new self("Could not delete setting {$property} because it does not exist");
}
public static function whenEditing(string $property): self
{
return new self("Could not edit setting {$property} because it does not exist");
}
public static function whenRenaming(string $from, string $to): self
{
return new self("Could not rename setting {$from} to {$to} because it does not exist");
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\LaravelSettings\Exceptions;
use Exception;
class SettingsCacheDisabled extends Exception
{
public static function create(): self
{
return new self('Settings cache is not enabled');
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace Spatie\LaravelSettings\Factories;
use Illuminate\Support\Str;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\AbstractList;
use phpDocumentor\Reflection\Types\Boolean;
use phpDocumentor\Reflection\Types\Float_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Nullable;
use phpDocumentor\Reflection\Types\Object_;
use phpDocumentor\Reflection\Types\String_;
use ReflectionProperty;
use Spatie\LaravelSettings\SettingsCasts\ArraySettingsCast;
use Spatie\LaravelSettings\SettingsCasts\EnumCast;
use Spatie\LaravelSettings\SettingsCasts\SettingsCast;
use Spatie\LaravelSettings\Support\PropertyReflector;
class SettingsCastFactory
{
public static function resolve(
ReflectionProperty $reflectionProperty,
array $localCasts
): ?SettingsCast {
$name = $reflectionProperty->getName();
$reflectedType = PropertyReflector::resolveType($reflectionProperty);
if (array_key_exists($name, $localCasts)) {
return self::createLocalCast($localCasts[$name], $reflectedType);
}
if ($reflectedType === null) {
return null;
}
return self::createDefaultCast($reflectedType);
}
/**
* @param string|SettingsCast $castDefinition
* @param \phpDocumentor\Reflection\Type|null $type
*
* @return \Spatie\LaravelSettings\SettingsCasts\SettingsCast
*/
protected static function createLocalCast(
$castDefinition,
?Type $type
): SettingsCast {
if ($castDefinition instanceof SettingsCast) {
return $castDefinition;
}
$castClass = Str::before($castDefinition, ':');
$arguments = Str::contains($castDefinition, ':')
? explode(',', Str::after($castDefinition, ':'))
: [];
$reflectedType = self::getLocalCastReflectedType($type);
if ($reflectedType) {
array_push($arguments, $reflectedType);
}
return new $castClass(...$arguments);
}
protected static function createDefaultCast(
Type $type
): ?SettingsCast {
$noCastRequired = self::isTypeWithNoCastRequired($type)
|| ($type instanceof AbstractList && self::isTypeWithNoCastRequired($type->getValueType()))
|| ($type instanceof Nullable && self::isTypeWithNoCastRequired($type->getActualType()));
if ($noCastRequired) {
return null;
}
if ($type instanceof AbstractList) {
return new ArraySettingsCast(self::createDefaultCast($type->getValueType()));
}
if ($type instanceof Nullable) {
return self::createDefaultCast($type->getActualType());
}
if (! $type instanceof Object_) {
return null;
}
$className = self::getObjectClassName($type);
if (enum_exists($className)) {
return new EnumCast($className);
}
foreach (config('settings.global_casts', []) as $base => $cast) {
if (self::shouldCast($className, $base)) {
return new $cast($className);
}
}
return null;
}
protected static function isTypeWithNoCastRequired(Type $type): bool
{
return $type instanceof Integer
|| $type instanceof Boolean
|| $type instanceof Float_
|| $type instanceof String_;
}
protected static function shouldCast(string $type, string $base): bool
{
return $type === $base
|| in_array($type, class_implements($base))
|| is_subclass_of($type, $base);
}
protected static function getLocalCastReflectedType(?Type $type): ?string
{
if ($type instanceof Object_) {
return self::getObjectClassName($type);
}
if ($type instanceof Nullable) {
return self::getLocalCastReflectedType($type->getActualType());
}
return null;
}
protected static function getObjectClassName(Object_ $type): string
{
return ltrim((string ) $type->getFqsen(), '\\');
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Spatie\LaravelSettings\Factories;
use Exception;
use Spatie\LaravelSettings\SettingsRepositories\SettingsRepository;
class SettingsRepositoryFactory
{
public static function create(?string $name = null): SettingsRepository
{
$name ??= config('settings.default_repository');
if (! array_key_exists($name, config('settings.repositories'))) {
throw new Exception("Tried to create unknown settings repository: {$name}");
}
$config = config("settings.repositories.{$name}");
return app($config['type'], [
'config' => $config,
]);
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace Spatie\LaravelSettings;
use Illuminate\Database\Events\SchemaLoaded;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Spatie\LaravelSettings\Console\CacheDiscoveredSettingsCommand;
use Spatie\LaravelSettings\Console\ClearCachedSettingsCommand;
use Spatie\LaravelSettings\Console\ClearDiscoveredSettingsCacheCommand;
use Spatie\LaravelSettings\Console\MakeSettingCommand;
use Spatie\LaravelSettings\Console\MakeSettingsMigrationCommand;
use Spatie\LaravelSettings\Factories\SettingsRepositoryFactory;
use Spatie\LaravelSettings\Migrations\SettingsMigration;
use Spatie\LaravelSettings\SettingsRepositories\SettingsRepository;
use Spatie\LaravelSettings\Support\SettingsCacheFactory;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
class LaravelSettingsServiceProvider extends ServiceProvider
{
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../config/settings.php' => config_path('settings.php'),
], 'config');
if (! class_exists('CreateSettingsTable')) {
$this->publishes([
__DIR__ . '/../database/migrations/create_settings_table.php.stub' => database_path('migrations/2022_12_14_083707_create_settings_table.php'),
], 'migrations');
}
$this->commands([
MakeSettingCommand::class,
MakeSettingsMigrationCommand::class,
CacheDiscoveredSettingsCommand::class,
ClearDiscoveredSettingsCacheCommand::class,
ClearCachedSettingsCommand::class,
]);
}
Event::subscribe(SettingsEventSubscriber::class);
Event::listen(SchemaLoaded::class, fn ($event) => $this->removeMigrationsWhenSchemaLoaded($event));
$this->loadMigrationsFrom($this->resolveMigrationPaths());
}
public function register(): void
{
$this->mergeConfigFrom(__DIR__ . '/../config/settings.php', 'settings');
$this->app->bind(SettingsRepository::class, fn () => SettingsRepositoryFactory::create());
$this->app->bind(SettingsCacheFactory::class, fn () => new SettingsCacheFactory(
config('settings'),
));
$this->app->scoped(SettingsMapper::class);
$settingsContainer = app(SettingsContainer::class);
$settingsContainer->registerBindings();
}
private function removeMigrationsWhenSchemaLoaded(SchemaLoaded $event)
{
$files = Finder::create()
->files()
->ignoreDotFiles(true)
->in($this->resolveMigrationPaths())
->depth(0);
$migrations = collect(iterator_to_array($files))
->map(function (SplFileInfo $file) {
$contents = file_get_contents($file->getRealPath());
if (
str_contains($contents, 'return new class extends '.SettingsMigration::class)
|| str_contains($contents, 'return new class extends SettingsMigration')
) {
return $file->getBasename('.php');
}
preg_match('/class\s*(?P<className>\w*)\s*extends/', $contents, $found);
if (empty($found['className'])) {
return null;
}
require_once $file->getRealPath();
if (! is_subclass_of($found['className'], SettingsMigration::class)) {
return null;
}
return $file->getBasename('.php');
})
->filter()
->values();
$migrationsConfig = config()->get('database.migrations');
$migrationsTable = is_array($migrationsConfig) ? ($migrationsConfig['table'] ?? null) : $migrationsConfig;
$event->connection
->table($migrationsTable)
->useWritePdo()
->whereIn('migration', $migrations)
->delete();
}
protected function resolveMigrationPaths(): array
{
return ! empty(config('settings.migrations_path'))
? [config('settings.migrations_path')]
: config('settings.migrations_paths');
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Spatie\LaravelSettings\Migrations;
use Closure;
class SettingsBlueprint
{
protected string $group;
protected SettingsMigrator $migrator;
public function __construct(string $group, SettingsMigrator $migrator)
{
$this->group = $group;
$this->migrator = $migrator;
}
public function rename(string $from, string $to): void
{
$this->migrator->rename(
$this->prependWithGroup($from),
$this->prependWithGroup($to)
);
}
public function add(string $name, $value = null, bool $encrypted = false): void
{
$this->migrator->add($this->prependWithGroup($name), $value, $encrypted);
}
public function delete(string $name): void
{
$this->migrator->delete($this->prependWithGroup($name));
}
public function update(string $name, Closure $closure, bool $encrypted = false): void
{
$this->migrator->update($this->prependWithGroup($name), $closure, $encrypted);
}
public function addEncrypted(string $name, $value = null): void
{
$this->migrator->addEncrypted($this->prependWithGroup($name), $value);
}
public function updateEncrypted(string $name, Closure $closure): void
{
$this->migrator->updateEncrypted($this->prependWithGroup($name), $closure);
}
public function encrypt(string $name): void
{
$this->migrator->encrypt($this->prependWithGroup($name));
}
public function decrypt(string $name): void
{
$this->migrator->decrypt($this->prependWithGroup($name));
}
protected function prependWithGroup(string $name): string
{
return "{$this->group}.{$name}";
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Spatie\LaravelSettings\Migrations;
use Illuminate\Database\Migrations\Migration;
abstract class SettingsMigration extends Migration
{
protected SettingsMigrator $migrator;
abstract public function up();
public function __construct()
{
$this->migrator = app(SettingsMigrator::class);
}
}

View File

@@ -0,0 +1,191 @@
<?php
namespace Spatie\LaravelSettings\Migrations;
use Closure;
use Illuminate\Support\Collection;
use Spatie\LaravelSettings\Exceptions\InvalidSettingName;
use Spatie\LaravelSettings\Exceptions\SettingAlreadyExists;
use Spatie\LaravelSettings\Exceptions\SettingDoesNotExist;
use Spatie\LaravelSettings\Factories\SettingsRepositoryFactory;
use Spatie\LaravelSettings\SettingsCasts\SettingsCast;
use Spatie\LaravelSettings\SettingsConfig;
use Spatie\LaravelSettings\SettingsContainer;
use Spatie\LaravelSettings\SettingsRepositories\SettingsRepository;
use Spatie\LaravelSettings\Support\Crypto;
class SettingsMigrator
{
protected SettingsRepository $repository;
public function __construct(SettingsRepository $connection)
{
$this->repository = $connection;
}
public function repository(string $name): self
{
$this->repository = SettingsRepositoryFactory::create($name);
return $this;
}
public function rename(string $from, string $to): void
{
if (! $this->checkIfPropertyExists($from)) {
throw SettingDoesNotExist::whenRenaming($from, $to);
}
if ($this->checkIfPropertyExists($to)) {
throw SettingAlreadyExists::whenRenaming($from, $to);
}
$this->createProperty(
$to,
$this->getPropertyPayload($from)
);
$this->deleteProperty($from);
}
public function add(string $property, $value = null, bool $encrypted = false): void
{
if ($this->checkIfPropertyExists($property)) {
throw SettingAlreadyExists::whenAdding($property);
}
if ($encrypted) {
$value = Crypto::encrypt($value);
}
$this->createProperty($property, $value);
}
public function delete(string $property): void
{
if (! $this->checkIfPropertyExists($property)) {
throw SettingDoesNotExist::whenDeleting($property);
}
$this->deleteProperty($property);
}
public function deleteIfExists(string $property): void
{
if ($this->checkIfPropertyExists($property)) {
$this->deleteProperty($property);
}
}
public function update(string $property, Closure $closure, bool $encrypted = false): void
{
if (! $this->checkIfPropertyExists($property)) {
throw SettingDoesNotExist::whenEditing($property);
}
$originalPayload = $encrypted
? Crypto::decrypt($this->getPropertyPayload($property))
: $this->getPropertyPayload($property);
$updatedPayload = $encrypted
? Crypto::encrypt($closure($originalPayload))
: $closure($originalPayload);
$this->updatePropertyPayload($property, $updatedPayload);
}
public function addEncrypted(string $property, $value = null): void
{
$this->add($property, $value, true);
}
public function updateEncrypted(string $property, Closure $closure): void
{
$this->update($property, $closure, true);
}
public function encrypt(string $property): void
{
$this->update($property, fn ($payload) => Crypto::encrypt($payload));
}
public function decrypt(string $property): void
{
$this->update($property, fn ($payload) => Crypto::decrypt($payload));
}
public function inGroup(string $group, Closure $closure): void
{
$closure(new SettingsBlueprint($group, $this));
}
protected function getPropertyParts(string $property): array
{
$propertyParts = explode('.', $property);
if (count($propertyParts) !== 2) {
throw InvalidSettingName::create($property);
}
return ['group' => $propertyParts[0], 'name' => $propertyParts[1]];
}
protected function checkIfPropertyExists(string $property): bool
{
['group' => $group, 'name' => $name] = $this->getPropertyParts($property);
return $this->repository->checkIfPropertyExists($group, $name);
}
protected function getPropertyPayload(string $property)
{
['group' => $group, 'name' => $name] = $this->getPropertyParts($property);
$payload = $this->repository->getPropertyPayload($group, $name);
return optional($this->getCast($group, $name))->get($payload) ?: $payload;
}
protected function createProperty(string $property, $payload): void
{
['group' => $group, 'name' => $name] = $this->getPropertyParts($property);
if (is_object($payload)) {
$payload = optional($this->getCast($group, $name))->set($payload) ?: $payload;
}
$this->repository->createProperty($group, $name, $payload);
}
protected function updatePropertyPayload(string $property, $payload): void
{
['group' => $group, 'name' => $name] = $this->getPropertyParts($property);
if (is_object($payload)) {
$payload = optional($this->getCast($group, $name))->set($payload) ?: $payload;
}
$this->repository->updatePropertiesPayload($group, [$name => $payload]);
}
protected function deleteProperty(string $property): void
{
['group' => $group, 'name' => $name] = $this->getPropertyParts($property);
$this->repository->deleteProperty($group, $name);
}
protected function getCast(string $group, string $name): ?SettingsCast
{
return optional($this->settingsGroups()->get($group))->getCast($name);
}
protected function settingsGroups(): Collection
{
return app(SettingsContainer::class)
->getSettingClasses()
->mapWithKeys(fn (string $settingsClass) => [
$settingsClass::group() => new SettingsConfig($settingsClass),
]);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Spatie\LaravelSettings\Models;
use Illuminate\Database\Eloquent\Model;
class SettingsProperty extends Model
{
protected $table = 'settings';
protected $guarded = [];
protected $casts = [
'locked' => 'boolean',
];
public static function get(string $property)
{
[$group, $name] = explode('.', $property);
$setting = self::query()
->where('group', $group)
->where('name', $name)
->first('payload');
return json_decode($setting->getAttribute('payload'));
}
}

View File

@@ -0,0 +1,301 @@
<?php
namespace Spatie\LaravelSettings;
use Exception;
use Illuminate\Container\Container;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Support\Collection;
use ReflectionProperty;
use Spatie\LaravelSettings\Events\SavingSettings;
use Spatie\LaravelSettings\Events\SettingsLoaded;
use Spatie\LaravelSettings\Events\SettingsSaved;
use Spatie\LaravelSettings\Exceptions\MissingSettings;
use Spatie\LaravelSettings\SettingsRepositories\SettingsRepository;
use Spatie\LaravelSettings\Support\Crypto;
abstract class Settings implements Arrayable, Jsonable, Responsable
{
private SettingsMapper $mapper;
private SettingsConfig $config;
private bool $loaded = false;
private bool $configInitialized = false;
protected ?Collection $originalValues = null;
abstract public static function group(): string;
public static function repository(): ?string
{
return null;
}
public static function casts(): array
{
return [];
}
public static function encrypted(): array
{
return [];
}
/**
* @param array $values
*
* @return static
*/
public static function fake(array $values, bool $loadMissingValues = true): self
{
$settingsMapper = app(SettingsMapper::class);
$propertiesToLoad = $settingsMapper->initialize(static::class)
->getReflectedProperties()
->keys()
->reject(fn (string $name) => array_key_exists($name, $values));
if ($propertiesToLoad->isEmpty()) {
return app(Container::class)->instance(static::class, new static(
$values
));
}
if($propertiesToLoad->isNotEmpty() && $loadMissingValues === false) {
throw MissingSettings::create(static::class, $propertiesToLoad->toArray(), 'loading fake');
}
$mergedValues = $settingsMapper
->fetchProperties(static::class, $propertiesToLoad)
->merge($values)
->all();
return app(Container::class)->instance(static::class, new static(
$mergedValues
));
}
final public function __construct(array $values = [])
{
$this->ensureConfigIsLoaded();
foreach ($this->config->getReflectedProperties() as $name => $property) {
if (method_exists($property, 'isReadOnly') && $property->isReadOnly()) {
continue;
}
unset($this->{$name});
}
if (! empty($values)) {
$this->loadValues($values);
}
}
public function __get($name)
{
$this->loadValues();
return $this->{$name};
}
public function __set($name, $value)
{
$this->loadValues();
$this->{$name} = $value;
}
public function __debugInfo(): array
{
try {
$this->loadValues();
return $this->toArray();
} catch (Exception $exception) {
return [
'Could not load values',
];
}
}
public function __isset($name)
{
$this->loadValues();
return isset($this->{$name});
}
public function __serialize(): array
{
/** @var Collection $encrypted */
/** @var Collection $nonEncrypted */
[$encrypted, $nonEncrypted] = $this->toCollection()->partition(
fn ($value, string $name) => $this->config->isEncrypted($name)
);
return array_merge(
$encrypted->map(fn ($value) => Crypto::encrypt($value))->all(),
$nonEncrypted->all()
);
}
public function __unserialize(array $data): void
{
$this->loaded = false;
$this->ensureConfigIsLoaded();
/** @var Collection $encrypted */
/** @var Collection $nonEncrypted */
[$encrypted, $nonEncrypted] = collect($data)->partition(
fn ($value, string $name) => $this->config->isEncrypted($name)
);
$data = array_merge(
$encrypted->map(fn ($value) => Crypto::decrypt($value))->all(),
$nonEncrypted->all()
);
$this->loadValues($data);
}
/**
* @param \Illuminate\Support\Collection|array $properties
*
* @return $this
*/
public function fill($properties): self
{
foreach ($properties as $name => $payload) {
$this->{$name} = $payload;
}
return $this;
}
public function save(): self
{
$properties = $this->toCollection();
event(new SavingSettings($properties, $this->originalValues, $this));
$values = $this->mapper->save(static::class, $properties);
$this->fill($values);
$this->originalValues = $values;
event(new SettingsSaved($this));
return $this;
}
public function lock(string ...$properties)
{
$this->ensureConfigIsLoaded();
$this->config->lock(...$properties);
}
public function unlock(string ...$properties)
{
$this->ensureConfigIsLoaded();
$this->config->unlock(...$properties);
}
public function isLocked(string $property): bool
{
return in_array($property, $this->getLockedProperties());
}
public function isUnlocked(string $property): bool
{
return ! $this->isLocked($property);
}
public function getLockedProperties(): array
{
$this->ensureConfigIsLoaded();
return $this->config->getLocked()->toArray();
}
public function toCollection(): Collection
{
$this->ensureConfigIsLoaded();
return $this->config
->getReflectedProperties()
->mapWithKeys(fn (ReflectionProperty $property) => [
$property->getName() => $this->{$property->getName()},
]);
}
public function toArray(): array
{
return $this->toCollection()->toArray();
}
public function toJson($options = 0): string
{
return json_encode($this->toArray(), $options);
}
public function toResponse($request)
{
return response()->json($this->toJson());
}
public function getRepository(): SettingsRepository
{
$this->ensureConfigIsLoaded();
return $this->config->getRepository();
}
public function refresh(): self
{
$this->config->clearCachedLockedProperties();
$this->loaded = false;
$this->loadValues();
return $this;
}
private function loadValues(?array $values = null): self
{
if ($this->loaded) {
return $this;
}
$values ??= $this->mapper->load(static::class);
$this->loaded = true;
$this->fill($values);
$this->originalValues = collect($values);
event(new SettingsLoaded($this));
return $this;
}
private function ensureConfigIsLoaded(): self
{
if ($this->configInitialized) {
return $this;
}
$this->mapper = app(SettingsMapper::class);
$this->config = $this->mapper->initialize(static::class);
$this->configInitialized = true;
return $this;
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Spatie\LaravelSettings;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Spatie\LaravelSettings\Exceptions\CouldNotUnserializeSettings;
use Spatie\LaravelSettings\Exceptions\SettingsCacheDisabled;
class SettingsCache
{
private bool $enabled;
private ?string $store;
private ?string $prefix;
/** @var \DateTimeInterface|\DateInterval|int|null */
private $ttl;
public function __construct(
bool $enabled,
?string $store,
?string $prefix,
$ttl = null
) {
$this->enabled = $enabled;
$this->store = $store;
$this->prefix = $prefix;
$this->ttl = $ttl;
}
public function isEnabled(): bool
{
return $this->enabled;
}
public function has(string $settingsClass): bool
{
if ($this->enabled === false) {
return false;
}
return Cache::store($this->store)->has($this->resolveCacheKey($settingsClass));
}
public function get(string $settingsClass): Settings
{
if ($this->enabled === false) {
throw SettingsCacheDisabled::create();
}
$serialized = Cache::store($this->store)->get($this->resolveCacheKey($settingsClass));
$settings = unserialize($serialized);
if (! $settings instanceof Settings) {
throw new CouldNotUnserializeSettings();
}
return $settings;
}
public function put(Settings $settings): void
{
if ($this->enabled === false) {
return;
}
$serialized = serialize($settings);
Cache::store($this->store)->put(
$this->resolveCacheKey(get_class($settings)),
$serialized,
$this->ttl
);
}
public function clear(): void
{
app(SettingsContainer::class)
->getSettingClasses()
->map(fn (string $class) => $this->resolveCacheKey($class))
->pipe(fn (Collection $keys) => Cache::store($this->store)->deleteMultiple($keys));
}
private function resolveCacheKey(string $settingsClass): string
{
$prefix = $this->prefix ? "{$this->prefix}." : '';
return "{$prefix}settings.{$settingsClass}";
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
class ArraySettingsCast implements SettingsCast
{
protected SettingsCast $cast;
public function __construct(SettingsCast $cast)
{
$this->cast = $cast;
}
public function getCast(): ?SettingsCast
{
return $this->cast;
}
public function get($payload): array
{
return array_map(
fn ($data) => $this->cast->get($data),
$payload
);
}
public function set($payload)
{
return array_map(
fn ($data) => $this->cast->set($data),
$payload
);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
use Illuminate\Support\Collection;
class CollectionCast implements SettingsCast
{
public function get($payload): Collection
{
return collect($payload);
}
public function set($payload): array
{
return $payload->toArray();
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
use Exception;
use Spatie\LaravelData\Data;
class DataCast implements SettingsCast
{
protected string $type;
public function __construct(?string $type)
{
$this->type = $this->ensureDataTypeExists($type);
}
public function get($payload): Data
{
return $this->type::from($payload);
}
/**
* @param Data $payload
*
* @return array
*/
public function set($payload): array
{
return $payload->toArray();
}
protected function ensureDataTypeExists(?string $type): string
{
if ($type === null) {
throw new Exception('Cannot create a data cast because no data class was given');
}
if (! class_exists($type)) {
throw new Exception("Cannot create a data cast for `{$type}` because the data does not exist");
}
return $type;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Exception;
class DateTimeInterfaceCast implements SettingsCast
{
protected string $type;
public function __construct(?string $type)
{
$this->type = $type ?? DateTime::class;
}
public function get($payload): ?DateTimeInterface
{
if ($payload === null) {
return null;
}
if ($this->type === Carbon::class) {
return new Carbon($payload);
}
if ($this->type === CarbonImmutable::class) {
return new CarbonImmutable($payload);
}
if ($this->type === DateTimeImmutable::class) {
return new DateTimeImmutable($payload);
}
if ($this->type === DateTime::class) {
return new DateTime($payload);
}
throw new Exception("Could not cast DateTime type `{$this->type}`");
}
/** @param DateTimeInterface|null $payload */
public function set($payload): ?string
{
return $payload !== null
? $payload->format(DATE_ATOM)
: null;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
use DateTimeZone;
class DateTimeZoneCast implements SettingsCast
{
protected string $type;
public function __construct(?string $type)
{
$this->type = $type ?? DateTimeZone::class;
}
public function get($payload): ?DateTimeZone
{
return $payload !== null
? new DateTimeZone($payload)
: null;
}
/**
* @param DateTimeZone|null $payload
*
* @return string
*/
public function set($payload): ?string
{
return $payload !== null
? $payload->getName()
: null;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
use Exception;
use Spatie\DataTransferObject\DataTransferObject;
/** @deprecated */
class DtoCast implements SettingsCast
{
protected string $type;
public function __construct(?string $type)
{
$this->type = $this->ensureDtoTypeExists($type);
}
public function get($payload): DataTransferObject
{
return new $this->type($payload);
}
/**
* @param \Spatie\DataTransferObject\DataTransferObject $payload
*
* @return array
*/
public function set($payload): array
{
return $payload->toArray();
}
protected function ensureDtoTypeExists(?string $type): string
{
if ($type === null) {
throw new Exception('Cannot create a DTO cast because no DTO class was given');
}
if (! class_exists($type)) {
throw new Exception("Cannot create a DTO cast for `{$type}` because the DTO does not exist");
}
return $type;
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
use BackedEnum;
use Exception;
use UnitEnum;
class EnumCast implements SettingsCast
{
private string $enum;
public function __construct(string $enum)
{
$this->enum = $enum;
}
public function get($payload): ?UnitEnum
{
if($payload === null) {
return null;
}
if (is_a($this->enum, BackedEnum::class, true)) {
return $this->enum::from($payload);
}
if (is_a($this->enum, UnitEnum::class, true)) {
foreach ($this->enum::cases() as $enum) {
if ($enum->name === $payload) {
return $enum;
}
}
}
throw new Exception('Invalid enum');
}
public function set($payload): string|int|null
{
if($payload === null) {
return null;
}
if ($payload instanceof BackedEnum) {
return $payload->value;
}
if ($payload instanceof UnitEnum) {
return $payload->name;
}
throw new Exception('Invalid enum');
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Spatie\LaravelSettings\SettingsCasts;
interface SettingsCast
{
/**
* Will be used to when retrieving a value from the repository, and
* inserting it into the settings class.
*/
public function get($payload);
/**
* Will be used to when retrieving a value from the settings class, and
* inserting it into the repository.
*/
public function set($payload);
}

View File

@@ -0,0 +1,132 @@
<?php
namespace Spatie\LaravelSettings;
use Exception;
use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionProperty;
use Spatie\LaravelSettings\Factories\SettingsCastFactory;
use Spatie\LaravelSettings\Factories\SettingsRepositoryFactory;
use Spatie\LaravelSettings\SettingsCasts\SettingsCast;
use Spatie\LaravelSettings\SettingsRepositories\SettingsRepository;
class SettingsConfig
{
/** @var class-string<\Spatie\LaravelSettings\Settings> */
private string $settingsClass;
/** @var Collection<string, ?\Spatie\LaravelSettings\SettingsCasts\SettingsCast> */
private Collection $casts;
/** @var Collection<string, \ReflectionProperty> */
private Collection $reflectionProperties;
/** @var string[]|\Illuminate\Support\Collection */
private Collection $encrypted;
/** @var string[]|\Illuminate\Support\Collection */
private Collection $locked;
private SettingsRepository $repository;
public function __construct(string $settingsClass)
{
if (! is_subclass_of($settingsClass, Settings::class)) {
throw new Exception("Tried decorating {$settingsClass} which is not extending `Spatie\LaravelSettings\Settings::class`");
}
$this->settingsClass = $settingsClass;
$this->reflectionProperties = collect(
(new ReflectionClass($settingsClass))->getProperties(ReflectionProperty::IS_PUBLIC)
)->mapWithKeys(fn (ReflectionProperty $property) => [$property->getName() => $property]);
$this->casts = $this->reflectionProperties
->map(fn (ReflectionProperty $reflectionProperty) => SettingsCastFactory::resolve(
$reflectionProperty,
$this->settingsClass::casts()
));
$this->encrypted = collect($this->settingsClass::encrypted());
$this->repository = SettingsRepositoryFactory::create($this->settingsClass::repository());
}
public function getName(): string
{
return $this->settingsClass;
}
public function getReflectedProperties(): Collection
{
return $this->reflectionProperties;
}
public function getRepository(): SettingsRepository
{
return $this->repository;
}
public function getGroup(): string
{
return $this->settingsClass::group();
}
public function isEncrypted(string $name): bool
{
return $this->encrypted->contains($name);
}
public function isLocked(string $name): bool
{
return $this->getLocked()->contains($name);
}
public function getCast(string $name): ?SettingsCast
{
return $this->casts->get($name);
}
public function lock(string ...$names): self
{
$this->locked = $this->getLocked()->merge($names);
$this->repository->lockProperties(
$this->getGroup(),
$names
);
return $this;
}
public function unlock(string ...$names): self
{
$this->locked = $this->getLocked()->diff($names);
$this->repository->unlockProperties(
$this->getGroup(),
$names
);
return $this;
}
public function getLocked(): Collection
{
if (! empty($this->locked)) {
return $this->locked;
}
return $this->locked = collect(
$this->repository->getLockedProperties($this->settingsClass::group())
);
}
public function clearCachedLockedProperties(): self
{
unset($this->locked);
return $this;
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace Spatie\LaravelSettings;
use Illuminate\Container\Container;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Spatie\LaravelSettings\Exceptions\CouldNotUnserializeSettings;
use Spatie\LaravelSettings\Support\Composer;
use Spatie\LaravelSettings\Support\DiscoverSettings;
use Spatie\LaravelSettings\Support\SettingsCacheFactory;
class SettingsContainer
{
protected Container $container;
protected static ?Collection $settingsClasses = null;
public function __construct(Container $container)
{
$this->container = $container;
}
public function registerBindings(): void
{
$cacheFactory = $this->container->make(SettingsCacheFactory::class);
$this->getSettingClasses()->each(function (string $settingClass) use ($cacheFactory) {
$this->container->scoped($settingClass, function () use ($cacheFactory, $settingClass) {
$cache = $cacheFactory->build($settingClass::repository());
if ($cache->isEnabled() && $cache->has($settingClass)) {
try {
return $cache->get($settingClass);
} catch (CouldNotUnserializeSettings $exception) {
Log::error("Could not unserialize settings class: `{$settingClass}` from cache");
}
}
return new $settingClass();
});
});
}
public function getSettingClasses(): Collection
{
if (self::$settingsClasses !== null) {
return self::$settingsClasses;
}
$cachedDiscoveredSettings = config('settings.discovered_settings_cache_path') . '/settings.php';
if (file_exists($cachedDiscoveredSettings)) {
$classes = require $cachedDiscoveredSettings;
return self::$settingsClasses = collect($classes);
}
/** @var \Spatie\LaravelSettings\Settings[] $settings */
$settings = array_merge(
$this->discoverSettings(),
config('settings.settings', [])
);
return self::$settingsClasses = collect($settings)->unique();
}
public function clearCache(): self
{
self::$settingsClasses = null;
return $this;
}
protected function discoverSettings(): array
{
return (new DiscoverSettings())
->within(config('settings.auto_discover_settings', []))
->useBasePath(base_path())
->ignoringFiles(Composer::getAutoloadedFiles(base_path('composer.json')))
->discover();
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Spatie\LaravelSettings;
use Illuminate\Events\Dispatcher;
use Spatie\LaravelSettings\Events\SettingsLoaded;
use Spatie\LaravelSettings\Events\SettingsSaved;
use Spatie\LaravelSettings\Support\SettingsCacheFactory;
class SettingsEventSubscriber
{
private SettingsCacheFactory $settingsCacheFactory;
public function __construct(SettingsCacheFactory $settingsCacheFactory)
{
$this->settingsCacheFactory = $settingsCacheFactory;
}
public function subscribe(Dispatcher $dispatcher)
{
$dispatcher->listen(
SettingsSaved::class,
function (SettingsSaved $event) {
$cache = $this->settingsCacheFactory->build(
$event->settings::repository()
);
if ($cache->isEnabled()) {
$cache->put($event->settings);
}
}
);
$dispatcher->listen(
SettingsLoaded::class,
function (SettingsLoaded $event) {
$cache = $this->settingsCacheFactory->build(
$event->settings::repository()
);
if ($cache->has(get_class($event->settings))) {
return;
}
$cache->put($event->settings);
}
);
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Spatie\LaravelSettings;
use Illuminate\Support\Collection;
use Spatie\LaravelSettings\Events\LoadingSettings;
use Spatie\LaravelSettings\Exceptions\MissingSettings;
use Spatie\LaravelSettings\Support\Crypto;
class SettingsMapper
{
/** @var array<string, \Spatie\LaravelSettings\SettingsConfig> */
private array $configs = [];
public function initialize(string $settingsClass): SettingsConfig
{
if ($this->has($settingsClass)) {
return $this->configs[$settingsClass];
}
$config = new SettingsConfig($settingsClass);
return $this->configs[$settingsClass] = $config;
}
public function has(string $settingsClass): bool
{
return array_key_exists($settingsClass, $this->configs);
}
public function load(string $settingsClass): Collection
{
$config = $this->getConfig($settingsClass);
$properties = $this->fetchProperties(
$settingsClass,
$config->getReflectedProperties()->keys()
);
event(new LoadingSettings($settingsClass, $properties));
$this->ensureNoMissingSettings($config, $properties, 'loading');
return $properties;
}
public function save(
string $settingsClass,
Collection $properties
): Collection {
$config = $this->getConfig($settingsClass);
$this->ensureNoMissingSettings($config, $properties, 'saving');
$notRejectedProperties = $properties
->reject(fn ($payload, string $name) => $config->isLocked($name));
$changedProperties = $notRejectedProperties
->map(function ($payload, string $name) use ($config) {
if ($cast = $config->getCast($name)) {
$payload = $cast->set($payload);
}
if ($config->isEncrypted($name)) {
$payload = Crypto::encrypt($payload);
}
return $payload;
})
->toArray();
$config->getRepository()->updatePropertiesPayload(
$config->getGroup(),
$changedProperties
);
return $this
->fetchProperties($settingsClass, $config->getLocked())
->merge($notRejectedProperties);
}
public function fetchProperties(string $settingsClass, Collection $names): Collection
{
$config = $this->getConfig($settingsClass);
return collect($config->getRepository()->getPropertiesInGroup($config->getGroup()))
->filter(fn ($payload, string $name) => $names->contains($name))
->map(function ($payload, string $name) use ($config) {
if ($config->isEncrypted($name)) {
$payload = Crypto::decrypt($payload);
}
if ($cast = $config->getCast($name)) {
$payload = $cast->get($payload);
}
return $payload;
});
}
private function getConfig(string $settingsClass): SettingsConfig
{
if (! $this->has($settingsClass)) {
$this->initialize($settingsClass);
}
return $this->configs[$settingsClass];
}
private function ensureNoMissingSettings(
SettingsConfig $config,
Collection $properties,
string $operation
): void {
$missingSettings = $config
->getReflectedProperties()
->keys()
->diff($properties->keys())
->toArray();
if (! empty($missingSettings)) {
throw MissingSettings::create($config->getName(), $missingSettings, $operation);
}
}
}

View File

@@ -0,0 +1,147 @@
<?php
namespace Spatie\LaravelSettings\SettingsRepositories;
use Illuminate\Database\Eloquent\Builder;
use Spatie\LaravelSettings\Models\SettingsProperty;
class DatabaseSettingsRepository implements SettingsRepository
{
/** @var class-string<\Illuminate\Database\Eloquent\Model> */
protected string $propertyModel;
protected ?string $connection;
protected ?string $table;
public function __construct(array $config)
{
$this->propertyModel = $config['model'] ?? SettingsProperty::class;
$this->connection = $config['connection'] ?? null;
$this->table = $config['table'] ?? null;
}
public function getPropertiesInGroup(string $group): array
{
return $this->getBuilder()
->where('group', $group)
->get(['name', 'payload'])
->mapWithKeys(function (object $object) {
return [$object->name => $this->decode($object->payload, true)];
})
->toArray();
}
public function checkIfPropertyExists(string $group, string $name): bool
{
return $this->getBuilder()
->where('group', $group)
->where('name', $name)
->exists();
}
public function getPropertyPayload(string $group, string $name)
{
$setting = $this->getBuilder()
->where('group', $group)
->where('name', $name)
->first('payload')
->toArray();
return $this->decode($setting['payload']);
}
public function createProperty(string $group, string $name, $payload): void
{
$this->getBuilder()->create([
'group' => $group,
'name' => $name,
'payload' => $this->encode($payload),
'locked' => false,
]);
}
public function updatePropertiesPayload(string $group, array $properties): void
{
$propertiesInBatch = collect($properties)->map(function ($payload, $name) use ($group) {
return [
'group' => $group,
'name' => $name,
'payload' => $this->encode($payload),
];
})->values()->toArray();
$this->getBuilder()
->where('group', $group)
->upsert($propertiesInBatch, ['group', 'name'], ['payload']);
}
public function deleteProperty(string $group, string $name): void
{
$this->getBuilder()
->where('group', $group)
->where('name', $name)
->delete();
}
public function lockProperties(string $group, array $properties): void
{
$this->getBuilder()
->where('group', $group)
->whereIn('name', $properties)
->update(['locked' => true]);
}
public function unlockProperties(string $group, array $properties): void
{
$this->getBuilder()
->where('group', $group)
->whereIn('name', $properties)
->update(['locked' => false]);
}
public function getLockedProperties(string $group): array
{
return $this->getBuilder()
->where('group', $group)
->where('locked', true)
->pluck('name')
->toArray();
}
public function getBuilder(): Builder
{
$model = new $this->propertyModel;
if ($this->connection) {
$model->setConnection($this->connection);
}
if ($this->table) {
$model->setTable($this->table);
}
return $model->newQuery();
}
/**
* @param mixed $value
* @return mixed
*/
protected function encode($value)
{
$encoder = config('settings.encoder') ?? fn ($value) => json_encode($value);
return $encoder($value);
}
/**
* @return mixed
*/
protected function decode(string $payload, bool $associative = false)
{
$decoder = config('settings.decoder') ?? fn ($payload, $associative) => json_decode($payload, $associative);
return $decoder($payload, $associative);
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Spatie\LaravelSettings\SettingsRepositories;
use Illuminate\Redis\RedisManager;
class RedisSettingsRepository implements SettingsRepository
{
/** @var \Redis */
protected $connection;
protected string $prefix;
public function __construct(array $config, RedisManager $connection)
{
$this->connection = $connection
->connection($config['connection'] ?? null)
->client();
$this->prefix = array_key_exists('prefix', $config)
? "{$config['prefix']}."
: '';
}
public function getPropertiesInGroup(string $group): array
{
return collect($this->connection->hGetAll($this->prefix . $group))
->mapWithKeys(function ($payload, string $name) {
return [$name => json_decode($payload, true)];
})->toArray();
}
public function checkIfPropertyExists(string $group, string $name): bool
{
return $this->connection->hExists($this->prefix . $group, $name);
}
public function getPropertyPayload(string $group, string $name)
{
return json_decode($this->connection->hGet($this->prefix . $group, $name));
}
public function createProperty(string $group, string $name, $payload): void
{
$this->connection->hSet($this->prefix . $group, $name, json_encode($payload));
}
public function updatePropertiesPayload(string $group, array $properties): void
{
$properties = collect($properties)->mapWithKeys(function ($payload, $name) {
return [$name => json_encode($payload)];
})->toArray();
$this->connection->hmset($this->prefix . $group, $properties);
}
public function deleteProperty(string $group, string $name): void
{
$this->connection->hDel($this->prefix . $group, $name);
}
public function lockProperties(string $group, array $properties): void
{
$this->connection->sAdd($this->getLocksSetKey($group), ...$properties);
}
public function unlockProperties(string $group, array $properties): void
{
$this->connection->sRem($this->getLocksSetKey($group), ...$properties);
}
public function getLockedProperties(string $group): array
{
return $this->connection->sMembers($this->getLocksSetKey($group));
}
protected function getLocksSetKey(string $group): string
{
return $this->prefix . 'locks.' . $group;
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Spatie\LaravelSettings\SettingsRepositories;
interface SettingsRepository
{
/**
* Get all the properties in the repository for a single group
*/
public function getPropertiesInGroup(string $group): array;
/**
* Check if a property exists in a group
*/
public function checkIfPropertyExists(string $group, string $name): bool;
/**
* Get the payload of a property
*/
public function getPropertyPayload(string $group, string $name);
/**
* Create a property within a group with a payload
*/
public function createProperty(string $group, string $name, $payload): void;
/**
* Update the payloads of properties within a group.
*/
public function updatePropertiesPayload(string $group, array $properties): void;
/**
* Delete a property from a group
*/
public function deleteProperty(string $group, string $name): void;
/**
* Lock a set of properties for a specific group
*/
public function lockProperties(string $group, array $properties): void;
/**
* Unlock a set of properties for a group
*/
public function unlockProperties(string $group, array $properties): void;
/**
* Get all the locked properties within a group
*/
public function getLockedProperties(string $group): array;
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Spatie\LaravelSettings\Support;
use Illuminate\Support\Str;
class Composer
{
public static function getAutoloadedFiles($composerJsonPath): array
{
if (! file_exists($composerJsonPath)) {
return [];
}
$basePath = Str::before($composerJsonPath, 'composer.json');
$composerContents = json_decode(file_get_contents($composerJsonPath), true);
$paths = array_merge(
$composerContents['autoload']['files'] ?? [],
$composerContents['autoload-dev']['files'] ?? []
);
return array_map(fn (string $path) => realpath($basePath.$path), $paths);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Spatie\LaravelSettings\Support;
class Crypto
{
public static function encrypt($payload): ?string
{
return $payload !== null
? encrypt($payload)
: $payload;
}
public static function decrypt(?string $payload)
{
return $payload !== null
? decrypt($payload)
: null;
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace Spatie\LaravelSettings\Support;
use Illuminate\Support\Str;
use ReflectionClass;
use Spatie\LaravelSettings\Settings;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
use Throwable;
class DiscoverSettings
{
protected array $directories = [];
protected string $basePath = '';
protected string $rootNamespace = '';
protected array $ignoredFiles = [];
public function __construct()
{
$this->basePath = app_path();
}
public function within(array $directories): self
{
$this->directories = array_values(
array_filter($directories, fn (string $directory) => is_dir($directory))
);
return $this;
}
public function useBasePath(string $basePath): self
{
$this->basePath = $basePath;
return $this;
}
public function useRootNamespace(string $rootNamespace): self
{
$this->rootNamespace = $rootNamespace;
return $this;
}
public function ignoringFiles(array $ignoredFiles): self
{
$this->ignoredFiles = $ignoredFiles;
return $this;
}
public function discover(): array
{
if (empty($this->directories)) {
return [];
}
$files = (new Finder())->files()->in($this->directories);
return collect($files)
->reject(fn (SplFileInfo $file) => in_array($file->getPathname(), $this->ignoredFiles))
->map(fn (SplFileInfo $file) => $this->fullQualifiedClassNameFromFile($file))
->filter(function (string $settingsClass) {
try {
return is_subclass_of($settingsClass, Settings::class) &&
(new ReflectionClass($settingsClass))->isInstantiable();
} catch (Throwable $e) {
return false;
}
})
->flatten()
->toArray();
}
protected function fullQualifiedClassNameFromFile(SplFileInfo $file): string
{
$class = trim(Str::replaceFirst($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
$class = str_replace(
[DIRECTORY_SEPARATOR, 'App\\'],
['\\', app()->getNamespace()],
ucfirst(Str::replaceLast('.php', '', $class))
);
return $this->rootNamespace.$class;
}
}

View File

@@ -0,0 +1,138 @@
<?php
namespace Spatie\LaravelSettings\Support;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\FqsenResolver;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\TypeResolver;
use phpDocumentor\Reflection\Types\AbstractList;
use phpDocumentor\Reflection\Types\Boolean;
use phpDocumentor\Reflection\Types\Compound;
use phpDocumentor\Reflection\Types\ContextFactory;
use phpDocumentor\Reflection\Types\Float_;
use phpDocumentor\Reflection\Types\Integer;
use phpDocumentor\Reflection\Types\Null_;
use phpDocumentor\Reflection\Types\Nullable;
use phpDocumentor\Reflection\Types\Object_;
use phpDocumentor\Reflection\Types\String_;
use ReflectionNamedType;
use ReflectionProperty;
use Spatie\LaravelSettings\Exceptions\CouldNotResolveDocblockType;
class PropertyReflector
{
public static function resolveType(
ReflectionProperty $reflectionProperty
): ?Type {
$reflectionType = $reflectionProperty->getType();
$docblock = $reflectionProperty->getDocComment();
if ($reflectionType === null && empty($docblock)) {
return null;
}
if ($docblock) {
preg_match('/@var ((?:(?:[\w?|\\\\<>,\s])+(?:\[])?)+)/', $docblock, $output_array);
return count($output_array) === 2
? self::reflectDocblock($reflectionProperty, $output_array[1])
: null;
}
if (! $reflectionType instanceof ReflectionNamedType) {
return null;
}
$builtInTypes = [
'int',
'string',
'float',
'bool',
'mixed',
'array',
];
if (in_array($reflectionType->getName(), $builtInTypes)) {
return null;
}
$type = new Object_(new Fqsen('\\' . $reflectionType->getName()));
return $reflectionType->allowsNull()
? new Nullable($type)
: $type;
}
protected static function reflectDocblock(
ReflectionProperty $reflectionProperty,
string $type
): Type {
$resolvedType = (new TypeResolver())->resolve($type);
$isValidPrimitive = $resolvedType instanceof Boolean
|| $resolvedType instanceof Float_
|| $resolvedType instanceof Integer
|| $resolvedType instanceof String_;
if ($isValidPrimitive) {
return $resolvedType;
}
if ($resolvedType instanceof Object_) {
return self::reflectObject($reflectionProperty, $resolvedType);
}
if ($resolvedType instanceof Compound) {
return self::reflectCompound($reflectionProperty, $resolvedType);
}
if ($resolvedType instanceof Nullable) {
return new Nullable(self::reflectDocblock($reflectionProperty, (string) $resolvedType->getActualType()));
}
if ($resolvedType instanceof AbstractList) {
$listType = get_class($resolvedType);
return new $listType(
self::reflectDocblock($reflectionProperty, (string) $resolvedType->getValueType()),
$resolvedType->getKeyType()
);
}
throw CouldNotResolveDocblockType::create($type, $reflectionProperty);
}
private static function reflectCompound(
ReflectionProperty $reflectionProperty,
Compound $compound
): Nullable {
if ($compound->getIterator()->count() !== 2 || ! $compound->contains(new Null_())) {
throw CouldNotResolveDocblockType::create((string) $compound, $reflectionProperty);
}
$other = current(array_filter(
iterator_to_array($compound->getIterator()),
fn (Type $type) => ! $type instanceof Null_
));
return new Nullable(self::reflectDocblock($reflectionProperty, (string) $other));
}
private static function reflectObject(
ReflectionProperty $reflectionProperty,
Object_ $object
): Object_ {
if (class_exists((string) $object->getFqsen())) {
return $object;
}
$context = (new ContextFactory)->createFromReflector($reflectionProperty);
$className = ltrim((string) $object->getFqsen(), '\\');
$fqsen = (new FqsenResolver)->resolve($className, $context);
return new Object_($fqsen);
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Spatie\LaravelSettings\Support;
use Spatie\LaravelSettings\SettingsCache;
class SettingsCacheFactory
{
private array $config;
private SettingsCache $defaultCache;
private array $repositoryCaches = [];
public function __construct(array $settingsConfig)
{
$this->config = $settingsConfig;
$this->initializeCaches();
}
public function build(?string $repository = null): SettingsCache
{
if ($repository === null) {
return $this->defaultCache;
}
if (array_key_exists($repository, $this->repositoryCaches)) {
return $this->repositoryCaches[$repository];
}
return $this->defaultCache;
}
/** @return array<SettingsCache> */
public function all(): array
{
return array_merge(
['default' => $this->defaultCache],
$this->repositoryCaches
);
}
protected function initializeCaches(): void
{
$this->defaultCache = $this->initializeCache($this->config['cache']);
foreach ($this->config['repositories'] as $name => $repositoryConfig) {
if (array_key_exists('cache', $repositoryConfig)) {
$this->repositoryCaches[$name] = $this->initializeCache($repositoryConfig['cache']);
}
}
}
protected function initializeCache(array $config): SettingsCache
{
return new SettingsCache(
$config['enabled'] ?? false,
$config['store'] ?? null,
$config['prefix'] ?? null,
$config['ttl'] ?? null,
);
}
}