From 727d60e8848ba5b01d4f63a8db4c1287a7467f31 Mon Sep 17 00:00:00 2001 From: manuelduarte077 Date: Thu, 12 Nov 2026 16:07:20 -0600 Subject: [PATCH 1/6] feat(storage): add store abstraction, fake and local fallback driver Settings resolve through a SettingsStore driver: native bridge on device, file or array store locally and in tests. Settings::fake() swaps in an in-memory store for assertions. --- config/nativephp-settings.php | 44 +++ src/Contracts/SettingsBridge.php | 2 +- src/Contracts/SettingsStore.php | 41 +++ src/Events/SettingsCorrupted.php | 18 ++ src/Exceptions/SettingTypeMismatch.php | 22 ++ src/Facades/Settings.php | 59 +++- src/Settings.php | 334 ++++++++++++++++++----- src/SettingsServiceProvider.php | 31 ++- src/Stores/ArrayStore.php | 43 +++ src/Stores/FileStore.php | 201 ++++++++++++++ src/Stores/NativeStore.php | 113 ++++++++ src/Stores/StoreResolver.php | 118 ++++++++ src/Stores/UnavailableStore.php | 48 ++++ src/Support/RuntimeEnvironment.php | 53 ++++ src/Testing/SettingsFake.php | 105 +++++++ tests/FileStoreTest.php | 103 +++++++ tests/Pest.php | 2 +- tests/SettingsFakeTest.php | 78 ++++++ tests/StoreContractTest.php | 83 ++++++ tests/StoreResolverTest.php | 162 +++++++++++ tests/Support/SettingsContractBridge.php | 63 +++++ tests/Support/TemporaryDirectory.php | 29 ++ tests/TestCase.php | 32 +++ 23 files changed, 1704 insertions(+), 80 deletions(-) create mode 100644 config/nativephp-settings.php create mode 100644 src/Contracts/SettingsStore.php create mode 100644 src/Events/SettingsCorrupted.php create mode 100644 src/Exceptions/SettingTypeMismatch.php create mode 100644 src/Stores/ArrayStore.php create mode 100644 src/Stores/FileStore.php create mode 100644 src/Stores/NativeStore.php create mode 100644 src/Stores/StoreResolver.php create mode 100644 src/Stores/UnavailableStore.php create mode 100644 src/Support/RuntimeEnvironment.php create mode 100644 src/Testing/SettingsFake.php create mode 100644 tests/FileStoreTest.php create mode 100644 tests/SettingsFakeTest.php create mode 100644 tests/StoreContractTest.php create mode 100644 tests/StoreResolverTest.php create mode 100644 tests/Support/SettingsContractBridge.php create mode 100644 tests/Support/TemporaryDirectory.php create mode 100644 tests/TestCase.php diff --git a/config/nativephp-settings.php b/config/nativephp-settings.php new file mode 100644 index 0000000..3b6dd2a --- /dev/null +++ b/config/nativephp-settings.php @@ -0,0 +1,44 @@ + env('NATIVE_SETTINGS_DRIVER', 'auto'), + + /* + |-------------------------------------------------------------------------- + | File driver path + |-------------------------------------------------------------------------- + */ + + 'file_path' => env('NATIVE_SETTINGS_FILE_PATH', storage_path('app/nativephp-settings.json')), + + /* + |-------------------------------------------------------------------------- + | Strict typed getters + |-------------------------------------------------------------------------- + | + | When false, typed getters such as Settings::getBool() return the default + | and log a warning when the stored value has another type. When true, + | they throw SettingTypeMismatch instead. + | + */ + + 'strict' => (bool) env('NATIVE_SETTINGS_STRICT', false), + +]; diff --git a/src/Contracts/SettingsBridge.php b/src/Contracts/SettingsBridge.php index b0c4bd8..d3ef6ec 100644 --- a/src/Contracts/SettingsBridge.php +++ b/src/Contracts/SettingsBridge.php @@ -7,7 +7,7 @@ interface SettingsBridge { /** - * @param array $parameters + * @param array $parameters * @return array */ public function call(string $method, array $parameters = []): array; diff --git a/src/Contracts/SettingsStore.php b/src/Contracts/SettingsStore.php new file mode 100644 index 0000000..8f72007 --- /dev/null +++ b/src/Contracts/SettingsStore.php @@ -0,0 +1,41 @@ +, corrupt: list} + */ + public function all(): array; +} diff --git a/src/Events/SettingsCorrupted.php b/src/Events/SettingsCorrupted.php new file mode 100644 index 0000000..ef188fe --- /dev/null +++ b/src/Events/SettingsCorrupted.php @@ -0,0 +1,18 @@ + $keys + */ + public function __construct(public readonly array $keys) {} +} diff --git a/src/Exceptions/SettingTypeMismatch.php b/src/Exceptions/SettingTypeMismatch.php new file mode 100644 index 0000000..c07006d --- /dev/null +++ b/src/Exceptions/SettingTypeMismatch.php @@ -0,0 +1,22 @@ + all() + * @method static array{values: array, corrupt: list} allWithReport() + * @method static bool getBool(string $key, bool $default) + * @method static int getInt(string $key, int $default) + * @method static float getFloat(string $key, float $default) + * @method static string getString(string $key, string $default) + * @method static array getArray(string $key, array $default) * - * @see \Momotombo\NativephpSettings\Settings + * @see SettingsService */ class Settings extends Facade { + /** + * Replace settings storage with an in-memory fake for the current test. + * + * Initial values are validated like real writes but are not recorded as writes. + * + * @param array $initial + * + * @throws \InvalidArgumentException When an initial key or value violates the storage contract. + */ + public static function fake(array $initial = []): SettingsFake + { + $fake = new SettingsFake; + $settings = new SettingsService($fake, (bool) static::$app['config']->get('nativephp-settings.strict', false)); + + foreach ($initial as $key => $value) { + $settings->set((string) $key, $value); + } + + $fake->clearRecorded(); + + static::$app->instance(SettingsStore::class, $fake); + static::swap($settings); + + return $fake; + } + + /** + * Read a backed enum case of the default's enum class. + * + * Declared here, rather than as a `@method` tag, so static analysis and + * IDEs keep the concrete enum type of the default. + * + * @template TEnum of BackedEnum + * + * @param TEnum $default + * @return TEnum + * + * @throws SettingTypeMismatch In strict mode when the stored value is not a case of the enum. + */ + public static function getEnum(string $key, BackedEnum $default): BackedEnum + { + return static::getFacadeRoot()->getEnum($key, $default); + } + protected static function getFacadeAccessor(): string { - return \Momotombo\NativephpSettings\Settings::class; + return SettingsService::class; } } diff --git a/src/Settings.php b/src/Settings.php index 426db7b..59bc016 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -5,16 +5,23 @@ namespace Momotombo\NativephpSettings; use BackedEnum; +use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Log; use InvalidArgumentException; use Momotombo\NativephpSettings\Contracts\SettingsBridge; +use Momotombo\NativephpSettings\Contracts\SettingsStore; +use Momotombo\NativephpSettings\Events\SettingsCorrupted; use Momotombo\NativephpSettings\Exceptions\SettingsBridgeException; +use Momotombo\NativephpSettings\Exceptions\SettingTypeMismatch; +use Momotombo\NativephpSettings\Stores\NativeStore; use UnitEnum; /** - * Stores device-local preferences through the NativePHP bridge. + * Validates device-local preferences and delegates persistence to a {@see SettingsStore}. * - * Values are normalized and validated before they cross the bridge; native - * implementations validate them again before persistence. + * Values are normalized and validated before they reach the store and again + * when they are read back; native implementations validate them once more + * before persistence. */ final class Settings { @@ -22,28 +29,42 @@ final class Settings private const MAX_NESTING_DEPTH = 32; - public function __construct(private readonly SettingsBridge $bridge) {} + /** + * Key segments rejected on every platform because JavaScript treats them specially. + */ + public const RESERVED_KEY_SEGMENTS = ['__proto__', 'constructor', 'prototype']; + + /** + * Keys already reported by a type-mismatch warning in this process. + * + * @var array + */ + private static array $reportedTypeMismatches = []; + + private readonly SettingsStore $store; + + /** + * Passing a {@see SettingsBridge} is still supported and wraps it in a {@see NativeStore}. + * + * @param bool $strict When true, typed getters throw {@see SettingTypeMismatch} instead of returning the default. + */ + public function __construct(SettingsStore|SettingsBridge $store, private readonly bool $strict = false) + { + $this->store = $store instanceof SettingsBridge ? new NativeStore($store) : $store; + } /** * Persist a supported value under a lowercase, dot-separated key. * * @throws InvalidArgumentException When the key or value violates the storage contract. - * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + * @throws SettingsBridgeException When the store is unavailable or returns an invalid response. */ public function set(string $key, mixed $value): void { $key = self::validateKey($key); - $value = self::normalizeValue($value); - self::assertValueSize($value); + $value = self::normalize($value); - $response = $this->bridge->call('Settings.Set', [ - 'key' => $key, - 'value' => $value, - ]); - - if (($response['status'] ?? null) !== 'ok') { - self::invalidResponse('Settings.Set'); - } + $this->store->set($key, $value); } /** @@ -52,111 +73,286 @@ public function set(string $key, mixed $value): void * The default is returned as-is and is never persisted. * * @throws InvalidArgumentException When the key does not use the supported format. - * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + * @throws SettingsBridgeException When the store is unavailable or returns an invalid value. */ public function get(string $key, mixed $default = null): mixed { - $response = $this->bridge->call('Settings.Get', ['key' => self::validateKey($key)]); + $value = $this->store->get(self::validateKey($key)); - if (! is_bool($response['found'] ?? null)) { - self::invalidResponse('Settings.Get'); + if ($value === null) { + return $default; } - if (! $response['found']) { - if (array_key_exists('value', $response)) { - self::invalidResponse('Settings.Get'); - } + return self::normalizeStoredValue($value, 'Settings.Get'); + } + + /** + * Read a boolean, or return the default when the key is absent or holds another type. + * + * @throws SettingTypeMismatch In strict mode when the stored value is not a boolean. + */ + public function getBool(string $key, bool $default): bool + { + $value = $this->get($key); + if ($value === null || is_bool($value)) { + return $value ?? $default; + } + + $this->reportTypeMismatch($key, 'bool'); + + return $default; + } + + /** + * Read an integer, or return the default when the key is absent or holds another type. + * + * @throws SettingTypeMismatch In strict mode when the stored value is not an integer. + */ + public function getInt(string $key, int $default): int + { + $value = $this->get($key); + + if ($value === null || is_int($value)) { + return $value ?? $default; + } + + $this->reportTypeMismatch($key, 'int'); + + return $default; + } + + /** + * Read a float. Whole numbers are accepted and cast, because a float such + * as 2.0 can come back from storage as the integer 2. + * + * @throws SettingTypeMismatch In strict mode when the stored value is not a number. + */ + public function getFloat(string $key, float $default): float + { + $value = $this->get($key); + + if ($value === null) { return $default; } - if (! array_key_exists('value', $response)) { - self::invalidResponse('Settings.Get'); + if (is_float($value) || is_int($value)) { + return (float) $value; } - return self::normalizeBridgeValue($response['value'], 'Settings.Get'); + $this->reportTypeMismatch($key, 'float'); + + return $default; } /** - * Determine whether a setting exists, including when its value is false or zero. + * Read a string, or return the default when the key is absent or holds another type. * - * @throws InvalidArgumentException When the key does not use the supported format. - * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + * @throws SettingTypeMismatch In strict mode when the stored value is not a string. */ - public function has(string $key): bool + public function getString(string $key, string $default): string + { + $value = $this->get($key); + + if ($value === null || is_string($value)) { + return $value ?? $default; + } + + $this->reportTypeMismatch($key, 'string'); + + return $default; + } + + /** + * Read a list or map, or return the default when the key is absent or holds another type. + * + * @param array $default + * @return array + * + * @throws SettingTypeMismatch In strict mode when the stored value is not an array. + */ + public function getArray(string $key, array $default): array + { + $value = $this->get($key); + + if ($value === null || is_array($value)) { + return $value ?? $default; + } + + $this->reportTypeMismatch($key, 'array'); + + return $default; + } + + /** + * Read a backed enum case of the default's enum class. Unknown cases and + * values of the wrong backing type return the default. + * + * @template TEnum of BackedEnum + * + * @param TEnum $default + * @return TEnum + * + * @throws SettingTypeMismatch In strict mode when the stored value is not a case of the enum. + */ + public function getEnum(string $key, BackedEnum $default): BackedEnum { - $response = $this->bridge->call('Settings.Has', ['key' => self::validateKey($key)]); + $value = $this->get($key); + + if ($value === null) { + return $default; + } + + $enum = $default::class; + $hasBackingType = is_string($default->value) ? is_string($value) : is_int($value); + $case = $hasBackingType ? $enum::tryFrom($value) : null; - if (! is_bool($response['found'] ?? null)) { - self::invalidResponse('Settings.Has'); + if ($case === null) { + $this->reportTypeMismatch($key, $enum); + + return $default; } - return $response['found']; + return $case; + } + + /** + * Determine whether a setting exists, including when its value is false or zero. + * + * @throws InvalidArgumentException When the key does not use the supported format. + * @throws SettingsBridgeException When the store is unavailable or returns an invalid response. + */ + public function has(string $key): bool + { + return $this->store->has(self::validateKey($key)); } /** * Remove a setting. Removing an absent key succeeds without changing other values. * * @throws InvalidArgumentException When the key does not use the supported format. - * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + * @throws SettingsBridgeException When the store is unavailable or returns an invalid response. */ public function forget(string $key): void { - $response = $this->bridge->call('Settings.Forget', ['key' => self::validateKey($key)]); - - if (($response['status'] ?? null) !== 'ok') { - self::invalidResponse('Settings.Forget'); - } + $this->store->forget(self::validateKey($key)); } /** - * Retrieve all stored settings keyed by their validated setting keys. + * Retrieve all readable settings keyed by their validated setting keys. + * + * Entries with an invalid key or an unreadable value are skipped instead of + * failing the whole read. Their keys (never their values) are logged and + * reported through the {@see SettingsCorrupted} event. * * Numeric-only keys may appear as integer keys because PHP casts numeric * string array keys to integers. * * @return array * - * @throws SettingsBridgeException When NativePHP is unavailable or returns invalid data. + * @throws SettingsBridgeException When the store is unavailable or returns a malformed response. */ public function all(): array { - $response = $this->bridge->call('Settings.All'); - $values = $response['values'] ?? null; - - if (! is_array($values)) { - self::invalidResponse('Settings.All'); - } + return $this->allWithReport()['values']; + } + /** + * Like {@see all()}, but also return the keys that were skipped. + * + * Skipped keys that use the supported key format can be removed with + * {@see forget()}; keys in any other format cannot be addressed through this API. + * + * @return array{values: array, corrupt: list} + * + * @throws SettingsBridgeException When the store is unavailable or returns a malformed response. + */ + public function allWithReport(): array + { + $stored = $this->store->all(); $settings = []; + $corrupt = $stored['corrupt']; - foreach ($values as $key => $value) { - if (! is_string($key) && ! is_int($key)) { - self::invalidResponse('Settings.All'); - } - + foreach ($stored['values'] as $key => $value) { // PHP casts numeric-string array keys to integers during JSON decoding. $key = (string) $key; try { - $key = self::validateKey($key); - } catch (InvalidArgumentException $exception) { - throw new SettingsBridgeException( - 'INVALID_RESPONSE', - 'The Settings.All response contains an invalid settings key.', - $exception, - ); + $settings[self::validateKey($key)] = self::normalize($value); + } catch (InvalidArgumentException) { + $corrupt[] = $key; } + } + + $corrupt = array_values(array_unique($corrupt)); - $settings[$key] = self::normalizeBridgeValue($value, 'Settings.All'); + if ($corrupt !== []) { + $this->reportCorruptSettings($corrupt); } - return $settings; + return ['values' => $settings, 'corrupt' => $corrupt]; + } + + /** + * Validate and normalize a value into its stored representation + * (string-backed enums become their string value). + * + * @internal Used by the package and its testing helpers. + * + * @throws InvalidArgumentException When the value violates the storage contract. + */ + public static function normalize(mixed $value): mixed + { + $value = self::normalizeValue($value); + self::assertValueSize($value); + + return $value; + } + + /** + * @param list $keys + */ + private function reportCorruptSettings(array $keys): void + { + Log::warning('Some NativePHP settings could not be read and were skipped.', ['keys' => $keys]); + + Event::dispatch(new SettingsCorrupted($keys)); + } + + /** + * @throws SettingTypeMismatch In strict mode. + */ + private function reportTypeMismatch(string $key, string $expected): void + { + if ($this->strict) { + throw new SettingTypeMismatch($key, $expected); + } + + if (isset(self::$reportedTypeMismatches[$key])) { + return; + } + + self::$reportedTypeMismatches[$key] = true; + + Log::warning('A NativePHP setting has an unexpected type; the default was returned.', [ + 'key' => $key, + 'expected' => $expected, + ]); + } + + /** + * @internal Resets the once-per-key type-mismatch warnings between tests. + */ + public static function flushTypeMismatchWarnings(): void + { + self::$reportedTypeMismatches = []; } private static function validateKey(string $key): string { - if ($key === '' || preg_match('/^[a-z0-9_]+(?:\.[a-z0-9_]+)*$/D', $key) !== 1) { + if ($key === '' + || preg_match('/^[a-z0-9_]+(?:\.[a-z0-9_]+)*$/D', $key) !== 1 + || array_intersect(explode('.', $key), self::RESERVED_KEY_SEGMENTS) !== []) { throw new InvalidArgumentException('Settings keys must use lowercase dot notation.'); } @@ -214,13 +410,10 @@ private static function normalizeValue(mixed $value, int $depth = 0): mixed throw new InvalidArgumentException('Settings values must be strings, booleans, integers, floats, or JSON-safe arrays.'); } - private static function normalizeBridgeValue(mixed $value, string $method): mixed + private static function normalizeStoredValue(mixed $value, string $method): mixed { try { - $normalized = self::normalizeValue($value); - self::assertValueSize($normalized); - - return $normalized; + return self::normalize($value); } catch (InvalidArgumentException $exception) { throw new SettingsBridgeException('INVALID_RESPONSE', "The {$method} response contains an unsupported settings value.", $exception); } @@ -238,9 +431,4 @@ private static function assertValueSize(mixed $value): void throw new InvalidArgumentException('Settings values cannot exceed 65536 bytes when JSON encoded.'); } } - - private static function invalidResponse(string $method): never - { - throw new SettingsBridgeException('INVALID_RESPONSE', "The {$method} response does not match the NativePHP Settings contract."); - } } diff --git a/src/SettingsServiceProvider.php b/src/SettingsServiceProvider.php index 84512b0..fc1801d 100644 --- a/src/SettingsServiceProvider.php +++ b/src/SettingsServiceProvider.php @@ -4,23 +4,48 @@ namespace Momotombo\NativephpSettings; +use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\ServiceProvider; use Momotombo\NativephpSettings\Bridge\NativePhpSettingsBridge; -use Momotombo\NativephpSettings\Commands\CopyAssetsCommand; use Momotombo\NativephpSettings\Contracts\SettingsBridge; +use Momotombo\NativephpSettings\Contracts\SettingsStore; +use Momotombo\NativephpSettings\Stores\StoreResolver; +use Momotombo\NativephpSettings\Support\RuntimeEnvironment; class SettingsServiceProvider extends ServiceProvider { public function register(): void { + $this->mergeConfigFrom(__DIR__.'/../config/nativephp-settings.php', 'nativephp-settings'); + $this->app->singleton(SettingsBridge::class, NativePhpSettingsBridge::class); - $this->app->singleton(Settings::class); + + $this->app->singleton(SettingsStore::class, function (Application $app): SettingsStore { + $config = $app['config']; + + $resolver = new StoreResolver( + $app->make(SettingsBridge::class), + (string) $config->get('nativephp-settings.file_path', storage_path('app/nativephp-settings.json')), + ); + + return $resolver->resolve( + (string) $config->get('nativephp-settings.driver', 'auto'), + RuntimeEnvironment::detect($app->runningUnitTests(), $app->environment(['local', 'testing'])), + ); + }); + + $this->app->singleton(Settings::class, fn (Application $app): Settings => new Settings( + $app->make(SettingsStore::class), + (bool) $app['config']->get('nativephp-settings.strict', false), + )); } public function boot(): void { if ($this->app->runningInConsole()) { - $this->commands([CopyAssetsCommand::class]); + $this->publishes([ + __DIR__.'/../config/nativephp-settings.php' => config_path('nativephp-settings.php'), + ], 'nativephp-settings-config'); } } } diff --git a/src/Stores/ArrayStore.php b/src/Stores/ArrayStore.php new file mode 100644 index 0000000..ea784ec --- /dev/null +++ b/src/Stores/ArrayStore.php @@ -0,0 +1,43 @@ + $values + */ + public function __construct(private array $values = []) {} + + public function get(string $key): mixed + { + return $this->values[$key] ?? null; + } + + public function has(string $key): bool + { + return array_key_exists($key, $this->values); + } + + public function set(string $key, mixed $value): void + { + $this->values[$key] = $value; + } + + public function forget(string $key): void + { + unset($this->values[$key]); + } + + public function all(): array + { + return ['values' => $this->values, 'corrupt' => []]; + } +} diff --git a/src/Stores/FileStore.php b/src/Stores/FileStore.php new file mode 100644 index 0000000..4ddb3cc --- /dev/null +++ b/src/Stores/FileStore.php @@ -0,0 +1,201 @@ +.corrupt-` so nothing is silently overwritten. + * Only the path is logged, never the contents. Whole-file corruption has no + * recoverable keys, so it is not reported through `SettingsCorrupted`. + */ +final class FileStore implements SettingsStore +{ + public const MAX_FILE_BYTES = 8 * 1024 * 1024; + + private const JSON_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION; + + /** Generous for values nested 32 levels inside the top-level object. */ + private const MAX_JSON_DEPTH = 64; + + private const DEFAULT_FILE_MODE = 0644; + + public function __construct(private readonly string $path) {} + + public function get(string $key): mixed + { + return $this->read()['values'][$key] ?? null; + } + + public function has(string $key): bool + { + return array_key_exists($key, $this->read()['values']); + } + + public function set(string $key, mixed $value): void + { + $this->mutate(function (array $values) use ($key, $value): array { + $values[$key] = $value; + + return $values; + }); + } + + public function forget(string $key): void + { + $this->mutate(function (array $values) use ($key): array { + unset($values[$key]); + + return $values; + }); + } + + public function all(): array + { + return ['values' => $this->read()['values'], 'corrupt' => []]; + } + + /** + * @return array{values: array, corrupt: bool} + */ + private function read(): array + { + clearstatcache(true, $this->path); + + if (! is_file($this->path)) { + return ['values' => [], 'corrupt' => false]; + } + + $size = @filesize($this->path); + + if ($size === false) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings file could not be read.'); + } + + if ($size > self::MAX_FILE_BYTES) { + return $this->corrupt(); + } + + $contents = @file_get_contents($this->path); + + if ($contents === false) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings file could not be read.'); + } + + try { + $values = json_decode($contents, true, self::MAX_JSON_DEPTH, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return $this->corrupt(); + } + + return is_array($values) ? ['values' => $values, 'corrupt' => false] : $this->corrupt(); + } + + /** + * @return array{values: array, corrupt: bool} + */ + private function corrupt(): array + { + Log::warning('The NativePHP settings file is corrupt and was treated as empty.', ['path' => $this->path]); + + return ['values' => [], 'corrupt' => true]; + } + + /** + * @param Closure(array): array $mutation + */ + private function mutate(Closure $mutation): void + { + $directory = dirname($this->path); + + if (! is_dir($directory) && ! @mkdir($directory, 0755, true) && ! is_dir($directory)) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings directory could not be created.'); + } + + $lock = @fopen($this->path.'.lock', 'c'); + + if ($lock === false) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings lock file could not be opened.'); + } + + try { + if (! flock($lock, LOCK_EX)) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings file could not be locked.'); + } + + $current = $this->read(); + + if ($current['corrupt']) { + $this->quarantine(); + } + + $this->write($directory, $mutation($current['values'])); + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } + + private function quarantine(): void + { + $backup = $this->path.'.corrupt-'.date('YmdHis'); + + if (file_exists($backup)) { + $backup .= '-'.bin2hex(random_bytes(3)); + } + + if (! @rename($this->path, $backup)) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The corrupt settings file could not be moved aside.'); + } + + Log::warning('The corrupt NativePHP settings file was moved aside.', ['path' => $this->path, 'backup' => $backup]); + } + + /** + * @param array $values + */ + private function write(string $directory, array $values): void + { + try { + // Cast to an object so an empty or list-like map is still written as a JSON object. + $json = json_encode((object) $values, self::JSON_FLAGS); + } catch (JsonException $exception) { + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings could not be encoded as JSON.', $exception); + } + + $mode = is_file($this->path) ? (@fileperms($this->path) ?: self::DEFAULT_FILE_MODE) & 0777 : self::DEFAULT_FILE_MODE; + + // tempnam() silently falls back to the system temp directory, and a + // rename across filesystems would not be atomic. + $temporary = @tempnam($directory, '.nativephp-settings-'); + + if ($temporary === false || realpath(dirname($temporary)) !== realpath($directory)) { + if (is_string($temporary)) { + @unlink($temporary); + } + + throw new SettingsBridgeException('STORAGE_FAILED', 'A temporary settings file could not be created next to the settings file.'); + } + + if (@file_put_contents($temporary, $json) === false || ! @chmod($temporary, $mode) || ! @rename($temporary, $this->path)) { + @unlink($temporary); + + throw new SettingsBridgeException('STORAGE_FAILED', 'The settings file could not be written.'); + } + } +} diff --git a/src/Stores/NativeStore.php b/src/Stores/NativeStore.php new file mode 100644 index 0000000..a3bd97a --- /dev/null +++ b/src/Stores/NativeStore.php @@ -0,0 +1,113 @@ +bridge->call('Settings.Get', ['key' => $key]); + + if (! is_bool($response['found'] ?? null)) { + self::invalidResponse('Settings.Get'); + } + + if (! $response['found']) { + if (array_key_exists('value', $response)) { + self::invalidResponse('Settings.Get'); + } + + return null; + } + + if (! array_key_exists('value', $response) || $response['value'] === null) { + self::invalidResponse('Settings.Get'); + } + + return $response['value']; + } + + /** + * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + */ + public function has(string $key): bool + { + $response = $this->bridge->call('Settings.Has', ['key' => $key]); + + if (! is_bool($response['found'] ?? null)) { + self::invalidResponse('Settings.Has'); + } + + return $response['found']; + } + + /** + * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + */ + public function set(string $key, mixed $value): void + { + $response = $this->bridge->call('Settings.Set', ['key' => $key, 'value' => $value]); + + if (($response['status'] ?? null) !== 'ok') { + self::invalidResponse('Settings.Set'); + } + } + + /** + * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + */ + public function forget(string $key): void + { + $response = $this->bridge->call('Settings.Forget', ['key' => $key]); + + if (($response['status'] ?? null) !== 'ok') { + self::invalidResponse('Settings.Forget'); + } + } + + /** + * Native implementations skip entries they cannot decode and report their + * keys in the optional `corrupt` list. + * + * @throws SettingsBridgeException When NativePHP is unavailable or returns an invalid response. + */ + public function all(): array + { + $response = $this->bridge->call('Settings.All'); + $values = $response['values'] ?? null; + $corrupt = $response['corrupt'] ?? []; + + if (! is_array($values) || ! is_array($corrupt)) { + self::invalidResponse('Settings.All'); + } + + return [ + 'values' => $values, + 'corrupt' => array_values(array_filter($corrupt, is_string(...))), + ]; + } + + private static function invalidResponse(string $method): never + { + throw new SettingsBridgeException('INVALID_RESPONSE', "The {$method} response does not match the NativePHP Settings contract."); + } +} diff --git a/src/Stores/StoreResolver.php b/src/Stores/StoreResolver.php new file mode 100644 index 0000000..591db69 --- /dev/null +++ b/src/Stores/StoreResolver.php @@ -0,0 +1,118 @@ +onDevice) { + if ($driver !== 'auto' && $driver !== 'native' && ! self::$warnedAboutIgnoredDriver) { + self::$warnedAboutIgnoredDriver = true; + + Log::warning('The NativePHP settings driver is ignored on device; native storage is used.', ['driver' => $driver]); + } + + return new NativeStore($this->bridge); + } + + return match ($driver) { + 'native' => new NativeStore($this->bridge), + 'file' => new FileStore($this->filePath), + 'array' => new ArrayStore, + default => $this->resolveAutomatically($environment), + }; + } + + /** + * @internal Resets the once-per-process warning between tests. + */ + public static function flushWarnings(): void + { + self::$warnedAboutIgnoredDriver = false; + } + + private function resolveAutomatically(RuntimeEnvironment $environment): SettingsStore + { + if (! $this->bridge instanceof NativePhpSettingsBridge) { + return new NativeStore($this->bridge); + } + + if ($environment->runningUnitTests && $environment->fakeBridgeBound && ! $environment->runningInJump) { + return new ArrayStore; + } + + if ($environment->runningInJump || $environment->fakeBridgeBound) { + if ($environment->settingsBridgeAvailable) { + return new NativeStore($this->bridge); + } + + $fallback = $environment->runningUnitTests ? new ArrayStore : new FileStore($this->filePath); + + Log::warning('NativePHP settings bridge functions are unavailable in this runtime; using a local fallback store.', [ + 'store' => $fallback::class, + ]); + + return $fallback; + } + + if ($environment->runningUnitTests) { + return new ArrayStore; + } + + return $environment->localEnvironment ? new FileStore($this->filePath) : new UnavailableStore; + } +} diff --git a/src/Stores/UnavailableStore.php b/src/Stores/UnavailableStore.php new file mode 100644 index 0000000..624a813 --- /dev/null +++ b/src/Stores/UnavailableStore.php @@ -0,0 +1,48 @@ +isInternal(); + $runningInJump = ! $onDevice && $bridgeDefined && System::runningInJump(); + $fakeBridgeBound = ! $onDevice && $bridgeDefined && FakeBridge::current() !== null; + + return new self( + onDevice: $onDevice, + runningInJump: $runningInJump, + fakeBridgeBound: $fakeBridgeBound, + settingsBridgeAvailable: $onDevice + || (($runningInJump || $fakeBridgeBound) && function_exists('nativephp_can') && nativephp_can('Settings.Get')), + runningUnitTests: $runningUnitTests, + localEnvironment: $localEnvironment, + ); + } +} diff --git a/src/Testing/SettingsFake.php b/src/Testing/SettingsFake.php new file mode 100644 index 0000000..c1f1a31 --- /dev/null +++ b/src/Testing/SettingsFake.php @@ -0,0 +1,105 @@ + */ + private array $values = []; + + /** @var list */ + private array $writes = []; + + /** @var list */ + private array $forgotten = []; + + public function get(string $key): mixed + { + return $this->values[$key] ?? null; + } + + public function has(string $key): bool + { + return array_key_exists($key, $this->values); + } + + public function set(string $key, mixed $value): void + { + $this->values[$key] = $value; + $this->writes[] = ['key' => $key, 'value' => $value]; + } + + public function forget(string $key): void + { + unset($this->values[$key]); + $this->forgotten[] = $key; + } + + public function all(): array + { + return ['values' => $this->values, 'corrupt' => []]; + } + + /** + * Forget recorded writes and removals while keeping the current values. + */ + public function clearRecorded(): void + { + $this->writes = []; + $this->forgotten = []; + } + + /** + * Assert the key was set. When a value is given, at least one write must + * match it after normalization (string-backed enums compare by value). + */ + public function assertSet(string $key, mixed $value = null): self + { + $writes = array_values(array_filter($this->writes, fn (array $write): bool => $write['key'] === $key)); + + Assert::assertNotEmpty($writes, "The setting [{$key}] was not set."); + + if (func_num_args() > 1) { + $expected = Settings::normalize($value); + + Assert::assertContains( + $expected, + array_column($writes, 'value'), + "The setting [{$key}] was set, but never to the expected value.", + ); + } + + return $this; + } + + public function assertForgotten(string $key): self + { + Assert::assertContains($key, $this->forgotten, "The setting [{$key}] was not forgotten."); + + return $this; + } + + public function assertNothingSet(): self + { + Assert::assertSame( + [], + $this->writes, + 'Expected no settings to be set, but these were: '.implode(', ', array_unique(array_column($this->writes, 'key'))).'.', + ); + + return $this; + } +} diff --git a/tests/FileStoreTest.php b/tests/FileStoreTest.php new file mode 100644 index 0000000..d8f976b --- /dev/null +++ b/tests/FileStoreTest.php @@ -0,0 +1,103 @@ +directory = createSettingsTemporaryDirectory(); + $this->path = $this->directory.'/nested/settings.json'; +}); + +afterEach(function () { + deleteSettingsTemporaryDirectory($this->directory); +}); + +/** + * @return list + */ +function settingsFilesIn(string $directory): array +{ + return array_values(array_diff(scandir($directory) ?: [], ['.', '..'])); +} + +function writeSettingsFile(string $path, string $contents): void +{ + @mkdir(dirname($path), 0755, true); + file_put_contents($path, $contents); +} + +it('creates the directory and persists values across store instances', function () { + (new Settings(new FileStore($this->path)))->set('app.language', 'es'); + + expect((new Settings(new FileStore($this->path)))->get('app.language'))->toBe('es') + ->and(json_decode((string) file_get_contents($this->path), true))->toBe(['app.language' => 'es']); +}); + +it('writes a JSON object with mode 0644 and leaves no temporary files behind', function () { + $settings = new Settings(new FileStore($this->path)); + + $settings->set('app.language', 'es'); + $settings->forget('app.language'); + + clearstatcache(); + + expect(file_get_contents($this->path))->toBe('{}') + ->and(fileperms($this->path) & 0777)->toBe(0644) + ->and(settingsFilesIn(dirname($this->path)))->toBe(['settings.json', 'settings.json.lock']); +}); + +it('preserves the permissions of an existing file', function () { + writeSettingsFile($this->path, '{}'); + chmod($this->path, 0600); + + (new Settings(new FileStore($this->path)))->set('app.language', 'es'); + + clearstatcache(); + + expect(fileperms($this->path) & 0777)->toBe(0600); +}); + +it('treats unreadable files as empty and moves them aside before the next write', function (string $contents) { + writeSettingsFile($this->path, $contents); + Log::spy(); + + $settings = new Settings(new FileStore($this->path)); + + expect($settings->all())->toBe([]) + ->and($settings->get('secret.token', 'none'))->toBe('none'); + + $settings->set('app.language', 'en'); + + $backups = array_values(array_filter(settingsFilesIn(dirname($this->path)), fn (string $file): bool => str_starts_with($file, 'settings.json.corrupt-'))); + + expect(json_decode((string) file_get_contents($this->path), true))->toBe(['app.language' => 'en']) + ->and($backups)->toHaveCount(1) + ->and(file_get_contents(dirname($this->path).'/'.$backups[0]))->toBe($contents); + + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, array $context): bool => array_key_exists('path', $context) + && ! str_contains($message.json_encode($context), 'abc123')) + ->atLeast()->once(); +})->with([ + 'invalid JSON' => ['{"secret.token": "abc123"'], + 'not an object' => ['"abc123"'], + 'too deep' => ['{"secret.token":'.str_repeat('[', 70).'"abc123"'.str_repeat(']', 70).'}'], +]); + +it('treats a file larger than the size cap as corrupt without reading it', function () { + writeSettingsFile($this->path, '{"app.language":"'.str_repeat('x', FileStore::MAX_FILE_BYTES).'"}'); + Log::spy(); + + expect((new Settings(new FileStore($this->path)))->all())->toBe([]); + + Log::shouldHaveReceived('warning')->once(); +}); diff --git a/tests/Pest.php b/tests/Pest.php index d027081..c50403d 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -6,4 +6,4 @@ |-------------------------------------------------------------------------- */ -uses()->in('.'); \ No newline at end of file +uses()->in('.'); diff --git a/tests/SettingsFakeTest.php b/tests/SettingsFakeTest.php new file mode 100644 index 0000000..0c6963d --- /dev/null +++ b/tests/SettingsFakeTest.php @@ -0,0 +1,78 @@ +toBeInstanceOf(SettingsFake::class) + ->and(app(SettingsStore::class))->toBe($fake) + ->and(app(SettingsService::class)->get('app.language'))->toBe('es') + ->and(Settings::all())->toBe(['app.language' => 'es']); +}); + +it('seeds validated initial values without recording them as writes', function () { + $fake = Settings::fake(['app.language' => SettingsFakeLanguage::English, 'layout.columns' => 2]); + + expect(Settings::get('app.language'))->toBe('en') + ->and(Settings::get('layout.columns'))->toBe(2); + + $fake->assertNothingSet(); +}); + +it('rejects invalid initial values', function () { + Settings::fake(['Invalid Key' => 'value']); +})->throws(InvalidArgumentException::class); + +it('still validates keys and values written through the facade', function () { + $fake = Settings::fake(); + + expect(fn () => Settings::set('app.value', null))->toThrow(InvalidArgumentException::class); + + $fake->assertNothingSet(); +}); + +it('asserts writes with and without an expected value', function () { + $fake = Settings::fake(); + + Settings::set('app.language', SettingsFakeLanguage::English); + Settings::set('layout.columns', 3); + + $fake->assertSet('app.language') + ->assertSet('app.language', SettingsFakeLanguage::English) + ->assertSet('app.language', 'en') + ->assertSet('layout.columns', 3); + + expect(fn () => $fake->assertSet('layout.columns', '3'))->toThrow(AssertionFailedError::class) + ->and(fn () => $fake->assertSet('profile.name'))->toThrow(AssertionFailedError::class) + ->and(fn () => $fake->assertNothingSet())->toThrow(AssertionFailedError::class); +}); + +it('asserts forgotten keys', function () { + $fake = Settings::fake(['profile.name' => 'Ana']); + + Settings::forget('profile.name'); + + $fake->assertForgotten('profile.name'); + + expect(Settings::has('profile.name'))->toBeFalse() + ->and(fn () => $fake->assertForgotten('app.language'))->toThrow(AssertionFailedError::class); +}); diff --git a/tests/StoreContractTest.php b/tests/StoreContractTest.php new file mode 100644 index 0000000..67ce7f2 --- /dev/null +++ b/tests/StoreContractTest.php @@ -0,0 +1,83 @@ + fn (): SettingsStore => new ArrayStore, + 'file' => function (): SettingsStore { + $directory = createSettingsTemporaryDirectory(); + test()->temporaryDirectory = $directory; + + return new FileStore($directory.'/settings.json'); + }, + 'native (fake bridge)' => fn (): SettingsStore => new NativeStore(new SettingsContractBridge), +]); + +afterEach(function () { + if (is_string($this->temporaryDirectory ?? null)) { + deleteSettingsTemporaryDirectory($this->temporaryDirectory); + } +}); + +it('round trips every supported value type', function (SettingsStore $store) { + $settings = new Settings($store); + $nested = ['show_email' => true, 'shortcuts' => ['home', 'search'], 'scale' => 1.5]; + + $settings->set('profile.name', 'Ana Pérez'); + $settings->set('feature.enabled', false); + $settings->set('layout.columns', 0); + $settings->set('display.scale', 1.0); + $settings->set('profile.options', $nested); + + expect($settings->get('profile.name'))->toBe('Ana Pérez') + ->and($settings->get('feature.enabled'))->toBeFalse() + ->and($settings->get('layout.columns'))->toBe(0) + ->and($settings->get('display.scale'))->toBe(1.0) + ->and($settings->get('profile.options'))->toBe($nested) + ->and($settings->all())->toBe([ + 'profile.name' => 'Ana Pérez', + 'feature.enabled' => false, + 'layout.columns' => 0, + 'display.scale' => 1.0, + 'profile.options' => $nested, + ]); +})->with('stores'); + +it('reports absent keys with found semantics', function (SettingsStore $store) { + $settings = new Settings($store); + + expect($store->get('missing.key'))->toBeNull() + ->and($store->has('missing.key'))->toBeFalse() + ->and($settings->get('missing.key', 'fallback'))->toBe('fallback') + ->and($store->all())->toBe(['values' => [], 'corrupt' => []]); + + $settings->forget('missing.key'); + + expect($settings->has('missing.key'))->toBeFalse(); +})->with('stores'); + +it('replaces and forgets values without touching other keys', function (SettingsStore $store) { + $settings = new Settings($store); + + $settings->set('app.language', 'es'); + $settings->set('app.language', 'en'); + $settings->set('profile.name', 'Ana'); + $settings->forget('profile.name'); + $settings->forget('profile.name'); + + expect($settings->all())->toBe(['app.language' => 'en']) + ->and($settings->has('profile.name'))->toBeFalse(); +})->with('stores'); diff --git a/tests/StoreResolverTest.php b/tests/StoreResolverTest.php new file mode 100644 index 0000000..c24ae21 --- /dev/null +++ b/tests/StoreResolverTest.php @@ -0,0 +1,162 @@ +resolve($driver, settingsEnvironment()))->toBeInstanceOf($store) + ->and(settingsResolver()->resolve($driver, settingsEnvironment(fakeBridge: true, available: true, unitTests: true)))->toBeInstanceOf($store); +})->with([ + 'native' => ['native', NativeStore::class], + 'file' => ['file', FileStore::class], + 'array' => ['array', ArrayStore::class], +]); + +it('rejects unknown drivers, including on a device', function (RuntimeEnvironment $environment) { + settingsResolver()->resolve('redis', $environment); +})->with([ + 'off device' => [settingsEnvironment()], + 'on device' => [settingsEnvironment(onDevice: true, available: true)], +])->throws(InvalidArgumentException::class, 'Unsupported settings driver [redis]'); + +it('always uses native storage on a device', function (string $driver) { + Log::spy(); + + expect(settingsResolver()->resolve($driver, settingsEnvironment(onDevice: true, available: true, unitTests: true))) + ->toBeInstanceOf(NativeStore::class); + + Log::shouldNotHaveReceived('warning'); +})->with(['auto', 'native']); + +it('ignores a non-native driver on a device and warns once per process', function () { + Log::spy(); + $environment = settingsEnvironment(onDevice: true, available: true); + + expect(settingsResolver()->resolve('file', $environment))->toBeInstanceOf(NativeStore::class) + ->and(settingsResolver()->resolve('array', $environment))->toBeInstanceOf(NativeStore::class); + + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, array $context): bool => str_contains($message, 'ignored on device') && $context === ['driver' => 'file']) + ->once(); +}); + +it('uses a custom bound bridge through native storage under auto', function () { + expect(settingsResolver(new SettingsContractBridge)->resolve('auto', settingsEnvironment(unitTests: true))) + ->toBeInstanceOf(NativeStore::class) + ->and(settingsResolver(new SettingsContractBridge)->resolve('array', settingsEnvironment(unitTests: true))) + ->toBeInstanceOf(ArrayStore::class); +}); + +it('uses an in-memory store for unit tests driven by a FakeBridge', function () { + expect(settingsResolver()->resolve('auto', settingsEnvironment(fakeBridge: true, available: true, unitTests: true))) + ->toBeInstanceOf(ArrayStore::class); +}); + +it('uses native storage through Jump when it provides the settings functions', function () { + expect(settingsResolver()->resolve('auto', settingsEnvironment(jump: true, available: true, local: true))) + ->toBeInstanceOf(NativeStore::class); +}); + +it('falls back with a warning when a relayed bridge lacks the settings functions', function (RuntimeEnvironment $environment, string $store) { + Log::spy(); + + expect(settingsResolver()->resolve('auto', $environment))->toBeInstanceOf($store); + + Log::shouldHaveReceived('warning')->once(); +})->with([ + 'jump' => [settingsEnvironment(jump: true, local: true), FileStore::class], + 'jump under tests' => [settingsEnvironment(jump: true, unitTests: true), ArrayStore::class], +]); + +it('uses a local fallback without a bridge only in local and testing environments', function (RuntimeEnvironment $environment, string $store) { + Log::spy(); + + expect(settingsResolver()->resolve('auto', $environment))->toBeInstanceOf($store); + + Log::shouldNotHaveReceived('warning'); +})->with([ + 'local' => [settingsEnvironment(local: true), FileStore::class], + 'unit tests' => [settingsEnvironment(unitTests: true, local: true), ArrayStore::class], + 'production' => [settingsEnvironment(), UnavailableStore::class], +]); + +it('fails every call outside a runtime in other environments', function () { + $settings = new Settings(new UnavailableStore); + + expect(fn () => $settings->get('app.language'))->toThrow(SettingsBridgeException::class, 'only available inside a NativePHP runtime') + ->and(fn () => $settings->set('app.language', 'es'))->toThrow(SettingsBridgeException::class) + ->and(fn () => $settings->has('app.language'))->toThrow(SettingsBridgeException::class) + ->and(fn () => $settings->forget('app.language'))->toThrow(SettingsBridgeException::class) + ->and(fn () => $settings->all())->toThrow(SettingsBridgeException::class); + + try { + $settings->get('app.language'); + } catch (SettingsBridgeException $exception) { + expect($exception->bridgeCode)->toBe('BRIDGE_UNAVAILABLE'); + } +}); + +it('detects an off-device runtime without a bridge', function () { + expect(RuntimeEnvironment::detect(true, true))->toEqual(settingsEnvironment(unitTests: true, local: true)); +}); + +it('detects a test FakeBridge and its capabilities', function () { + Native::fakeBridge(); + + expect(RuntimeEnvironment::detect(true, false))->toEqual(settingsEnvironment(fakeBridge: true, available: true, unitTests: true)); + + Native::fakeBridge()->withoutCapability('Settings.Get'); + + expect(RuntimeEnvironment::detect(true, false))->toEqual(settingsEnvironment(fakeBridge: true, unitTests: true)); +}); + +it('binds an in-memory store under unit tests and honours the configured driver', function () { + Native::fakeBridge(); + + expect(app(SettingsStore::class))->toBeInstanceOf(ArrayStore::class) + ->and(app(Settings::class))->toBeInstanceOf(Settings::class); + + config(['nativephp-settings.driver' => 'native']); + app()->forgetInstance(SettingsStore::class); + + expect(app(SettingsStore::class))->toBeInstanceOf(NativeStore::class); +}); diff --git a/tests/Support/SettingsContractBridge.php b/tests/Support/SettingsContractBridge.php new file mode 100644 index 0000000..ecc0f8c --- /dev/null +++ b/tests/Support/SettingsContractBridge.php @@ -0,0 +1,63 @@ + */ + public array $values = []; + + /** @var array}> */ + public array $calls = []; + + /** @var array|Closure> */ + public array $responses = []; + + public function call(string $method, array $parameters = []): array + { + $this->calls[] = ['method' => $method, 'parameters' => $parameters]; + + if (array_key_exists($method, $this->responses)) { + $response = $this->responses[$method]; + + return $response instanceof Closure ? $response($parameters, $this) : $response; + } + + return match ($method) { + 'Settings.Set' => $this->set($parameters), + 'Settings.Get' => $this->get($parameters), + 'Settings.Has' => ['found' => array_key_exists($parameters['key'], $this->values)], + 'Settings.Forget' => $this->forget($parameters), + 'Settings.All' => ['values' => $this->values], + default => throw new LogicException("Unexpected bridge call [{$method}]."), + }; + } + + private function set(array $parameters): array + { + $this->values[$parameters['key']] = $parameters['value']; + + return ['status' => 'ok']; + } + + private function get(array $parameters): array + { + $key = $parameters['key']; + + return array_key_exists($key, $this->values) + ? ['found' => true, 'value' => $this->values[$key]] + : ['found' => false]; + } + + private function forget(array $parameters): array + { + unset($this->values[$parameters['key']]); + + return ['status' => 'ok']; + } +} diff --git a/tests/Support/TemporaryDirectory.php b/tests/Support/TemporaryDirectory.php new file mode 100644 index 0000000..31cc36e --- /dev/null +++ b/tests/Support/TemporaryDirectory.php @@ -0,0 +1,29 @@ + + */ + protected function getPackageProviders($app): array + { + return [NativeServiceProvider::class, SettingsServiceProvider::class]; + } + } +} else { + abstract class BaseTestCase extends \Tests\TestCase {} +} + +abstract class TestCase extends BaseTestCase {} From f3383d35ed8fd8ed5d2c6fbc62279682cd37a5a9 Mon Sep 17 00:00:00 2001 From: manuelduarte077 Date: Thu, 12 Nov 2026 16:07:25 -0600 Subject: [PATCH 2/6] feat(api): add typed getters and allWithReport Typed getters (bool, int, float, string, array, enum) return the default on type mismatch. all() skips corrupted entries and allWithReport() exposes what was skipped. --- tests/SettingsContractTest.php | 71 +++------------- tests/TolerantAllTest.php | 97 ++++++++++++++++++++++ tests/TypedGettersTest.php | 147 +++++++++++++++++++++++++++++++++ 3 files changed, 257 insertions(+), 58 deletions(-) create mode 100644 tests/TolerantAllTest.php create mode 100644 tests/TypedGettersTest.php diff --git a/tests/SettingsContractTest.php b/tests/SettingsContractTest.php index 5deef74..7b432f3 100644 --- a/tests/SettingsContractTest.php +++ b/tests/SettingsContractTest.php @@ -1,10 +1,11 @@ */ - public array $values = []; - - /** @var array}> */ - public array $calls = []; - - /** @var array|Closure> */ - public array $responses = []; - - public function call(string $method, array $parameters = []): array - { - $this->calls[] = ['method' => $method, 'parameters' => $parameters]; - - if (array_key_exists($method, $this->responses)) { - $response = $this->responses[$method]; - - return $response instanceof Closure ? $response($parameters, $this) : $response; - } - - return match ($method) { - 'Settings.Set' => $this->set($parameters), - 'Settings.Get' => $this->get($parameters), - 'Settings.Has' => ['found' => array_key_exists($parameters['key'], $this->values)], - 'Settings.Forget' => $this->forget($parameters), - 'Settings.All' => ['values' => $this->values], - default => throw new LogicException("Unexpected bridge call [{$method}]."), - }; - } - - private function set(array $parameters): array - { - $this->values[$parameters['key']] = $parameters['value']; - - return ['status' => 'ok']; - } - - private function get(array $parameters): array - { - $key = $parameters['key']; - - return array_key_exists($key, $this->values) - ? ['found' => true, 'value' => $this->values[$key]] - : ['found' => false]; - } - - private function forget(array $parameters): array - { - unset($this->values[$parameters['key']]); - - return ['status' => 'ok']; - } -} - function makeSettingsContract(): array { $bridge = new SettingsContractBridge; @@ -138,7 +84,7 @@ function makeSettingsContract(): array it('rejects keys outside lowercase dot notation', function () { [$settings] = makeSettingsContract(); - foreach (['', 'Profile.name', 'two words', 'trailing.', '.leading', 'double..dot', 'dash-key', 'ñame'] as $key) { + foreach (['', 'Profile.name', 'two words', 'trailing.', '.leading', 'double..dot', 'dash-key', 'ñame', '__proto__', 'app.__proto__.polluted', 'constructor', 'app.prototype', 'constructor.name'] as $key) { expect(fn () => $settings->set($key, 'value'))->toThrow(InvalidArgumentException::class); } }); @@ -220,6 +166,15 @@ function makeSettingsContract(): array $bridge->responses['Settings.Get'] = ['found' => true, 'value' => null]; expect(fn () => $settings->get('app.value'))->toThrow(SettingsBridgeException::class); - $bridge->responses['Settings.All'] = ['values' => ['Invalid.Key' => 'value']]; + $bridge->responses['Settings.All'] = ['values' => [], 'corrupt' => 'not-a-list']; expect(fn () => $settings->all())->toThrow(SettingsBridgeException::class); }); + +it('accepts keys that only contain reserved words as part of a segment', function () { + [$settings] = makeSettingsContract(); + + $settings->set('app.constructor_name', 'value'); + $settings->set('proto.prototypes', 'value'); + + expect($settings->all())->toBe(['app.constructor_name' => 'value', 'proto.prototypes' => 'value']); +}); diff --git a/tests/TolerantAllTest.php b/tests/TolerantAllTest.php new file mode 100644 index 0000000..fbbaa78 --- /dev/null +++ b/tests/TolerantAllTest.php @@ -0,0 +1,97 @@ +responses['Settings.All'] = [ + 'values' => ['app.language' => 'es', 'layout.columns' => 2], + 'corrupt' => ['profile.avatar', 42], + ]; + + expect((new Settings($bridge))->all())->toBe(['app.language' => 'es', 'layout.columns' => 2]); + + Event::assertDispatched(SettingsCorrupted::class, fn (SettingsCorrupted $event): bool => $event->keys === ['profile.avatar']); + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, array $context): bool => $context === ['keys' => ['profile.avatar']]) + ->once(); +}); + +it('skips invalid keys and values detected in PHP without logging values', function () { + Event::fake([SettingsCorrupted::class]); + Log::spy(); + + $bridge = new SettingsContractBridge; + $bridge->responses['Settings.All'] = [ + 'values' => [ + 'app.language' => 'es', + 'Invalid.Key' => 'secret-one', + 'profile.token' => null, + 'profile.options' => ['nested' => null], + ], + 'corrupt' => ['profile.token'], + ]; + + expect((new Settings($bridge))->all())->toBe(['app.language' => 'es']); + + Event::assertDispatched( + SettingsCorrupted::class, + fn (SettingsCorrupted $event): bool => $event->keys === ['profile.token', 'Invalid.Key', 'profile.options'], + ); + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, array $context): bool => ! str_contains($message.json_encode($context), 'secret-one')) + ->once(); +}); + +it('does not dispatch an event when every entry is readable', function () { + Event::fake([SettingsCorrupted::class]); + + expect((new Settings(new ArrayStore(['app.language' => 'es'])))->all())->toBe(['app.language' => 'es']); + + Event::assertNotDispatched(SettingsCorrupted::class); +}); + +it('keeps failing reads of a single corrupt key', function () { + $bridge = new SettingsContractBridge; + $bridge->responses['Settings.Get'] = ['found' => true, 'value' => ['nested' => null]]; + + expect(fn () => (new Settings($bridge))->get('profile.avatar'))->toThrow(SettingsBridgeException::class); +}); + +it('reports skipped keys with allWithReport', function () { + Event::fake([SettingsCorrupted::class]); + + $bridge = new SettingsContractBridge; + $bridge->responses['Settings.All'] = [ + 'values' => ['app.language' => 'es', 'app.__proto__' => 'x', 'profile.avatar' => ['nested' => null]], + 'corrupt' => ['profile.photo', 'profile.photo'], + ]; + + expect((new Settings($bridge))->allWithReport())->toBe([ + 'values' => ['app.language' => 'es'], + 'corrupt' => ['profile.photo', 'app.__proto__', 'profile.avatar'], + ]); + + Event::assertDispatchedTimes(SettingsCorrupted::class, 1); +}); + +it('reports an empty corrupt list when everything is readable', function () { + expect((new Settings(new ArrayStore(['app.language' => 'es'])))->allWithReport()) + ->toBe(['values' => ['app.language' => 'es'], 'corrupt' => []]); +}); diff --git a/tests/TypedGettersTest.php b/tests/TypedGettersTest.php new file mode 100644 index 0000000..1720717 --- /dev/null +++ b/tests/TypedGettersTest.php @@ -0,0 +1,147 @@ + $values + */ +function typedSettings(array $values = [], bool $strict = false): Settings +{ + return new Settings(new ArrayStore($values), $strict); +} + +it('returns the default for absent keys without logging', function () { + Log::spy(); + $settings = typedSettings(); + + expect($settings->getBool('a.key', true))->toBeTrue() + ->and($settings->getInt('a.key', 7))->toBe(7) + ->and($settings->getFloat('a.key', 1.5))->toBe(1.5) + ->and($settings->getString('a.key', 'x'))->toBe('x') + ->and($settings->getArray('a.key', ['x']))->toBe(['x']) + ->and($settings->getEnum('a.key', TypedGetterTheme::Light))->toBe(TypedGetterTheme::Light); + + Log::shouldNotHaveReceived('warning'); +}); + +it('returns stored values of the expected type', function () { + $settings = typedSettings([ + 'flag' => false, + 'count' => 0, + 'ratio' => 1.25, + 'whole' => 2, + 'name' => 'Ana', + 'list' => ['home', 'search'], + 'map' => ['show_tips' => true], + 'theme' => 'dark', + 'level' => 2, + ]); + + expect($settings->getBool('flag', true))->toBeFalse() + ->and($settings->getInt('count', 5))->toBe(0) + ->and($settings->getFloat('ratio', 0.0))->toBe(1.25) + ->and($settings->getFloat('whole', 0.0))->toBe(2.0) + ->and($settings->getString('name', ''))->toBe('Ana') + ->and($settings->getArray('list', []))->toBe(['home', 'search']) + ->and($settings->getArray('map', []))->toBe(['show_tips' => true]) + ->and($settings->getEnum('theme', TypedGetterTheme::Light))->toBe(TypedGetterTheme::Dark) + ->and($settings->getEnum('level', TypedGetterLevel::Low))->toBe(TypedGetterLevel::High); +}); + +it('returns the default and logs only the key when the type does not match', function (Closure $read, mixed $default) { + Log::spy(); + $settings = typedSettings(['stored.value' => 'secret-value', 'stored.number' => 1]); + + expect($read($settings))->toBe($default); + + Log::shouldHaveReceived('warning') + ->withArgs(fn (string $message, array $context): bool => in_array($context['key'], ['stored.value', 'stored.number'], true) + && ! str_contains($message.json_encode($context), 'secret-value')) + ->once(); +})->with([ + 'bool' => [fn (Settings $settings) => $settings->getBool('stored.value', true), true], + 'int' => [fn (Settings $settings) => $settings->getInt('stored.value', 3), 3], + 'float' => [fn (Settings $settings) => $settings->getFloat('stored.value', 0.5), 0.5], + 'string' => [fn (Settings $settings) => $settings->getString('stored.number', 'x'), 'x'], + 'array' => [fn (Settings $settings) => $settings->getArray('stored.value', ['x']), ['x']], + 'unknown enum case' => [fn (Settings $settings) => $settings->getEnum('stored.value', TypedGetterTheme::Light), TypedGetterTheme::Light], + 'enum backing type' => [fn (Settings $settings) => $settings->getEnum('stored.number', TypedGetterTheme::Dark), TypedGetterTheme::Dark], + 'int enum backing type' => [fn (Settings $settings) => $settings->getEnum('stored.value', TypedGetterLevel::Low), TypedGetterLevel::Low], +]); + +it('throws a type mismatch without the stored value in strict mode', function () { + $settings = typedSettings(['stored.value' => 'secret-value'], strict: true); + + try { + $settings->getInt('stored.value', 0); + $this->fail('Expected a type mismatch.'); + } catch (SettingTypeMismatch $exception) { + expect($exception->key)->toBe('stored.value') + ->and($exception->expected)->toBe('int') + ->and($exception->getMessage())->not->toContain('secret-value'); + } + + expect(fn () => $settings->getEnum('stored.value', TypedGetterTheme::Light)) + ->toThrow(SettingTypeMismatch::class, TypedGetterTheme::class) + ->and($settings->getString('stored.value', ''))->toBe('secret-value') + ->and($settings->getBool('absent.key', true))->toBeTrue(); +}); + +it('reads the strict flag from config for the container and the fake', function () { + config(['nativephp-settings.strict' => true]); + app()->instance(SettingsStore::class, new ArrayStore(['stored.value' => 'text'])); + app()->forgetInstance(Settings::class); + + expect(fn () => app(Settings::class)->getBool('stored.value', false))->toThrow(SettingTypeMismatch::class); + + SettingsFacade::fake(['stored.value' => 'text']); + + expect(fn () => SettingsFacade::getBool('stored.value', false))->toThrow(SettingTypeMismatch::class); +}); + +it('logs a type mismatch once per key per process', function () { + Log::spy(); + $settings = typedSettings(['stored.value' => 'text', 'other.value' => 'text']); + + $settings->getInt('stored.value', 0); + $settings->getBool('stored.value', false); + typedSettings(['stored.value' => 'text'])->getInt('stored.value', 0); + $settings->getInt('other.value', 0); + + Log::shouldHaveReceived('warning')->twice(); +}); + +it('keeps the enum type through the facade', function () { + SettingsFacade::fake(['appearance.theme' => 'dark']); + + expect(SettingsFacade::getEnum('appearance.theme', TypedGetterTheme::Light))->toBe(TypedGetterTheme::Dark) + ->and(SettingsFacade::getEnum('appearance.missing', TypedGetterLevel::Low))->toBe(TypedGetterLevel::Low); +}); From 06a2270201d28f697f4aaa26874cf4ef728e3ca1 Mon Sep 17 00:00:00 2001 From: manuelduarte077 Date: Thu, 12 Nov 2026 16:07:25 -0600 Subject: [PATCH 3/6] fix(native): tolerate corrupt entries and harden stored value decoding Native readers skip entries they cannot decode instead of failing the whole map, and read the v2 storage format. --- resources/android/SettingsFunctions.kt | 63 +++++++++++++++++++------- resources/ios/SettingsFunctions.swift | 45 +++++++++++++++--- 2 files changed, 85 insertions(+), 23 deletions(-) diff --git a/resources/android/SettingsFunctions.kt b/resources/android/SettingsFunctions.kt index b559184..7078f79 100644 --- a/resources/android/SettingsFunctions.kt +++ b/resources/android/SettingsFunctions.kt @@ -14,8 +14,12 @@ private const val STORAGE_KEY_PREFIX = "dev.momotombo.nativephp.settings." private const val STRING_PREFIX = "mnp-settings:v1:s:" private const val DOUBLE_PREFIX = "mnp-settings:v1:d:" private const val JSON_PREFIX = "mnp-settings:v1:j:" +/** Read-only: a future writer stores any JSON value as compact JSON after this prefix. */ +private const val JSON_V2_PREFIX = "mnp-settings:v2:" private const val MAX_VALUE_BYTES = 65_536 private const val MAX_NESTING_DEPTH = 32 +/** Rejected on every platform because JavaScript treats them specially. */ +private val RESERVED_KEY_SEGMENTS = setOf("__proto__", "constructor", "prototype") /** * NativePHP bridge handlers for device-local settings. @@ -90,19 +94,30 @@ object SettingsFunctions { } } + /** Skips entries that cannot be decoded and reports their keys in `corrupt`. */ class All(private val context: Context) : BridgeFunction { override fun execute(parameters: Map): Map { val values = linkedMapOf() + val corrupt = mutableListOf() preferences(context).all.forEach { (storageKey, storedValue) -> if (storageKey.startsWith(STORAGE_KEY_PREFIX)) { val key = storageKey.removePrefix(STORAGE_KEY_PREFIX) - validateKey(key) - values[key] = decodeStoredValue(storedValue) + try { + validateKey(key) + values[key] = decodeStoredValue(storedValue) + } catch (_: Exception) { + corrupt.add(key) + } } } - return BridgeResponse.success(mapOf("values" to values)) + val data = linkedMapOf("values" to values) + if (corrupt.isNotEmpty()) { + data["corrupt"] = corrupt.sorted() + } + + return BridgeResponse.success(data) } } } @@ -116,7 +131,7 @@ private fun settingKey(parameters: Map): String { } private fun validateKey(key: String) { - if (!Regex("^[a-z0-9_]+(?:\\.[a-z0-9_]+)*$").matches(key)) { + if (!Regex("^[a-z0-9_]+(?:\\.[a-z0-9_]+)*$").matches(key) || key.split('.').any { it in RESERVED_KEY_SEGMENTS }) { invalidParameters("key must use lowercase dot notation.") } } @@ -195,18 +210,8 @@ private fun decodeStoredValue(value: Any?): Any { value.startsWith(DOUBLE_PREFIX) -> value.removePrefix(DOUBLE_PREFIX).toDoubleOrNull() ?.takeIf(Double::isFinite) ?: corruptStoredValue() - value.startsWith(JSON_PREFIX) -> { - val jsonValue = try { - val tokener = JSONTokener(value.removePrefix(JSON_PREFIX)) - val parsed = tokener.nextValue() - if (tokener.nextClean() != '\u0000') corruptStoredValue() - parsed - } catch (_: JSONException) { - corruptStoredValue() - } - if (jsonValue !is JSONObject && jsonValue !is JSONArray) corruptStoredValue() - normalizeStoredValue(jsonValue) - } + value.startsWith(JSON_PREFIX) -> decodeStoredJson(value.removePrefix(JSON_PREFIX), allowScalars = false) + value.startsWith(JSON_V2_PREFIX) -> decodeStoredJson(value.removePrefix(JSON_V2_PREFIX), allowScalars = true) else -> corruptStoredValue() } else -> corruptStoredValue() @@ -222,6 +227,32 @@ private fun decodeStoredValue(value: Any?): Any { return decoded } +/** + * Decodes v1 JSON collections and v2 JSON values (any type, including scalars). + * Both go through the same null, depth, finiteness, and size validation as writes. + */ +private fun decodeStoredJson(json: String, allowScalars: Boolean): Any { + // Reject oversized payloads before parsing; a valid value never exceeds the limit. + if (json.toByteArray(Charsets.UTF_8).size > MAX_VALUE_BYTES) corruptStoredValue() + + val parsed = try { + val tokener = JSONTokener(json) + val value = tokener.nextValue() + if (tokener.nextClean() != '\u0000') corruptStoredValue() + value + } catch (_: JSONException) { + corruptStoredValue() + } catch (_: StackOverflowError) { + // JSONTokener is recursive; deeply nested input must not crash the app. + corruptStoredValue() + } + + // JSONTokener accepts unquoted words as strings; a JSON string must be quoted. + if (parsed is String && !json.trimStart().startsWith("\"")) corruptStoredValue() + if (!allowScalars && parsed !is JSONObject && parsed !is JSONArray) corruptStoredValue() + return normalizeStoredValue(parsed) +} + private fun normalizeStoredValue(value: Any?): Any = try { normalizeValue(value) } catch (_: BridgeError) { diff --git a/resources/ios/SettingsFunctions.swift b/resources/ios/SettingsFunctions.swift index d703cdf..29643e2 100644 --- a/resources/ios/SettingsFunctions.swift +++ b/resources/ios/SettingsFunctions.swift @@ -5,8 +5,12 @@ private let storageKeyPrefix = "dev.momotombo.nativephp.settings." private let stringPrefix = "mnp-settings:v1:s:" private let doublePrefix = "mnp-settings:v1:d:" private let jsonPrefix = "mnp-settings:v1:j:" +/// Read-only: a future writer stores any JSON value as compact JSON after this prefix. +private let jsonV2Prefix = "mnp-settings:v2:" private let maxValueBytes = 65_536 private let maxNestingDepth = 32 +/// Rejected on every platform because JavaScript treats them specially. +private let reservedKeySegments: Set = ["__proto__", "constructor", "prototype"] /// NativePHP bridge handlers for device-local settings. /// Keep method names, payloads, and validation limits aligned with PHP and Android. @@ -78,19 +82,31 @@ enum SettingsFunctions { } } + /// Skips entries that cannot be decoded and reports their keys in `corrupt`. class All: BridgeFunction { func execute(parameters: [String: Any]) throws -> [String: Any] { var values: [String: Any] = [:] + var corrupt: [String] = [] let storedSettings = try persistedSettings() for (storageKey, storedValue) in storedSettings where storageKey.hasPrefix(storageKeyPrefix) { let key = String(storageKey.dropFirst(storageKeyPrefix.count)) - try validateKey(key) - values[key] = try decodeStoredValue(storedValue) + + do { + try validateKey(key) + values[key] = try decodeStoredValue(storedValue) + } catch { + corrupt.append(key) + } + } + + var data: [String: Any] = ["values": values] + if !corrupt.isEmpty { + data["corrupt"] = corrupt.sorted() } - return BridgeResponse.success(data: ["values": values]) + return BridgeResponse.success(data: data) } } } @@ -113,7 +129,8 @@ private func settingKey(_ parameters: [String: Any]) throws -> String { } private func validateKey(_ key: String) throws { - guard key.range(of: "^[a-z0-9_]+(?:\\.[a-z0-9_]+)*$", options: .regularExpression) != nil else { + guard key.range(of: "^[a-z0-9_]+(?:\\.[a-z0-9_]+)*$", options: .regularExpression) != nil, + !key.split(separator: ".").contains(where: { reservedKeySegments.contains(String($0)) }) else { throw BridgeError.invalidParameters("key must use lowercase dot notation.") } } @@ -212,14 +229,28 @@ private func decodeStoredValue(_ value: Any) throws -> Any { return try validateStoredValueSize(double) } - guard storedString.hasPrefix(jsonPrefix), - let data = String(storedString.dropFirst(jsonPrefix.count)).data(using: .utf8) else { + if storedString.hasPrefix(jsonV2Prefix) { + return try decodeStoredJSON(String(storedString.dropFirst(jsonV2Prefix.count)), allowsScalars: true) + } + + guard storedString.hasPrefix(jsonPrefix) else { + throw BridgeError.executionFailed("Stored value is malformed or unsupported.") + } + + return try decodeStoredJSON(String(storedString.dropFirst(jsonPrefix.count)), allowsScalars: false) +} + +/// Decodes v1 JSON collections and v2 JSON values (any type, including scalars). +/// Both go through the same null, depth, finiteness, and size validation as writes. +private func decodeStoredJSON(_ json: String, allowsScalars: Bool) throws -> Any { + // Reject oversized payloads before parsing; a valid value never exceeds the limit. + guard json.utf8.count <= maxValueBytes, let data = json.data(using: .utf8) else { throw BridgeError.executionFailed("Stored value is malformed or unsupported.") } do { let decoded = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) - guard decoded is [Any] || decoded is [String: Any] else { + guard allowsScalars || decoded is [Any] || decoded is [String: Any] else { throw BridgeError.executionFailed("Stored value is malformed or unsupported.") } return try validateStoredValueSize(normalizeValue(decoded)) From 460b479c4999d576dc1c57651f87340a483a8639 Mon Sep 17 00:00:00 2001 From: manuelduarte077 Date: Thu, 12 Nov 2026 16:07:25 -0600 Subject: [PATCH 4/6] feat(js): harden bridge client and add TypeScript types Bridge errors surface as SettingsBridgeError. Reserved keys are rejected. set and forget resolve undefined. Adds settings.d.ts. --- package.json | 10 +- resources/js/settings.d.ts | 78 +++++++++ resources/js/settings.js | 298 +++++++++++++++++++++++++++++---- resources/js/settings.test.mjs | 282 +++++++++++++++++++++++++++---- 4 files changed, 605 insertions(+), 63 deletions(-) create mode 100644 resources/js/settings.d.ts diff --git a/package.json b/package.json index ba1f672..853cd22 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,15 @@ "name": "@momotombo/nativephp-settings", "private": true, "type": "module", + "main": "./resources/js/settings.js", + "types": "./resources/js/settings.d.ts", + "exports": { + ".": { + "types": "./resources/js/settings.d.ts", + "default": "./resources/js/settings.js" + } + }, "scripts": { "test:js": "node --test resources/js/settings.test.mjs" } -} \ No newline at end of file +} diff --git a/resources/js/settings.d.ts b/resources/js/settings.d.ts new file mode 100644 index 0000000..33fc162 --- /dev/null +++ b/resources/js/settings.d.ts @@ -0,0 +1,78 @@ +/** A JSON-compatible value accepted by the native settings store. `null` is not a valid value; use `forget()` instead. */ +export type SettingValue = + | string + | number + | boolean + | SettingValue[] + | { [key: string]: SettingValue }; + +/** A PHP-style array: a list or a string-keyed map. */ +export type SettingArray = SettingValue[] | { [key: string]: SettingValue }; + +export type SettingsErrorCode = + | 'INVALID_KEY' + | 'INVALID_VALUE' + | 'INVALID_RESPONSE' + | 'METHOD_NOT_FOUND' + | 'FUNCTION_NOT_AVAILABLE' + | 'BRIDGE_UNAVAILABLE' + | 'BRIDGE_ERROR' + | (string & {}); + +export class SettingsBridgeError extends Error { + constructor(code: SettingsErrorCode, message: string, options?: { status?: number | null; cause?: unknown }); + readonly name: 'SettingsBridgeError'; + /** Machine-readable error code; codes reported by NativePHP or native code are passed through. */ + code: SettingsErrorCode; + /** HTTP status of the bridge response, or `null` when no response was received or the call was rejected client-side. */ + status: number | null; +} + +export interface SettingsReport { + values: Record; + /** Keys whose stored values could not be decoded and were skipped. */ + corrupt: string[]; +} + +export function set(key: string, value: SettingValue): Promise; + +export function get(key: string): Promise; +export function get(key: string, defaultValue: D): Promise; + +export function has(key: string): Promise; +export function forget(key: string): Promise; +export function all(): Promise>; +export function allWithReport(): Promise; + +export function getBool(key: string): Promise; +export function getBool(key: string, defaultValue: D): Promise; + +export function getInt(key: string): Promise; +export function getInt(key: string, defaultValue: D): Promise; + +export function getFloat(key: string): Promise; +export function getFloat(key: string, defaultValue: D): Promise; + +export function getString(key: string): Promise; +export function getString(key: string, defaultValue: D): Promise; + +export function getArray(key: string): Promise; +export function getArray(key: string, defaultValue: D): Promise; + +export interface Settings { + set: typeof set; + get: typeof get; + has: typeof has; + forget: typeof forget; + all: typeof all; + allWithReport: typeof allWithReport; + getBool: typeof getBool; + getInt: typeof getInt; + getFloat: typeof getFloat; + getString: typeof getString; + getArray: typeof getArray; +} + +export const settings: Settings; + +export default settings; diff --git a/resources/js/settings.js b/resources/js/settings.js index 335e8f5..5f0440e 100644 --- a/resources/js/settings.js +++ b/resources/js/settings.js @@ -2,47 +2,172 @@ * Local settings bridge for NativePHP Mobile. * * @example - * import { settings } from '../../vendor/momotombo/nativephp-settings/resources/js/settings.js'; + * import { settings } from '@momotombo/nativephp-settings'; * * await settings.set('app.language', 'es'); - * const language = await settings.get('app.language', 'es'); + * const language = await settings.getString('app.language', 'es'); */ const baseUrl = '/_native/api/call'; +const KEY_PATTERN = /^[a-z0-9_]+(?:\.[a-z0-9_]+)*$/; + +/** Key segments rejected on every platform because JavaScript treats them specially. */ +const RESERVED_KEY_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype']); + +/** + * Error raised for every failed settings call: invalid input, an unreachable + * bridge, an error reported by NativePHP or native code, or a response that does + * not match the settings contract. + */ +export class SettingsBridgeError extends Error { + /** + * @param {string} code Machine-readable error code, for example `INVALID_KEY`. + * @param {string} message Human-readable description. + * @param {{ status?: number | null, cause?: unknown }} [options] + */ + constructor(code, message, { status = null, cause } = {}) { + super(message, cause === undefined ? undefined : { cause }); + this.name = 'SettingsBridgeError'; + this.code = code; + this.status = status; + } +} + +function isPlainObject(value) { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + return false; + } + + const prototype = Object.getPrototypeOf(value); + + return prototype === Object.prototype || prototype === null; +} + +function assertKey(key) { + if (typeof key !== 'string' || !KEY_PATTERN.test(key) || key.split('.').some((segment) => RESERVED_KEY_SEGMENTS.has(segment))) { + throw new SettingsBridgeError('INVALID_KEY', 'Settings keys must use lowercase dot notation.'); + } +} + +function assertValue(value) { + if (value === undefined || value === null) { + throw new SettingsBridgeError('INVALID_VALUE', 'Settings values cannot be null or undefined; use forget() to remove a key.'); + } + + if (typeof value === 'number' && !Number.isFinite(value)) { + throw new SettingsBridgeError('INVALID_VALUE', 'Settings values must be finite numbers.'); + } + + if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint') { + throw new SettingsBridgeError('INVALID_VALUE', `Settings values cannot be of type ${typeof value}.`); + } +} + +function csrfToken() { + return globalThis.document?.querySelector?.('meta[name="csrf-token"]')?.content || ''; +} + +/** + * POST a call to the NativePHP bridge endpoint and return the native payload. + * + * The endpoint (`Native\Mobile\Http\Controllers\NativeCallController`) answers + * `{ status: 'success', data: }` on success, where the native + * payload is the bridge function's result returned unwrapped by + * `BridgeResponse.success`. Failures answer `{ status: 'error', code, message }` + * with HTTP 400 (missing method or native error), 404 (`METHOD_NOT_FOUND`), + * 503 (`FUNCTION_NOT_AVAILABLE`) or 500 (`EXECUTION_ERROR`). + * + * @returns {Promise<{ payload: Record, status: number | null }>} + */ async function bridgeCall(method, params = {}) { - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '' - }, - body: JSON.stringify({ method, params }) - }); + let response; - const result = await response.json(); + try { + response = await fetch(baseUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + 'X-CSRF-TOKEN': csrfToken() + }, + body: JSON.stringify({ method, params }) + }); + } catch (error) { + throw new SettingsBridgeError('BRIDGE_UNAVAILABLE', `The NativePHP bridge could not be reached for ${method}.`, { cause: error }); + } - if (!response.ok || result.status === 'error') { - throw new Error(result.message || 'Native settings call failed'); + const status = typeof response.status === 'number' ? response.status : null; + let body; + + try { + body = JSON.parse(await response.text()); + } catch (error) { + body = undefined; } - const nativeResponse = result.data; - if (nativeResponse && nativeResponse.data !== undefined) { - return nativeResponse.data; + const errorBody = isPlainObject(body) && body.status === 'error' ? body : null; + const message = typeof errorBody?.message === 'string' && errorBody.message !== '' ? errorBody.message : null; + + if (status === 404) { + throw new SettingsBridgeError('METHOD_NOT_FOUND', message ?? `${method} is not registered in the NativePHP bridge.`, { status }); + } + + if (status === 503) { + throw new SettingsBridgeError('FUNCTION_NOT_AVAILABLE', message ?? 'The NativePHP bridge is not available.', { status }); + } + + if (errorBody !== null || !response.ok) { + if (body === undefined) { + throw new SettingsBridgeError('INVALID_RESPONSE', `${method} failed with a non-JSON response.`, { status }); + } + + const code = typeof errorBody?.code === 'string' && errorBody.code !== '' ? errorBody.code : 'BRIDGE_ERROR'; + + throw new SettingsBridgeError(code, message ?? `${method} failed.`, { status }); + } + + if (!isPlainObject(body) || body.status !== 'success' || !isPlainObject(body.data)) { + throw new SettingsBridgeError('INVALID_RESPONSE', `The ${method} response does not match the NativePHP bridge contract.`, { status }); + } + + return { payload: body.data, status }; +} + +function invalidShape(method, status) { + return new SettingsBridgeError('INVALID_RESPONSE', `The ${method} response does not match the NativePHP Settings contract.`, { status }); +} + +async function acknowledgedCall(method, params) { + const { payload, status } = await bridgeCall(method, params); + + if (payload.status !== 'ok') { + throw invalidShape(method, status); + } +} + +async function lookup(key) { + assertKey(key); + const { payload, status } = await bridgeCall('Settings.Get', { key }); + + if (typeof payload.found !== 'boolean' || (payload.found && payload.value === undefined)) { + throw invalidShape('Settings.Get', status); } - return nativeResponse; + return payload; } /** * Persist a supported value for a setting key. * * @param {string} key Lowercase dot-notation key. - * @param {unknown} value Value supported by the PHP and native storage contract. - * @returns {Promise} Resolves with the NativePHP success payload. + * @param {import('./settings').SettingValue} value Non-null JSON-compatible value. + * @returns {Promise} */ export async function set(key, value) { - return bridgeCall('Settings.Set', { key, value }); + assertKey(key); + assertValue(value); + await acknowledgedCall('Settings.Set', { key, value }); } /** @@ -53,8 +178,9 @@ export async function set(key, value) { * @returns {Promise} */ export async function get(key, defaultValue = null) { - const response = await bridgeCall('Settings.Get', { key }); - return response.found ? response.value : defaultValue; + const payload = await lookup(key); + + return payload.found ? payload.value : defaultValue; } /** @@ -64,30 +190,142 @@ export async function get(key, defaultValue = null) { * @returns {Promise} */ export async function has(key) { - const response = await bridgeCall('Settings.Has', { key }); - return response.found; + assertKey(key); + const { payload, status } = await bridgeCall('Settings.Has', { key }); + + if (typeof payload.found !== 'boolean') { + throw invalidShape('Settings.Has', status); + } + + return payload.found; } /** * Remove a setting; removing a missing key succeeds. * * @param {string} key Lowercase dot-notation key. - * @returns {Promise} Resolves with the NativePHP success payload. + * @returns {Promise} */ export async function forget(key) { - return bridgeCall('Settings.Forget', { key }); + assertKey(key); + await acknowledgedCall('Settings.Forget', { key }); } /** - * Return every stored setting as an object keyed by setting key. + * Return every readable setting plus the keys whose stored values are corrupt. + * + * @returns {Promise<{ values: Record, corrupt: string[] }>} + */ +export async function allWithReport() { + const { payload, status } = await bridgeCall('Settings.All'); + const values = normalizeValuesMap(payload.values); + + if (values === null) { + throw invalidShape('Settings.All', status); + } + + const corrupt = payload.corrupt ?? []; + + if (!Array.isArray(corrupt) || !corrupt.every((key) => typeof key === 'string')) { + throw invalidShape('Settings.All', status); + } + + return { values, corrupt }; +} + +/** + * NativeCallController decodes the native payload into a PHP array and + * re-encodes it, so a map whose keys are `"0"`, `"1"`, … (including the empty + * map of a fresh install) arrives as a JSON list. Rebuild the map from the list. + * + * @returns {Record | null} `null` when the value is neither a map nor a list. + */ +function normalizeValuesMap(values) { + if (isPlainObject(values)) { + return values; + } + + if (Array.isArray(values)) { + return Object.fromEntries(values.map((value, index) => [String(index), value])); + } + + return null; +} + +/** + * Return every readable setting as an object keyed by setting key. * * @returns {Promise>} */ export async function all() { - const response = await bridgeCall('Settings.All'); - return response.values; + return (await allWithReport()).values; +} + +async function typedGet(key, defaultValue, matches) { + const payload = await lookup(key); + + return payload.found && matches(payload.value) ? payload.value : defaultValue; +} + +/** + * @param {string} key + * @param {boolean} [defaultValue=false] Returned when the key is absent or not a boolean. + * @returns {Promise} + */ +export async function getBool(key, defaultValue = false) { + return typedGet(key, defaultValue, (value) => typeof value === 'boolean'); +} + +/** + * @param {string} key + * @param {number} [defaultValue=0] Returned when the key is absent or not an integer. + * @returns {Promise} + */ +export async function getInt(key, defaultValue = 0) { + return typedGet(key, defaultValue, (value) => Number.isInteger(value)); +} + +/** + * @param {string} key + * @param {number} [defaultValue=0] Returned when the key is absent or not a number; integers are accepted. + * @returns {Promise} + */ +export async function getFloat(key, defaultValue = 0) { + return typedGet(key, defaultValue, (value) => typeof value === 'number' && Number.isFinite(value)); +} + +/** + * @param {string} key + * @param {string} [defaultValue=''] Returned when the key is absent or not a string. + * @returns {Promise} + */ +export async function getString(key, defaultValue = '') { + return typedGet(key, defaultValue, (value) => typeof value === 'string'); +} + +/** + * Return a stored list or map (a PHP array). + * + * @param {string} key + * @param {unknown[] | Record} [defaultValue=[]] Returned when the key is absent or not a list/map. + * @returns {Promise>} + */ +export async function getArray(key, defaultValue = []) { + return typedGet(key, defaultValue, (value) => Array.isArray(value) || isPlainObject(value)); } -export const settings = { set, get, has, forget, all }; +export const settings = { + set, + get, + has, + forget, + all, + allWithReport, + getBool, + getInt, + getFloat, + getString, + getArray +}; export default settings; diff --git a/resources/js/settings.test.mjs b/resources/js/settings.test.mjs index 19b1dc7..906d599 100644 --- a/resources/js/settings.test.mjs +++ b/resources/js/settings.test.mjs @@ -1,8 +1,27 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import settings, { all, forget, get, has, set } from './settings.js'; +import settings, { + SettingsBridgeError, + all, + allWithReport, + forget, + get, + getArray, + getBool, + getFloat, + getInt, + getString, + has, + set +} from './settings.js'; +/** + * Replace global fetch/document for one test. Each queued response is one of: + * - an Error: fetch rejects with it (network failure); + * - { status?, text }: a raw body string; + * - { status?, body }: a JSON-encoded body. + */ function fakeBridge(t, responses) { const originalFetch = globalThis.fetch; const originalDocument = globalThis.document; @@ -24,13 +43,13 @@ function fakeBridge(t, responses) { throw response; } - if (response instanceof Function) { - return response(url, options); - } + const status = response.status ?? 200; + const text = response.text ?? JSON.stringify(response.body); return { - ok: response.ok ?? true, - json: async () => response.body + ok: status >= 200 && status < 300, + status, + text: async () => text }; }; @@ -51,21 +70,37 @@ function fakeBridge(t, responses) { return calls; } +/** Wrap a native payload the way NativeCallController does on success. */ +function ok(data) { + return { body: { status: 'success', data } }; +} + +function bridgeError(code, status = null) { + return (error) => { + assert.ok(error instanceof SettingsBridgeError, `expected SettingsBridgeError, got ${error}`); + assert.ok(error instanceof Error); + assert.equal(error.name, 'SettingsBridgeError'); + assert.equal(error.code, code); + assert.equal(error.status, status); + + return true; + }; +} + test('exports the same API through named, object, and default exports', () => { - assert.equal(settings.set, set); - assert.equal(settings.get, get); - assert.equal(settings.has, has); - assert.equal(settings.forget, forget); - assert.equal(settings.all, all); + for (const [name, fn] of Object.entries({ set, get, has, forget, all, allWithReport, getBool, getInt, getFloat, getString, getArray })) { + assert.equal(settings[name], fn, name); + } }); -test('sends a set operation to the NativePHP bridge with its CSRF token', async (t) => { - const calls = fakeBridge(t, [{ body: { status: 'ok', data: { saved: true } } }]); +test('sends a set operation to the NativePHP bridge with its CSRF token and resolves undefined', async (t) => { + const calls = fakeBridge(t, [ok({ status: 'ok' })]); - assert.deepEqual(await set('profile.name', 'Ana'), { saved: true }); + assert.equal(await set('profile.name', 'Ana'), undefined); assert.equal(calls[0].url, '/_native/api/call'); assert.equal(calls[0].options.method, 'POST'); assert.equal(calls[0].options.headers['Content-Type'], 'application/json'); + assert.equal(calls[0].options.headers.Accept, 'application/json'); assert.equal(calls[0].options.headers['X-CSRF-TOKEN'], 'csrf-token-value'); assert.deepEqual(JSON.parse(calls[0].options.body), { method: 'Settings.Set', @@ -75,25 +110,27 @@ test('sends a set operation to the NativePHP bridge with its CSRF token', async test('preserves false and zero values and returns defaults for missing settings', async (t) => { fakeBridge(t, [ - { body: { data: { found: true, value: false } } }, - { body: { data: { found: true, value: 0 } } }, - { body: { data: { found: false } } } + ok({ found: true, value: false }), + ok({ found: true, value: 0 }), + ok({ found: false }), + ok({ found: false }) ]); assert.equal(await get('feature.enabled', true), false); assert.equal(await get('layout.columns', 4), 0); assert.equal(await get('app.language', 'es'), 'es'); + assert.equal(await get('app.language'), null); }); test('checks existence, forgets keys, and returns all stored values', async (t) => { const calls = fakeBridge(t, [ - { body: { data: { found: true } } }, - { body: { status: 'ok', data: { removed: true } } }, - { body: { data: { values: { 'app.language': 'es', 'feature.enabled': false } } } } + ok({ found: true }), + ok({ status: 'ok' }), + ok({ values: { 'app.language': 'es', 'feature.enabled': false } }) ]); assert.equal(await has('feature.enabled'), true); - assert.deepEqual(await forget('feature.enabled'), { removed: true }); + assert.equal(await forget('feature.enabled'), undefined); assert.deepEqual(await all(), { 'app.language': 'es', 'feature.enabled': false }); assert.deepEqual(calls.map(({ options }) => JSON.parse(options.body).method), [ 'Settings.Has', @@ -102,17 +139,198 @@ test('checks existence, forgets keys, and returns all stored values', async (t) ]); }); -test('rejects native error responses, failed HTTP responses, malformed JSON, and network errors', async (t) => { - const bridge = fakeBridge(t, [ - { body: { status: 'error', message: 'Storage is unavailable.' } }, - { ok: false, body: { message: 'Request rejected.' } }, - () => ({ ok: true, json: async () => { throw new SyntaxError('Malformed JSON'); } }), - new Error('Network unavailable.') +test('allWithReport exposes corrupt keys and defaults them to an empty list', async (t) => { + fakeBridge(t, [ + ok({ values: { 'app.language': 'es' }, corrupt: ['broken.key'] }), + ok({ values: {} }), + ok({ values: { 'app.language': 'es' }, corrupt: ['broken.key'] }) + ]); + + assert.deepEqual(await allWithReport(), { values: { 'app.language': 'es' }, corrupt: ['broken.key'] }); + assert.deepEqual(await allWithReport(), { values: {}, corrupt: [] }); + assert.deepEqual(await all(), { 'app.language': 'es' }); +}); + +test('maps a non-JSON body to INVALID_RESPONSE', async (t) => { + fakeBridge(t, [ + { text: 'Server Error' }, + { status: 500, text: 'Server Error' } + ]); + + await assert.rejects(get('app.value'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(get('app.value'), bridgeError('INVALID_RESPONSE', 500)); +}); + +test('maps HTTP 404 to METHOD_NOT_FOUND, keeping the bridge message', async (t) => { + fakeBridge(t, [ + { status: 404, body: { status: 'error', code: 'METHOD_NOT_FOUND', message: "Method 'Settings.Get' is not registered in the bridge registry" } }, + { status: 404, text: 'Not Found' } + ]); + + await assert.rejects(get('app.value'), (error) => { + bridgeError('METHOD_NOT_FOUND', 404)(error); + assert.match(error.message, /not registered/); + + return true; + }); + await assert.rejects(get('app.value'), bridgeError('METHOD_NOT_FOUND', 404)); +}); + +test('maps HTTP 503 to FUNCTION_NOT_AVAILABLE', async (t) => { + fakeBridge(t, [ + { status: 503, body: { status: 'error', code: 'FUNCTION_NOT_AVAILABLE', message: 'nativephp_call function is not available' } } + ]); + + await assert.rejects(has('app.value'), bridgeError('FUNCTION_NOT_AVAILABLE', 503)); +}); + +test('maps a network failure to BRIDGE_UNAVAILABLE with the original cause', async (t) => { + const networkError = new TypeError('Failed to fetch'); + fakeBridge(t, [networkError]); + + await assert.rejects(all(), (error) => { + bridgeError('BRIDGE_UNAVAILABLE', null)(error); + assert.equal(error.cause, networkError); + + return true; + }); +}); + +test('passes through error codes and messages from status:error bodies', async (t) => { + fakeBridge(t, [ + { status: 400, body: { status: 'error', code: 'EXECUTION_FAILED', message: 'Storage is unavailable.', data: {} } }, + { status: 500, body: { status: 'error', code: 'EXECUTION_ERROR', message: 'Boom.' } }, + { status: 422, body: { message: 'Request rejected.' } } + ]); + + await assert.rejects(set('app.value', 'x'), (error) => { + bridgeError('EXECUTION_FAILED', 400)(error); + assert.equal(error.message, 'Storage is unavailable.'); + + return true; + }); + await assert.rejects(forget('app.value'), bridgeError('EXECUTION_ERROR', 500)); + await assert.rejects(get('app.value'), bridgeError('BRIDGE_ERROR', 422)); +}); + +test('rejects responses that do not match the bridge or settings contract', async (t) => { + fakeBridge(t, [ + { body: { status: 'success', data: null } }, + { body: { status: 'success', data: 'raw native string' } }, + { body: { found: true, value: 1 } }, + { body: { status: 'success', data: { data: { found: true, value: 1 } } } }, + ok({ found: 'yes' }), + ok({ found: true }), + ok({}), + ok({ status: 'saved' }), + ok({}), + ok({ values: 'not-a-map' }), + ok({ values: {}, corrupt: 'broken.key' }) + ]); + + await assert.rejects(get('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(get('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(get('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(get('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(get('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(get('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(has('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(set('a', 1), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(forget('a'), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(all(), bridgeError('INVALID_RESPONSE', 200)); + await assert.rejects(allWithReport(), bridgeError('INVALID_RESPONSE', 200)); +}); + +test('rejects invalid keys before calling the bridge', async (t) => { + const calls = fakeBridge(t, []); + + for (const key of ['', 'App.Language', 'app..language', '.app', 'app.', 'app-language', 'app language', 'app.language\n', '__proto__', 'app.__proto__.polluted', 'constructor', 'app.prototype', 42, undefined]) { + await assert.rejects(get(key), bridgeError('INVALID_KEY', null), String(key)); + } + + await assert.rejects(set('Bad', 'x'), bridgeError('INVALID_KEY', null)); + await assert.rejects(has('Bad'), bridgeError('INVALID_KEY', null)); + await assert.rejects(forget('Bad'), bridgeError('INVALID_KEY', null)); + await assert.rejects(getBool('Bad'), bridgeError('INVALID_KEY', null)); + assert.equal(calls.length, 0); +}); + +test('rejects null, undefined, and non-JSON values before calling the bridge', async (t) => { + const calls = fakeBridge(t, []); + + for (const value of [null, undefined, Number.NaN, Number.POSITIVE_INFINITY, () => 1, Symbol('x'), 1n]) { + await assert.rejects(set('app.value', value), bridgeError('INVALID_VALUE', null), String(value?.toString?.() ?? value)); + } + + assert.equal(calls.length, 0); +}); + +test('typed getters return the stored value when the type matches and the default otherwise', async (t) => { + fakeBridge(t, [ + ok({ found: true, value: false }), + ok({ found: true, value: 'true' }), + ok({ found: false }), + ok({ found: true, value: 3 }), + ok({ found: true, value: 3.5 }), + ok({ found: true, value: '3' }), + ok({ found: true, value: 2.5 }), + ok({ found: true, value: 2 }), + ok({ found: true, value: '2.5' }), + ok({ found: true, value: '' }), + ok({ found: true, value: 7 }), + ok({ found: true, value: [1, 2] }), + ok({ found: true, value: { theme: 'dark' } }), + ok({ found: true, value: 'list' }), + ok({ found: false }) + ]); + + assert.equal(await getBool('a', true), false); + assert.equal(await getBool('a', true), true); + assert.equal(await getBool('a'), false); + + assert.equal(await getInt('a', 9), 3); + assert.equal(await getInt('a', 9), 9); + assert.equal(await getInt('a', 9), 9); + + assert.equal(await getFloat('a', 9), 2.5); + assert.equal(await getFloat('a', 9), 2); + assert.equal(await getFloat('a', 9), 9); + + assert.equal(await getString('a', 'x'), ''); + assert.equal(await getString('a', 'x'), 'x'); + + assert.deepEqual(await getArray('a', ['d']), [1, 2]); + assert.deepEqual(await getArray('a', ['d']), { theme: 'dark' }); + assert.deepEqual(await getArray('a', ['d']), ['d']); + assert.deepEqual(await getArray('a'), []); +}); + +test('works without a document (no CSRF meta tag available)', async (t) => { + const calls = fakeBridge(t, [ok({ found: false })]); + delete globalThis.document; + + assert.equal(await has('app.value'), false); + assert.equal(calls[0].options.headers['X-CSRF-TOKEN'], ''); +}); + +test('accepts reserved words inside a longer key segment', async (t) => { + fakeBridge(t, [ok({ status: 'ok' }), ok({ status: 'ok' })]); + + assert.equal(await set('app.constructor_name', 'x'), undefined); + assert.equal(await set('proto.prototypes', 'x'), undefined); +}); + +test('accepts the list shape NativeCallController produces for empty and index-keyed maps', async (t) => { + // Real response bodies: PHP json_decode(assoc) + response()->json() turn {} into [] and {"0": …} into [ … ]. + fakeBridge(t, [ + { text: '{"status":"success","data":{"values":[]}}' }, + { text: '{"status":"success","data":{"values":[]}}' }, + { text: '{"status":"success","data":{"values":[],"corrupt":["broken.key"]}}' }, + { text: '{"status":"success","data":{"values":["zero","one"]}}' } ]); - await assert.rejects(set('app.value', 'x'), /Storage is unavailable/); - await assert.rejects(get('app.value'), /Request rejected/); - await assert.rejects(has('app.value'), /Malformed JSON/); - await assert.rejects(all(), /Network unavailable/); - assert.equal(bridge.length, 4); + assert.deepEqual(await all(), {}); + assert.deepEqual(await allWithReport(), { values: {}, corrupt: [] }); + assert.deepEqual(await allWithReport(), { values: {}, corrupt: ['broken.key'] }); + assert.deepEqual(await all(), { 0: 'zero', 1: 'one' }); }); From 90dd73e875dcefb1c7201078ac735d1fd66636eb Mon Sep 17 00:00:00 2001 From: manuelduarte077 Date: Thu, 12 Nov 2026 16:07:30 -0600 Subject: [PATCH 5/6] chore: add CI, license, changelog and package metadata Adds CI with actions pinned by SHA, LICENSE and CHANGELOG. Removes the no-op copy_assets hook and its command. --- .github/dependabot.yml | 6 + .github/workflows/tests.yml | 55 +++++ .gitignore | 5 +- CHANGELOG.md | 58 +++++ LICENSE | 21 ++ README.md | 219 +++++++++++++--- composer.json | 38 ++- nativephp.json | 17 +- phpunit.xml.dist | 18 ++ resources/boost/guidelines/core.blade.php | 44 +++- src/Commands/CopyAssetsCommand.php | 25 -- tests/PluginTest.php | 288 ++++++++-------------- 12 files changed, 534 insertions(+), 260 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/tests.yml create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 phpunit.xml.dist delete mode 100644 src/Commands/CopyAssetsCommand.php diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ca79ca5 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..262c1cf --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,55 @@ +name: tests + +on: + push: + branches: [main, develop] + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + php: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php: ['8.3', '8.4', '8.5'] + + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ matrix.php }} + extensions: dom, simplexml, mbstring, json + coverage: none + + - name: Install dependencies + run: composer update --prefer-dist --no-interaction --no-progress + + - name: Run tests + run: vendor/bin/pest + + - name: Check code style + run: vendor/bin/pint --test + + javascript: + name: JavaScript + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: '22' + + - name: Run tests + run: npm run test:js diff --git a/.gitignore b/.gitignore index 4deac1a..b226a1f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ /vendor/ /node_modules/ .DS_Store -*.log \ No newline at end of file +*.log +/composer.lock +/.phpunit.cache/ +/.phpunit.result.cache diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f25f155 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,58 @@ +# Changelog + +All notable changes to `momotombo/nativephp-settings` are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.1.0] - Unreleased + +### Added + +- `Settings::fake(array $initial = [])` for tests, returning a `SettingsFake` with `assertSet()`, `assertForgotten()`, and `assertNothingSet()`. Keys and values are still validated while faked. +- Storage drivers behind a new `SettingsStore` contract: `native` (UserDefaults / SharedPreferences), `file` (JSON file with locked, atomic writes), and `array` (in memory). +- `config/nativephp-settings.php` (publish with `--tag=nativephp-settings-config`) with `driver` (`NATIVE_SETTINGS_DRIVER`, default `auto`), `file_path`, and `strict` (`NATIVE_SETTINGS_STRICT`). +- `auto` driver. On a device, native storage is always used and any other configured driver is ignored with a one-time warning, because `.env` ships inside the app build. Off the device: a custom bound `SettingsBridge` is used as before; unit tests (including those using NativePHP's `FakeBridge`) use an in-memory store; `native:jump` uses native storage when the bridge reports the settings functions, otherwise a file; the `local` and `testing` environments use a JSON file. +- `Settings::allWithReport()` returns the readable values plus the keys that were skipped. +- Typed getters: `getBool()`, `getInt()`, `getFloat()` (also accepts stored whole numbers), `getString()`, `getArray()` (lists and maps), and `getEnum()` (rehydrates backed enum cases). A type mismatch returns the default and logs the key, or throws `SettingTypeMismatch` when `strict` is enabled. +- `SettingsCorrupted` event, dispatched with the keys `Settings::all()` had to skip. +- The file store refuses files over 8 MiB, keeps file permissions on write, and renames a corrupt file to `.corrupt-` before replacing it. +- Native decoders reject oversized stored JSON before parsing it, and Android maps a stack overflow from deeply nested stored JSON to a corrupt entry instead of crashing. +- Native decoders read the future `mnp-settings:v2:` storage format (any JSON value), so data written by 2.x stays readable after a downgrade. Writes still use the 1.x format. +- JavaScript: `SettingsBridgeError` (with `code` and `status`), typed getters (`getBool`, `getInt`, `getFloat`, `getString`, `getArray`), `allWithReport()` exposing corrupt keys, `settings.d.ts` TypeScript types, `exports`/`types` in `package.json`, and import through a Vite alias. +- `LICENSE`, this changelog, a GitHub Actions workflow, and Orchestra Testbench-based package tests. + +### Changed + +- **Behavior change:** `Settings::all()` and the native `Settings.All` functions skip entries with an invalid key or an unreadable value instead of failing the whole read. Native code reports skipped keys in an optional `corrupt` list. Reading a single corrupt key with `get()` still throws `SettingsBridgeException`. +- `Settings` accepts a `SettingsStore` (passing a `SettingsBridge` still works). +- JavaScript: `set()` and `forget()` resolve `undefined` instead of the raw bridge payload; every rejection is a `SettingsBridgeError` (extends `Error`); invalid keys and `null` or non-finite values are rejected before any request; `all()` ignores corrupt entries (use `allWithReport()`); double-wrapped `{data: {data: …}}` responses, which cannot occur on nativephp/mobile ^4.5, are rejected. +- Keys with a `__proto__`, `constructor`, or `prototype` segment are rejected in PHP, Swift, Kotlin, and JavaScript, because those names are special in JavaScript objects. A segment such as `constructor_name` is still allowed. +- Outside a NativePHP runtime in environments other than `local` and `testing`, calls still throw `SettingsBridgeException` (`BRIDGE_UNAVAILABLE`) immediately, without trying to reach a device. +- Type-mismatch warnings from typed getters are logged once per key per process. +- JavaScript: `all()` and `allWithReport()` accept the list shape NativePHP's HTTP bridge produces for an empty or index-keyed map, so a fresh install no longer fails with `INVALID_RESPONSE`. +- Requires PHP `^8.3`, matching `nativephp/mobile` ^4.5. + +### Removed + +- The `copy_assets` manifest hook. The plugin ships no assets. +- The `nativephp:settings:copy-assets` Artisan command. It was the no-op command behind that hook; remove any scripts that call it. + +### Upgrading + +- Nothing is required to upgrade from 1.0. If code relied on `Settings::all()` throwing for corrupt data, use `allWithReport()` or listen for `SettingsCorrupted` instead. +- Off the device, the `local` and `testing` environments now store settings in `storage/app/nativephp-settings.json` instead of failing; other environments still fail with `BRIDGE_UNAVAILABLE`. Set `NATIVE_SETTINGS_DRIVER` explicitly to choose otherwise. +- Tests that script `Settings.*` responses on NativePHP's `FakeBridge` now get an in-memory store under the default `auto` driver. Set `config(['nativephp-settings.driver' => 'native'])` in those tests, or switch them to `Settings::fake()`. +- Keys with a `__proto__`, `constructor`, or `prototype` segment now throw `InvalidArgumentException`. Existing entries under such keys are reported as corrupt by `all()`. +- Prefer `Settings::fake()` over scripting `Settings.*` responses on NativePHP's `FakeBridge`. Version 2.0 is planned to change the bridge wire format, and tests written against `Settings::fake()` will keep working. + +## [1.0.0] - 2026-10-02 + +### Added + +- `Settings` facade with `set()`, `get()`, `has()`, `forget()`, and `all()` for device-local preferences. +- iOS (UserDefaults) and Android (SharedPreferences) bridge functions with identical key and value validation. +- JavaScript module for Vue, React, and Inertia frontends. + +[1.1.0]: https://github.com/momotombodevs/nativephp-settings/compare/v1.0.0...HEAD +[1.0.0]: https://github.com/momotombodevs/nativephp-settings/releases/tag/v1.0.0 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a084d9b --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Momotombo + +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/README.md b/README.md index c53075a..3461207 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,18 @@ # NativePHP Settings +[![Latest Version on Packagist](https://img.shields.io/packagist/v/momotombo/nativephp-settings.svg)](https://packagist.org/packages/momotombo/nativephp-settings) +[![Total Downloads](https://img.shields.io/packagist/dt/momotombo/nativephp-settings.svg)](https://packagist.org/packages/momotombo/nativephp-settings) +[![Tests](https://github.com/momotombodevs/nativephp-settings/actions/workflows/tests.yml/badge.svg)](https://github.com/momotombodevs/nativephp-settings/actions/workflows/tests.yml) +[![License](https://img.shields.io/packagist/l/momotombo/nativephp-settings.svg)](LICENSE) + Device-local settings for NativePHP Mobile applications. Use it for small user preferences such as language, appearance, onboarding state, notification options, recent searches, and UI filters. Settings are stored on the current device and are not synchronized with a server. Do not use this package for credentials, payment data, authentication state, or server-authoritative data. ## Requirements -- PHP `^8.2` +- PHP `^8.3` - NativePHP Mobile `^4.5` -- Composer - Android and/or iOS support in the consuming NativePHP application ## Installation @@ -19,11 +23,10 @@ php artisan vendor:publish --tag=nativephp-plugins-provider php artisan native:plugin:register momotombo/nativephp-settings ``` -Confirm that NativePHP sees the plugin: +The `vendor:publish` step creates `app/Providers/NativeServiceProvider.php` the first time you install a plugin; it is safe to run again. Confirm that NativePHP sees the plugin: ```bash php artisan native:plugin:list -php artisan native:plugin:validate ``` Rebuild the native application after installing the plugin or changing native code: @@ -33,6 +36,12 @@ php artisan native:run android php artisan native:run ios ``` +Optionally publish the configuration file: + +```bash +php artisan vendor:publish --tag=nativephp-settings-config +``` + ## PHP usage ```php @@ -53,31 +62,176 @@ Settings::forget('app.language'); | --- | --- | | `Settings::set(string $key, mixed $value): void` | Store or replace a value. | | `Settings::get(string $key, mixed $default = null): mixed` | Read a value, or return the default when the key is absent. The default is not stored. | -| `Settings::has(string $key): bool` | Check whether a key exists. | +| `Settings::has(string $key): bool` | Check whether a key exists, including when its value is `false` or `0`. | | `Settings::forget(string $key): void` | Remove a value. Removing a missing key succeeds. | -| `Settings::all(): array` | Return all stored values. | +| `Settings::all(): array` | Return all readable values. See [Corrupt entries](#corrupt-entries). | +| `Settings::allWithReport(): array` | Return `['values' => [...], 'corrupt' => [...]]`, including the keys that could not be read. | +| `Settings::getBool(string $key, bool $default): bool` | Typed read. | +| `Settings::getInt(string $key, int $default): int` | Typed read. | +| `Settings::getFloat(string $key, float $default): float` | Typed read. Whole numbers are accepted and cast. | +| `Settings::getString(string $key, string $default): string` | Typed read. | +| `Settings::getArray(string $key, array $default): array` | Typed read. Lists and maps are accepted. | +| `Settings::getEnum(string $key, BackedEnum $default): BackedEnum` | Returns the matching case of the default's enum. | -Calls require a NativePHP runtime. Outside the runtime, bridge failures, native storage failures, and malformed native responses throw `SettingsBridgeException`. +Calls require a NativePHP runtime, except in the `local` and `testing` environments, where settings fall back to a local file (see [Storage drivers](#storage-drivers)). Elsewhere, calls outside a runtime throw `SettingsBridgeException` with the `BRIDGE_UNAVAILABLE` code. Storage failures and malformed native responses also throw `SettingsBridgeException`. Invalid keys and values throw `InvalidArgumentException`. -## JavaScript usage +### Typed getters -The package includes an ES module for Vue, React, Inertia, and other Vite-based frontends. It is installed through Composer and does not publish an npm package. +Typed getters return the default when the key is missing or the stored value has another type, so a preference written by an older app version never breaks a screen: -From an app entry point such as `resources/js/app.js`: +```php +enum Theme: string +{ + case Light = 'light'; + case Dark = 'dark'; +} + +$columns = Settings::getInt('layout.columns', 3); +$scale = Settings::getFloat('display.scale', 1.0); +$theme = Settings::getEnum('appearance.theme', Theme::Light); +``` -```js -import { settings } from '../../vendor/momotombo/nativephp-settings/resources/js/settings.js'; +A mismatch is logged as a warning with the key and the expected type, never the value. Set `NATIVE_SETTINGS_STRICT=true` (or `strict` in the config file) to throw `SettingTypeMismatch` instead, which is useful while developing. + +`getFloat()` accepts whole numbers because on a device a whole-number float such as `2.0` comes back as the integer `2`. The file store keeps `2.0` as a float, so `getInt()` on that value returns the default locally (or throws in strict mode) but the integer on a device. Store whole numbers as `int` to avoid the difference. -await settings.set('app.language', 'es'); +### Corrupt entries -const language = await settings.get('app.language', 'en'); -const enabled = await settings.has('notifications.enabled'); -const all = await settings.all(); +`Settings::all()` skips entries it cannot read (for example a value written by hand or by another tool) and returns everything else. The skipped keys are logged as a warning (once per read, without values) and reported through the `SettingsCorrupted` event. Use `allWithReport()` to get them directly, for example to clean them up: -await settings.forget('app.language'); +```php +['values' => $values, 'corrupt' => $corrupt] = Settings::allWithReport(); + +foreach ($corrupt as $key) { + try { + Settings::forget($key); + } catch (InvalidArgumentException) { + // Keys outside dot notation cannot be addressed through the API. + } +} ``` -The module also exports the individual `set`, `get`, `has`, `forget`, and `all` functions. Each function returns a promise, and native validation failures reject that promise. +Or listen for the event: + +```php +use Illuminate\Support\Facades\Event; +use Momotombo\NativephpSettings\Events\SettingsCorrupted; + +Event::listen(function (SettingsCorrupted $event): void { + logger()->notice('Unreadable settings skipped.', ['keys' => $event->keys]); +}); +``` + +Reading one corrupt key with `get()` still throws `SettingsBridgeException`. + +## Storage drivers + +The `driver` option (`NATIVE_SETTINGS_DRIVER`) selects where settings live off the device: + +| Driver | Storage | +| --- | --- | +| `auto` (default) | See below. | +| `native` | UserDefaults on iOS, SharedPreferences on Android, through the NativePHP bridge. | +| `file` | A JSON file, `storage/app/nativephp-settings.json` by default (`NATIVE_SETTINGS_FILE_PATH`). | +| `array` | In memory, for the current PHP process only. | + +**On a device, native storage is always used and the driver option is ignored** (a warning is logged once if it says otherwise). Your `.env` ships inside the app build, so a development value such as `NATIVE_SETTINGS_DRIVER=file` must never split PHP and JavaScript storage on a phone. + +Off the device, `auto` resolves to: + +- `native` when your app binds its own `SettingsBridge` implementation; +- `array` in unit tests, including tests that use NativePHP's `Native::visit()` or `Native::fakeBridge()` (set the driver to `native` in a test to exercise the bridge); +- `native` under `native:jump` when the bridge reports the settings functions, otherwise `file` with a warning; +- `file` in the `local` and `testing` environments; +- otherwise nothing: every call throws `SettingsBridgeException` (`BRIDGE_UNAVAILABLE`), as in 1.0. + +`native:jump` relays bridge calls to the Jump app, which does not include third-party plugins. If settings calls fail under Jump, set `NATIVE_SETTINGS_DRIVER=file` in your local `.env`; the setting is ignored in device builds. + +The store is resolved once per application instance. In a test, change the driver before the first settings call, or call `app()->forgetInstance()` for `SettingsStore` and `Settings` afterwards. `Settings::fake()` always replaces the store. + +The file store locks writes and replaces the file atomically, keeping the file's permissions (0644 for a new file). A file that is not valid JSON, is nested too deeply, or exceeds 8 MiB is treated as empty and renamed to `.corrupt-` before the next write. + +## Testing + +Replace settings storage with an in-memory fake: + +```php +use Momotombo\NativephpSettings\Facades\Settings; + +it('saves the selected language', function () { + $settings = Settings::fake(['app.language' => 'es']); + + Native::visit('/settings') + ->set('language', 'English') + ->tap('save-settings'); + + $settings->assertSet('app.language', 'en'); + $settings->assertForgotten('profile.display_name'); +}); +``` + +| Assertion | Passes when | +| --- | --- | +| `assertSet(string $key)` | The key was written at least once. | +| `assertSet(string $key, mixed $value)` | The key was written with that value (string-backed enums compare by value). | +| `assertForgotten(string $key)` | The key was forgotten. | +| `assertNothingSet()` | No key was written. | + +Initial values passed to `fake()` are validated but do not count as writes. The fake still validates keys and values, so a test fails on the same input a device would reject. + +## JavaScript usage + +The package ships an ES module with TypeScript types. Point a Vite alias at the vendored copy: + +```js +// vite.config.js +import path from 'node:path'; + +export default { + resolve: { + alias: { + '@momotombo/nativephp-settings': path.resolve(__dirname, 'vendor/momotombo/nativephp-settings/resources/js/settings.js'), + }, + }, +}; +``` + +```js +import { settings, SettingsBridgeError } from '@momotombo/nativephp-settings'; + +await settings.set('app.language', 'es'); // resolves undefined +const language = await settings.getString('app.language', 'en'); +const columns = await settings.getInt('layout.columns', 3); +const enabled = await settings.getBool('feature.enabled'); // false when missing or not a boolean +const value = await settings.get('profile.name', null); // untyped +await settings.has('feature.enabled'); // true even when the value is false or 0 +await settings.forget('feature.enabled'); // forgetting a missing key succeeds + +const values = await settings.all(); +const { values: readable, corrupt } = await settings.allWithReport(); // corrupt: keys whose stored value could not be read + +try { + await settings.set('Bad Key', 'x'); +} catch (error) { + if (error instanceof SettingsBridgeError) { + console.warn(error.code, error.status, error.message); + } +} +``` + +Typed getters (`getBool`, `getInt`, `getFloat`, `getString`, `getArray`) return the default when the key is missing or the stored type does not match. `getFloat` also accepts whole numbers. `getArray` accepts lists and maps. `all()` and `allWithReport()` always return an object, even when NativePHP's HTTP bridge delivers the stored settings as an empty or index-keyed list. + +Every failure rejects with a `SettingsBridgeError` (`code`, `status` for the HTTP status or `null`, `message`): + +| Code | When | +|------|------| +| `INVALID_KEY` | Key is not lowercase dot notation; no request is sent | +| `INVALID_VALUE` | Value is `null`, `undefined`, a non-finite number, or not JSON-compatible; use `forget()` to remove a key | +| `BRIDGE_UNAVAILABLE` | The request to `/_native/api/call` could not be made | +| `METHOD_NOT_FOUND` | HTTP 404: the plugin is not registered or the native build is stale (rebuild the app) | +| `FUNCTION_NOT_AVAILABLE` | HTTP 503: not running inside a NativePHP runtime | +| `INVALID_RESPONSE` | Non-JSON body or a response that does not match the settings contract | +| other | Codes reported by NativePHP or native code are passed through (`BRIDGE_ERROR` if none) | ## Keys and values @@ -91,7 +245,7 @@ onboarding.completed search.recent_queries ``` -Keys contain non-empty ASCII segments made of lowercase letters, digits, or underscores, separated by single dots. Uppercase letters, whitespace, punctuation, and empty segments are rejected. +Keys contain non-empty ASCII segments made of lowercase letters, digits, or underscores, separated by single dots. Uppercase letters, whitespace, punctuation, and empty segments are rejected, as are the segments `__proto__`, `constructor`, and `prototype` (they are special in JavaScript objects). Supported stored values are: @@ -104,25 +258,28 @@ Supported stored values are: `null`, closures, resources, arbitrary objects, integer-backed enums, non-finite floats, invalid UTF-8, and unsupported nested values are rejected. Collections may be nested up to 32 levels. Each value's compact UTF-8 JSON representation is limited to 65,536 bytes (64 KiB). +Values pass through PHP arrays, so an empty map (`{}`) is read back as an empty list (`[]`), and a map whose keys are `"0"`, `"1"`, … is read back as a list. Treat both shapes as equivalent, or avoid empty and index-keyed maps. + ## Platform behavior -The same API and validation rules are implemented on Android and iOS. Values survive application restarts and are scoped to the local app installation. This package does not provide secure storage; use a dedicated Keychain/Keystore-backed solution for secrets. +The same API and validation rules are implemented on Android and iOS. Values survive application restarts and are scoped to the local app installation. -## Running tests +## Backups and privacy -Run the PHP contract and NativePHP app integration tests from the consuming app: +Settings are stored in UserDefaults (iOS) and SharedPreferences (Android). Both are included in iCloud and Google device backups by default, so values can be restored onto another device and are readable by anyone with access to the backup. This package does not encrypt anything: never store tokens, passwords, or personal data that needs protection. Use a Keychain/Keystore-backed solution, such as NativePHP's `SecureStorage`, for secrets. -```bash -php artisan test -``` +## Running tests -Run the JavaScript bridge tests from the consuming app: +From the package directory: ```bash -npm --prefix packages/momotombo/nativephp-settings run test:js +composer install +composer test +composer format:check +npm run test:js ``` -The component tests fake the NativePHP bridge; they do not execute Kotlin or Swift storage. Verify device persistence and native rendering by running the app on Android and iOS. +The PHP tests use Orchestra Testbench and fake the NativePHP bridge; they do not execute Kotlin or Swift storage. Verify device persistence by running the app on Android and iOS. ## Validation before release @@ -134,6 +291,10 @@ php artisan native:plugin:validate packages/momotombo/nativephp-settings --no-in Then verify both platforms in a real app. Exercise `set`, `get`, `has`, `forget`, and `all`, including a missing key, an app restart, invalid input, and the 64 KiB boundary. NativePHP's plugin validation checks the manifest and source registration; it does not replace device testing. +## Changelog + +See [CHANGELOG.md](CHANGELOG.md). + ## License -MIT +MIT. See [LICENSE](LICENSE). diff --git a/composer.json b/composer.json index 3c4f416..3ea7913 100644 --- a/composer.json +++ b/composer.json @@ -3,13 +3,29 @@ "description": "Local typed settings for NativePHP Mobile applications.", "type": "nativephp-plugin", "license": "MIT", + "keywords": [ + "nativephp", + "nativephp-mobile", + "laravel", + "settings", + "preferences", + "storage", + "userdefaults", + "sharedpreferences", + "key-value" + ], + "homepage": "https://github.com/momotombodevs/nativephp-settings", + "support": { + "issues": "https://github.com/momotombodevs/nativephp-settings/issues", + "source": "https://github.com/momotombodevs/nativephp-settings" + }, "authors": [ { "name": "Momotombo" } ], "require": { - "php": "^8.2", + "php": "^8.3", "nativephp/mobile": "^4.5" }, "autoload": { @@ -17,6 +33,11 @@ "Momotombo\\NativephpSettings\\": "src/" } }, + "autoload-dev": { + "psr-4": { + "Momotombo\\NativephpSettings\\Tests\\": "tests/" + } + }, "extra": { "laravel": { "providers": [ @@ -28,14 +49,21 @@ } }, "require-dev": { - "pestphp/pest": "^3.0" + "laravel/pint": "^1.24", + "orchestra/testbench": "^10.0|^11.0", + "pestphp/pest": "^3.0|^4.0|^5.0" }, "scripts": { - "test": "pest" + "test": "pest", + "format": "pint", + "format:check": "pint --test" }, "config": { "allow-plugins": { "pestphp/pest-plugin": true - } - } + }, + "sort-packages": true + }, + "minimum-stability": "stable", + "prefer-stable": true } diff --git a/nativephp.json b/nativephp.json index c5f12e9..f8364c9 100644 --- a/nativephp.json +++ b/nativephp.json @@ -1,9 +1,17 @@ { "name": "momotombo/nativephp-settings", - "version": "1.0.0", + "version": "1.1.0", "description": "Local typed settings for NativePHP Mobile applications.", "namespace": "Settings", - "keywords": [], + "keywords": [ + "settings", + "preferences", + "storage", + "userdefaults", + "sharedpreferences", + "key-value", + "nativephp" + ], "category": "utilities", "license": "MIT", "pricing": { @@ -81,8 +89,5 @@ "ios": [] }, "secrets": [], - "service_provider": "Momotombo\\NativephpSettings\\SettingsServiceProvider", - "hooks": { - "copy_assets": "nativephp:settings:copy-assets" - } + "service_provider": "Momotombo\\NativephpSettings\\SettingsServiceProvider" } diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..09ffd86 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,18 @@ + + + + + tests + + + + + src + + + diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php index 82c54f7..983f871 100644 --- a/resources/boost/guidelines/core.blade.php +++ b/resources/boost/guidelines/core.blade.php @@ -4,14 +4,20 @@ ### Installation +Installing requires all of these steps; a plugin that is required but not registered does nothing: + ```bash composer require momotombo/nativephp-settings +php artisan vendor:publish --tag=nativephp-plugins-provider php artisan native:plugin:register momotombo/nativephp-settings +php artisan native:plugin:list ``` +`native:plugin:list` must show the plugin as registered. Then ask the user to rebuild with `php artisan native:run` (never run it yourself). + ### PHP Usage (Livewire/Blade) -Use the `Settings` facade: +Use the `Settings` facade. Prefer typed getters when reading values that drive UI state: @verbatim @@ -19,7 +25,11 @@ Settings::set('app.language', 'es'); -$language = Settings::get('app.language', 'es'); +$language = Settings::getString('app.language', 'es'); +$enabled = Settings::getBool('notifications.enabled', true); +$columns = Settings::getInt('layout.columns', 3); +$theme = Settings::getEnum('appearance.theme', Theme::Light); + $exists = Settings::has('app.language'); $all = Settings::all(); @@ -33,9 +43,35 @@ - `Settings::get(string $key, mixed $default = null): mixed` - `Settings::has(string $key): bool` - `Settings::forget(string $key): void` -- `Settings::all(): array` +- `Settings::all(): array` (skips unreadable entries and dispatches `SettingsCorrupted` with their keys) +- `Settings::allWithReport(): array` (`['values' => ..., 'corrupt' => [...keys]]`) +- `Settings::getBool()`, `getInt()`, `getFloat()`, `getString()`, `getArray()`, `getEnum()`: take a required default and return it when the key is missing or holds another type (`getFloat` accepts whole numbers; `getArray` accepts lists and maps). With `NATIVE_SETTINGS_STRICT=true` they throw `SettingTypeMismatch` instead. + +Keys use lowercase dot notation with non-empty segments. Stored values may be strings, booleans, integers, finite floats, string-backed enums, and JSON-safe arrays or maps up to 32 levels deep. `null` is not supported; each compact UTF-8 JSON value is limited to 65,536 bytes. Bridge or native storage failures throw `SettingsBridgeException`. + +Storage driver: `NATIVE_SETTINGS_DRIVER` (`auto` by default). Devices always use native storage and ignore this setting. Off the device, `auto` uses memory in unit tests, a JSON file in `local`/`testing`, and otherwise throws `BRIDGE_UNAVAILABLE`. Tests that script `Settings.*` on `Native::fakeBridge()` must set the driver to `native`; prefer `Settings::fake()`. + +Keys may not contain the segments `__proto__`, `constructor`, or `prototype`. + +### Testing + +Use `Settings::fake()` instead of scripting `Settings.*` responses on the NativePHP `FakeBridge`: + +@verbatim + +$settings = Settings::fake(['app.language' => 'es']); + +Native::visit('/settings')->tap('save-settings'); + +$settings->assertSet('app.language', 'en'); +$settings->assertForgotten('profile.display_name'); +$settings->assertNothingSet(); + +@endverbatim + +### Privacy -Keys use lowercase dot notation with non-empty segments. Stored values may be strings, booleans, integers, finite floats, string-backed enums, and JSON-safe arrays or maps up to 32 levels deep. `null` is not supported; each compact UTF-8 JSON value is limited to 65,536 bytes. Calls require a NativePHP runtime and may throw `SettingsBridgeException` on bridge or native storage failures. +Values are stored in UserDefaults / SharedPreferences, which are included in iCloud and Google backups and are not encrypted. Never store tokens, passwords, or sensitive personal data with this package; use NativePHP `SecureStorage` for secrets. ### JavaScript Usage (Vue/React/Inertia) diff --git a/src/Commands/CopyAssetsCommand.php b/src/Commands/CopyAssetsCommand.php deleted file mode 100644 index fe7b4bf..0000000 --- a/src/Commands/CopyAssetsCommand.php +++ /dev/null @@ -1,25 +0,0 @@ -isAndroid()) { - $this->info('Android assets copied for Settings'); - } - - if ($this->isIos()) { - $this->info('iOS assets copied for Settings'); - } - - return self::SUCCESS; - } -} diff --git a/tests/PluginTest.php b/tests/PluginTest.php index 08b6ccd..d90488b 100644 --- a/tests/PluginTest.php +++ b/tests/PluginTest.php @@ -1,221 +1,129 @@ */ +function settingsPluginJson(string $file): array +{ + return json_decode((string) file_get_contents(dirname(__DIR__).'/'.$file), true, 512, JSON_THROW_ON_ERROR); +} -beforeEach(function () { - $this->pluginPath = dirname(__DIR__); - $this->manifestPath = $this->pluginPath . '/nativephp.json'; -}); +function settingsPluginSource(string $file): string +{ + return (string) file_get_contents(dirname(__DIR__).'/'.$file); +} -describe('Plugin Manifest', function () { - it('has a valid nativephp.json file', function () { - expect(file_exists($this->manifestPath))->toBeTrue(); +/** + * @return array}> + */ +function settingsBridgeFunctions(): array +{ + $functions = []; - $content = file_get_contents($this->manifestPath); - $manifest = json_decode($content, true); + foreach (settingsPluginJson('nativephp.json')['bridge_functions'] as $function) { + $functions[$function['name']] = [$function]; + } - expect(json_last_error())->toBe(JSON_ERROR_NONE); - }); + return $functions; +} - it('has required fields', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); +describe('manifest', function () { + it('is accepted by the NativePHP plugin manifest parser', function () { + $manifest = PluginManifest::fromFile(dirname(__DIR__).'/nativephp.json'); - expect($manifest)->toHaveKeys(['name', 'namespace', 'bridge_functions']); - expect($manifest['name'])->toBe('momotombo/nativephp-settings'); - expect($manifest['namespace'])->toBe('Settings'); + expect($manifest->namespace)->toBe('Settings') + ->and($manifest->platforms)->toBe(['android', 'ios']) + ->and(array_column($manifest->bridgeFunctions, 'name'))->toBe([ + 'Settings.Set', + 'Settings.Get', + 'Settings.Has', + 'Settings.Forget', + 'Settings.All', + ]) + ->and($manifest->hooks)->toBe([]); }); - it('has valid bridge functions', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); + it('matches the composer package metadata', function () { + $manifest = settingsPluginJson('nativephp.json'); + $composer = settingsPluginJson('composer.json'); - expect($manifest['bridge_functions'])->toBeArray(); - - foreach ($manifest['bridge_functions'] as $function) { - expect($function)->toHaveKeys(['name']); - expect(array_intersect(['android', 'ios'], array_keys($function)))->not->toBeEmpty(); - } + expect($manifest['name'])->toBe($composer['name']) + ->and($manifest['license'])->toBe($composer['license']) + ->and($manifest['service_provider'])->toBe(SettingsServiceProvider::class) + ->and($composer['type'])->toBe('nativephp-plugin') + ->and($composer['extra']['nativephp']['manifest'])->toBe('nativephp.json') + ->and($composer['extra']['laravel']['providers'])->toBe([SettingsServiceProvider::class]) + ->and($manifest['keywords'])->not->toBeEmpty(); }); - it('has valid marketplace metadata', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); + it('declares the version of the latest changelog entry', function () { + preg_match('/^## \[(\d+\.\d+\.\d+)\]/m', settingsPluginSource('CHANGELOG.md'), $matches); - // Optional but recommended for marketplace - if (isset($manifest['keywords'])) { - expect($manifest['keywords'])->toBeArray(); - } - - if (isset($manifest['category'])) { - expect($manifest['category'])->toBeString(); - } - - if (isset($manifest['platforms'])) { - expect($manifest['platforms'])->toBeArray(); - foreach ($manifest['platforms'] as $platform) { - expect($platform)->toBeIn(['android', 'ios']); - } - } + expect($matches[1] ?? null)->toBe(settingsPluginJson('nativephp.json')['version']); }); }); -describe('Native Code', function () { - it('has Android Kotlin file', function () { - $kotlinFile = $this->pluginPath . '/resources/android/SettingsFunctions.kt'; - - expect(file_exists($kotlinFile))->toBeTrue(); - - $content = file_get_contents($kotlinFile); - expect($content)->toContain('package dev.momotombo.plugins.nativephp_settings'); - expect($content)->toContain('object SettingsFunctions'); - expect($content)->toContain('BridgeFunction'); - }); - - it('has iOS Swift file', function () { - $swiftFile = $this->pluginPath . '/resources/ios/SettingsFunctions.swift'; - - expect(file_exists($swiftFile))->toBeTrue(); - - $content = file_get_contents($swiftFile); - expect($content)->toContain('enum SettingsFunctions'); - expect($content)->toContain('BridgeFunction'); - }); - - it('has matching bridge function classes in native code', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); - - $kotlinFile = $this->pluginPath . '/resources/android/SettingsFunctions.kt'; - $swiftFile = $this->pluginPath . '/resources/ios/SettingsFunctions.swift'; - - $kotlinContent = file_get_contents($kotlinFile); - $swiftContent = file_get_contents($swiftFile); - - foreach ($manifest['bridge_functions'] as $function) { - // Extract class name from the function reference - if (isset($function['android'])) { - $parts = explode('.', $function['android']); - $className = end($parts); - expect($kotlinContent)->toContain("class {$className}"); - } - - if (isset($function['ios'])) { - $parts = explode('.', $function['ios']); - $className = end($parts); - expect($swiftContent)->toContain("class {$className}"); - } +describe('native parity', function () { + it('implements each bridge function in Swift and Kotlin', function (array $function) { + $swift = settingsPluginSource('resources/ios/SettingsFunctions.swift'); + $kotlin = settingsPluginSource('resources/android/SettingsFunctions.kt'); + + [$swiftContainer, $swiftClass] = explode('.', $function['ios']); + $androidParts = explode('.', $function['android']); + $kotlinClass = array_pop($androidParts); + $kotlinContainer = array_pop($androidParts); + $kotlinPackage = implode('.', $androidParts); + + expect($swift)->toContain("enum {$swiftContainer} {") + ->toMatch('/^\s+class '.preg_quote($swiftClass, '/').': BridgeFunction \{/m') + ->and($kotlin)->toContain("package {$kotlinPackage}\n") + ->toContain("object {$kotlinContainer} {") + ->toMatch('/^\s+class '.preg_quote($kotlinClass, '/').'\(private val context: Context\) : BridgeFunction \{/m') + ->and($function['android_params'] ?? [])->toBe(['context']); + })->with(settingsBridgeFunctions()); + + it('uses the same storage prefixes and limits on both platforms', function () { + $swift = settingsPluginSource('resources/ios/SettingsFunctions.swift'); + $kotlin = settingsPluginSource('resources/android/SettingsFunctions.kt'); + + foreach (['"dev.momotombo.nativephp.settings."', '"mnp-settings:v1:s:"', '"mnp-settings:v1:d:"', '"mnp-settings:v1:j:"', '"mnp-settings:v2:"', '65_536', '= 32'] as $token) { + expect($swift)->toContain($token) + ->and($kotlin)->toContain($token); } - }); -}); - -describe('PHP Classes', function () { - it('has service provider', function () { - $file = $this->pluginPath . '/src/SettingsServiceProvider.php'; - expect(file_exists($file))->toBeTrue(); - - $content = file_get_contents($file); - expect($content)->toContain('namespace Momotombo\NativephpSettings'); - expect($content)->toContain('class SettingsServiceProvider'); - }); - - it('has facade', function () { - $file = $this->pluginPath . '/src/Facades/Settings.php'; - expect(file_exists($file))->toBeTrue(); - - $content = file_get_contents($file); - expect($content)->toContain('namespace Momotombo\NativephpSettings\Facades'); - expect($content)->toContain('class Settings extends Facade'); - }); - it('has main implementation class', function () { - $file = $this->pluginPath . '/src/Settings.php'; - expect(file_exists($file))->toBeTrue(); - - $content = file_get_contents($file); - expect($content)->toContain('namespace Momotombo\NativephpSettings'); - expect($content)->toContain('class Settings'); + expect(Settings::MAX_VALUE_BYTES)->toBe(65_536); }); -}); -describe('Composer Configuration', function () { - it('has valid composer.json', function () { - $composerPath = $this->pluginPath . '/composer.json'; - expect(file_exists($composerPath))->toBeTrue(); + it('rejects the same reserved key segments in PHP, Swift, Kotlin, and JavaScript', function () { + $sources = [ + 'swift' => settingsPluginSource('resources/ios/SettingsFunctions.swift'), + 'kotlin' => settingsPluginSource('resources/android/SettingsFunctions.kt'), + 'javascript' => str_replace("'", '"', settingsPluginSource('resources/js/settings.js')), + ]; - $content = file_get_contents($composerPath); - $composer = json_decode($content, true); + foreach ($sources as $platform => $source) { + expect(preg_match('/RESERVED_KEY_SEGMENTS[^\n]*|reservedKeySegments[^\n]*/i', $source, $match))->toBe(1, $platform); - expect(json_last_error())->toBe(JSON_ERROR_NONE); - expect($composer['type'])->toBe('nativephp-plugin'); - expect($composer['extra']['nativephp']['manifest'])->toBe('nativephp.json'); - }); -}); + preg_match_all('/"([^"]+)"/', $match[0], $segments); -describe('Lifecycle Hooks', function () { - it('has valid hooks configuration', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); - - if (isset($manifest['hooks'])) { - expect($manifest['hooks'])->toBeArray(); - - $validHooks = ['pre_compile', 'post_compile', 'copy_assets', 'post_build']; - foreach (array_keys($manifest['hooks']) as $hook) { - expect($hook)->toBeIn($validHooks); - } + expect($segments[1])->toBe(Settings::RESERVED_KEY_SEGMENTS, $platform); } }); +}); - it('has copy_assets hook command', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); - - expect($manifest['hooks']['copy_assets'] ?? null)->not->toBeNull(); - - $commandFile = $this->pluginPath . '/src/Commands/CopyAssetsCommand.php'; - expect(file_exists($commandFile))->toBeTrue(); - }); - - it('copy_assets command extends NativePluginHookCommand', function () { - $commandFile = $this->pluginPath . '/src/Commands/CopyAssetsCommand.php'; - $content = file_get_contents($commandFile); - - expect($content)->toContain('extends NativePluginHookCommand'); - expect($content)->toContain('use Native\Mobile\Plugins\Commands\NativePluginHookCommand'); - }); - - it('copy_assets command has correct signature', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); - $expectedSignature = $manifest['hooks']['copy_assets']; - - $commandFile = $this->pluginPath . '/src/Commands/CopyAssetsCommand.php'; - $content = file_get_contents($commandFile); - - expect($content)->toContain('$signature = \'' . $expectedSignature . '\''); - }); - - it('copy_assets command has platform-specific methods', function () { - $commandFile = $this->pluginPath . '/src/Commands/CopyAssetsCommand.php'; - $content = file_get_contents($commandFile); - - // Should check for platform - expect($content)->toContain('$this->isAndroid()'); - expect($content)->toContain('$this->isIos()'); - }); - - it('has valid assets configuration', function () { - $manifest = json_decode(file_get_contents($this->manifestPath), true); - - // Assets are at top level with android/ios nested inside - if (isset($manifest['assets'])) { - expect($manifest['assets'])->toBeArray(); - - if (isset($manifest['assets']['android'])) { - expect($manifest['assets']['android'])->toBeArray(); - } - - if (isset($manifest['assets']['ios'])) { - expect($manifest['assets']['ios'])->toBeArray(); - } - } +describe('php entry points', function () { + it('exposes the facade, service, and provider classes', function () { + expect(class_exists(SettingsFacade::class))->toBeTrue() + ->and(class_exists(Settings::class))->toBeTrue() + ->and(is_subclass_of(SettingsServiceProvider::class, ServiceProvider::class))->toBeTrue() + ->and(file_exists(dirname(__DIR__).'/config/nativephp-settings.php'))->toBeTrue(); }); }); From 377f1163ebad2b513c1f76977c214213fc2987f7 Mon Sep 17 00:00:00 2001 From: manuelduarte077 Date: Thu, 12 Nov 2026 19:06:04 -0600 Subject: [PATCH 6/6] chore(release): prepare v1.1.0 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f25f155..c5c760a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to `momotombo/nativephp-settings` are documented in this fil The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.1.0] - Unreleased +## [1.1.0] - 2026-11-12 ### Added @@ -54,5 +54,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - iOS (UserDefaults) and Android (SharedPreferences) bridge functions with identical key and value validation. - JavaScript module for Vue, React, and Inertia frontends. -[1.1.0]: https://github.com/momotombodevs/nativephp-settings/compare/v1.0.0...HEAD +[1.1.0]: https://github.com/momotombodevs/nativephp-settings/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/momotombodevs/nativephp-settings/releases/tag/v1.0.0