Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Custom key/context serializers #30

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions config/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,40 @@
|
*/
'team_foreign_key' => 'team_id',

/*
|--------------------------------------------------------------------------
| Context Serializer
|--------------------------------------------------------------------------
|
| The context serializer is responsible for converting a Context object
| into a string, which gets appended to a setting key in the database.
|
| Any custom serializer you use must implement the
| \Rawilk\Settings\Contracts\ContextSerializer interface.
|
| Supported:
| - \Rawilk\Settings\Support\ContextSerializers\ContextSerializer (default)
| - \Rawilk\Settings\Support\ContextSerializers\DotNotationContextSerializer
|
*/
'context_serializer' => \Rawilk\Settings\Support\ContextSerializers\ContextSerializer::class,

/*
|--------------------------------------------------------------------------
| Key Generator
|--------------------------------------------------------------------------
|
| The key generator is responsible for generating a suitable key for a
| setting.
|
| Any custom key generator you use must implement the
| \Rawilk\Settings\Contracts\KeyGenerator interface.
|
| Supported:
| - \Rawilk\Settings\Support\KeyGenerators\ReadableKeyGenerator
| - \Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator (default)
|
*/
'key_generator' => \Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator::class,
];
2 changes: 1 addition & 1 deletion docs/best-practices/performance-tips.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ You are free to turn caching off, but you might notice a performance hit on larg
on apps that are retrieving many settings on each page load.

As always, if you choose to bypass the provided methods for setting and removing settings, you will need to flush the cache manually for
each setting you manipulate manually. To determine the cache key for a setting key, you should use the `Rawilk\Settings\Support\KeyGenerator` to
each setting you manipulate manually. To determine the cache key for a setting key, you should use the `Rawilk\Settings\Support\KeyGenerators\KeyGenerator` to
generate the md5 version of the setting's key:

```php
Expand Down
12 changes: 12 additions & 0 deletions src/Contracts/ContextSerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Contracts;

use Rawilk\Settings\Support\Context;

interface ContextSerializer
{
public function serialize(Context $context = null): string;
}
14 changes: 14 additions & 0 deletions src/Contracts/KeyGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Contracts;

use Rawilk\Settings\Support\Context;

interface KeyGenerator
{
public function generate(string $key, Context $context = null): string;

public function setContextSerializer(ContextSerializer $serializer): self;
}
15 changes: 15 additions & 0 deletions src/Exceptions/InvalidContextValue.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Exceptions;

use Exception;

final class InvalidContextValue extends Exception
{
public static function forKey(string $key): self
{
return new self("An invalid context value was provided for key: {$key}. Only string, integer, and boolean values are allowed.");
}
}
12 changes: 5 additions & 7 deletions src/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Rawilk\Settings\Contracts\Driver;
use Rawilk\Settings\Contracts\KeyGenerator;
use Rawilk\Settings\Support\Context;
use Rawilk\Settings\Support\ContextSerializer;
use Rawilk\Settings\Support\KeyGenerator;
use Rawilk\Settings\Support\ValueSerializer;

class Settings
Expand All @@ -25,8 +24,6 @@ class Settings

protected ?Encrypter $encrypter = null;

protected KeyGenerator $keyGenerator;

protected ValueSerializer $valueSerializer;

protected bool $cacheEnabled = false;
Expand All @@ -47,9 +44,10 @@ class Settings

protected string $cacheKeyPrefix = '';

public function __construct(protected Driver $driver)
{
$this->keyGenerator = new KeyGenerator(new ContextSerializer);
public function __construct(
protected Driver $driver,
protected KeyGenerator $keyGenerator,
) {
$this->valueSerializer = new ValueSerializer;
}

Expand Down
10 changes: 9 additions & 1 deletion src/SettingsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use Rawilk\Settings\Contracts\Setting as SettingContract;
use Rawilk\Settings\Drivers\Factory;
use Rawilk\Settings\Support\ContextSerializers\ContextSerializer;
use Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;

Expand Down Expand Up @@ -59,8 +61,14 @@ protected function registerSettings(): void
);

$this->app->singleton(Settings::class, function ($app) {
$keyGenerator = $this->app->make($app['config']['settings.key_generator'] ?? Md5KeyGenerator::class);
$keyGenerator->setContextSerializer(
$this->app->make($app['config']['settings.context_serializer'] ?? ContextSerializer::class)
);

$settings = new Settings(
$app['SettingsFactory']->driver()
$app['SettingsFactory']->driver(),
$keyGenerator,
);

$settings->useCacheKeyPrefix($app['config']['settings.cache_key_prefix'] ?? '');
Expand Down
19 changes: 18 additions & 1 deletion src/Support/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
namespace Rawilk\Settings\Support;

use Countable;
use Illuminate\Contracts\Support\Arrayable;
use OutOfBoundsException;
use Rawilk\Settings\Exceptions\InvalidContextValue;

class Context implements Countable
class Context implements Arrayable, Countable
{
protected array $arguments = [];

Expand Down Expand Up @@ -43,6 +45,8 @@ public function remove(string $name): self

public function set(string $name, $value): self
{
$this->ensureValidValue($name, $value);

$this->arguments[$name] = $value;

return $this;
Expand All @@ -52,4 +56,17 @@ public function count(): int
{
return count($this->arguments);
}

public function toArray(): array
{
return $this->arguments;
}

protected function ensureValidValue(string $key, mixed $value): void
{
throw_unless(
is_string($value) || is_numeric($value) || is_bool($value) || is_null($value),
InvalidContextValue::forKey($key),
);
}
}
13 changes: 0 additions & 13 deletions src/Support/ContextSerializer.php

This file was deleted.

16 changes: 16 additions & 0 deletions src/Support/ContextSerializers/ContextSerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Support\ContextSerializers;

use Rawilk\Settings\Contracts\ContextSerializer as ContextSerializerContract;
use Rawilk\Settings\Support\Context;

class ContextSerializer implements ContextSerializerContract
{
public function serialize(Context $context = null): string
{
return serialize($context);
}
}
34 changes: 34 additions & 0 deletions src/Support/ContextSerializers/DotNotationContextSerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Support\ContextSerializers;

use Rawilk\Settings\Contracts\ContextSerializer as ContextSerializerContract;
use Rawilk\Settings\Support\Context;

class DotNotationContextSerializer implements ContextSerializerContract
{
public function serialize(Context $context = null): string
{
if (is_null($context)) {
return '';
}

return collect($context->toArray())
->map(function ($value, string $key) {
// Use the model's morph class when possible.
$value = match ($key) {
'model' => rescue(fn () => app($value)->getMorphClass(), $value),
default => $value,
};

if ($value === false) {
$value = 0;
}

return "{$key}:{$value}";
})
->implode('::');
}
}
17 changes: 0 additions & 17 deletions src/Support/KeyGenerator.php

This file was deleted.

26 changes: 26 additions & 0 deletions src/Support/KeyGenerators/Md5KeyGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Support\KeyGenerators;

use Rawilk\Settings\Contracts\ContextSerializer;
use Rawilk\Settings\Contracts\KeyGenerator as KeyGeneratorContract;
use Rawilk\Settings\Support\Context;

class Md5KeyGenerator implements KeyGeneratorContract
{
protected ContextSerializer $serializer;

public function generate(string $key, Context $context = null): string
{
return md5($key . $this->serializer->serialize($context));
}

public function setContextSerializer(ContextSerializer $serializer): self
{
$this->serializer = $serializer;

return $this;
}
}
44 changes: 44 additions & 0 deletions src/Support/KeyGenerators/ReadableKeyGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Support\KeyGenerators;

use Illuminate\Support\Str;
use Rawilk\Settings\Contracts\ContextSerializer;
use Rawilk\Settings\Contracts\KeyGenerator as KeyGeneratorContract;
use Rawilk\Settings\Support\Context;

class ReadableKeyGenerator implements KeyGeneratorContract
{
protected ContextSerializer $serializer;

public function generate(string $key, Context $context = null): string
{
$key = $this->normalizeKey($key);

if ($context) {
$key .= ':c:::' . $this->serializer->serialize($context);
}

return $key;
}

public function setContextSerializer(ContextSerializer $serializer): KeyGeneratorContract
{
$this->serializer = $serializer;

return $this;
}

protected function normalizeKey(string $key): string
{
// We want to preserve period characters in the key, however everything else is fair game
// to convert to a slug.
return Str::of($key)
->replace('.', '-dot-')
->slug()
->replace('-dot-', '.')
->__toString();
}
}
4 changes: 2 additions & 2 deletions src/Support/ValueSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ public function serialize($value): string
return serialize($value);
}

public function unserialize(string $serialized)
public function unserialize(string $serialized): mixed
{
return unserialize($serialized);
return unserialize($serialized, ['allowed_classes' => false]);
}
}
Loading
Loading