From 62987d576e0271b07ba0739b77c3d3e1b4eb89f4 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Mon, 17 Mar 2025 17:23:44 +0400 Subject: [PATCH 01/27] Init changelog & version 0.4.1p82 --- CHANGES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 6055589..f74bd64 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,5 @@ +## Release 0.4.1p82 du 17/03/2025-17:23 + ## Release 0.4.1p74 du 17/03/2025-17:19 * `56fda96` changer le type de variables gérées par EnvConfig From 1feffb6c0f0d63ac109f91dfec9d684b1ad20635 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Tue, 18 Mar 2025 10:35:28 +0400 Subject: [PATCH 02/27] modifs.mineures sans commentaires --- src/schema/Schema.php | 35 +++++++++- src/schema/TODO.md | 1 - src/schema/WrapperContext.php | 19 ++++-- src/schema/_scalar/ScalarSchema.php | 32 --------- src/schema/_scalar/ScalarWrapper.php | 99 ++++++++++++++-------------- 5 files changed, 96 insertions(+), 90 deletions(-) diff --git a/src/schema/Schema.php b/src/schema/Schema.php index 02365cb..55f1304 100644 --- a/src/schema/Schema.php +++ b/src/schema/Schema.php @@ -17,6 +17,29 @@ use nur\sery\wip\schema\types\tcontent; use nur\sery\wip\schema\types\tpkey; use nur\sery\wip\schema\types\trawstring; +/** + * Class Schema + * + * @property-read array|IType $type + * @property-read mixed $default + * @property-read string|null $title + * @property-read bool $required + * @property-read bool $nullable + * @property-read string|array|null $desc + * @property-read callable|null $analyzerFunc + * @property-read callable|null $extractorFunc + * @property-read callable|null $parserFunc + * @property-read callable|null $normalizerFunc + * @property-read array|null $messages + * @property-read callable|null $formatterFunc + * @property-read mixed $format + * @property-read array $nature + * @property-read array|null $schema + * @property-read string|int|null $name + * @property-read string|array|null $pkey + * @property-read string|null $header + * @property-read bool|null $computed + */ abstract class Schema implements ArrayAccess { /** * créer le cas échéant une nouvelle instance de {@link Schema} à partir d'une @@ -253,6 +276,8 @@ abstract class Schema implements ArrayAccess { /** retourner true si le schéma est de nature scalaire */ function isScalar(?ScalarSchema &$schema=null): bool { return false; } + abstract protected function newWrapper(): Wrapper; + abstract function getWrapper(&$value=null, $valueKey=null, ?Wrapper &$wrapper=null): Wrapper; ############################################################################# @@ -272,7 +297,15 @@ abstract class Schema implements ArrayAccess { throw AccessException::read_only(null, $offset); } - const _PROPERTY_PKEYS = []; + const _PROPERTY_PKEYS = [ + "analyzerFunc" => "analyzer_func", + "extractorFunc" => "extractor_func", + "parserFunc" => "parser_func", + "normalizerFunc" => "normalizer_func", + "formatterFunc" => "formatter_func", + "nature" => ["", 0], + ]; + function __get($name) { $pkey = cl::get(static::_PROPERTY_PKEYS, $name, $name); return cl::pget($this->definition, $pkey); diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 5f50801..46e80ce 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -1,6 +1,5 @@ # nulib\schema -* instance de WrapperContext directement dans le schéma * plus de {key} ni {orig} dans messages * les messages standard ne sont utilisés que s'il n'y a pas de message dans l'exception diff --git a/src/schema/WrapperContext.php b/src/schema/WrapperContext.php index 5ee0d37..071ed7b 100644 --- a/src/schema/WrapperContext.php +++ b/src/schema/WrapperContext.php @@ -5,26 +5,31 @@ use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\types\IType; class WrapperContext { - function __construct(Schema $schema, Wrapper $wrapper, Input $input, $valueKey, Result $result) { + function __construct(Schema $schema, Wrapper $wrapper, ?Input $input, $valueKey, Result $result) { $this->schema = $schema; $this->wrapper = $wrapper; - $this->input = $input; - $this->result = $result; + if ($input !== null) $this->input = $input; + $this->valueKey = $valueKey; $this->type = null; + $this->result = $result; $this->origValue = null; $this->value = null; - $this->valueKey = $valueKey; } + /** schéma de la valeur */ public Schema $schema; + /** instance de Wrapper associé à ce contexte */ public Wrapper $wrapper; + /** source et destination de la valeur */ public Input $input; - public Result $result; + /** @var string|int|null clé de la valeur dans le tableau destination */ + public $valueKey; + /** type de la valeur après analyse */ public ?IType $type; + /** résultat de l'analyse de la valeur */ + public Result $result; /** @var mixed */ public $origValue; /** @var mixed */ public $value; - /** @var int|string|null */ - public $valueKey; } diff --git a/src/schema/_scalar/ScalarSchema.php b/src/schema/_scalar/ScalarSchema.php index a4c11bf..44e2ac5 100644 --- a/src/schema/_scalar/ScalarSchema.php +++ b/src/schema/_scalar/ScalarSchema.php @@ -8,26 +8,6 @@ use nur\sery\wip\schema\Wrapper; /** * Class ScalarSchema - * - * @property-read array|IType $type - * @property-read mixed $default - * @property-read string|null $title - * @property-read bool $required - * @property-read bool $nullable - * @property-read string|array|null $desc - * @property-read callable|null $analyzerFunc - * @property-read callable|null $extractorFunc - * @property-read callable|null $parserFunc - * @property-read callable|null $normalizerFunc - * @property-read array|null $messages - * @property-read callable|null $formatterFunc - * @property-read mixed $format - * @property-read array $nature - * @property-read array|null $schema - * @property-read string|int|null $name - * @property-read string|array|null $pkey - * @property-read string|null $header - * @property-read bool|null $composite */ class ScalarSchema extends Schema { /** @var array meta-schema d'un schéma de nature scalaire */ @@ -97,16 +77,4 @@ class ScalarSchema extends Schema { if (!($wrapper instanceof ScalarWrapper)) $wrapper = $this->newWrapper(); return $wrapper->reset($value, $valueKey, $verifix); } - - ############################################################################# - # key & properties - - const _PROPERTY_PKEYS = [ - "analyzerFunc" => "analyzer_func", - "extractorFunc" => "extractor_func", - "parserFunc" => "parser_func", - "normalizerFunc" => "normalizer_func", - "formatterFunc" => "formatter_func", - "nature" => ["", 0], - ]; } diff --git a/src/schema/_scalar/ScalarWrapper.php b/src/schema/_scalar/ScalarWrapper.php index 0ea9596..5bcb847 100644 --- a/src/schema/_scalar/ScalarWrapper.php +++ b/src/schema/_scalar/ScalarWrapper.php @@ -19,35 +19,21 @@ class ScalarWrapper extends Wrapper { # c'est une initialisation sans conséquences $throw = true; } + $this->context = new WrapperContext($schema, $this, null, null, new ScalarResult()); $this->verifix = $verifix; $this->throw = $throw ?? false; - $this->schema = $schema; - $this->result = new ScalarResult(); $this->reset($value, $valueKey); $this->throw = $throw ?? true; } function isScalar(?ScalarWrapper &$wrapper=null): bool { $wrapper = $this; return true; } + protected WrapperContext $context; + protected bool $verifix; protected bool $throw; - /** schéma de cette valeur */ - protected ScalarSchema $schema; - - /** source et destination de la valeur */ - protected Input $input; - - /** @var string|int|null clé de la valeur dans le tableau destination */ - protected $valueKey; - - /** type de la valeur après analyse */ - protected ?IType $type; - - /** résultat de l'analyse de la valeur */ - protected ScalarResult $result; - protected function newInput(&$value): Input { return new Input($value); } @@ -55,9 +41,9 @@ class ScalarWrapper extends Wrapper { function reset(&$value, $valueKey=null, ?bool $verifix=null): Wrapper { if ($value instanceof Input) $input = $value; else $input = $this->newInput($value); - $this->input = $input; - $this->valueKey = $valueKey; - $this->type = null; + $this->context->input = $input; + $this->context->valueKey = $valueKey; + $this->context->type = null; $this->analyze(); if ($verifix ?? $this->verifix) $this->verifix(); return $this; @@ -74,7 +60,8 @@ class ScalarWrapper extends Wrapper { } /** analyser la valeur et résoudre son type */ - protected function analyze0(WrapperContext $context): int { + protected function analyze0(): int { + $context = $this->context; /** @var ScalarSchema $schema */ $schema = $context->schema; $input = $context->input; @@ -112,7 +99,7 @@ class ScalarWrapper extends Wrapper { $args = $name; $name = $key; } - $type = types::get($schema->nullable, $name, $args, $this->schema->getDefinition()); + $type = types::get($schema->nullable, $name, $args, $schema->getDefinition()); if ($firstType === null) $firstType = $type; $types[] = $type; if ($type->isAvailable($input, $valueKey)) { @@ -166,17 +153,19 @@ class ScalarWrapper extends Wrapper { } protected function analyze(): int { - $schema = $this->schema; - $input = $this->input; - $valueKey = $this->valueKey; - $result = $this->result; + $context = $this->context; + /** @var ScalarSchema $schema */ + $schema = $context->schema; + $input = $context->input; + $valueKey = $context->valueKey; + /** @var ScalarResult $result */ + $result = $context->result; $result->reset(); - $context = new WrapperContext($schema, $this, $input, $valueKey, $result); /** @var func $analyzerFunc */ $analyzerFunc = $schema->analyzerFunc; if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context]); - else $what = $this->analyze0($context); + else $what = $this->analyze0(); if ($what !== ref_analyze::STRING) return $what; $value = $context->value; @@ -212,20 +201,27 @@ class ScalarWrapper extends Wrapper { } function verifix(?bool $throw=null): bool { - $result = $this->result; - $valueKey = $this->valueKey; + $context = $this->context; + /** @var ScalarSchema $schema */ + $schema = $context->schema; + $input = $context->input; + $valueKey = $context->valueKey; + /** @var ScalarResult $result */ + $result = $context->result; + + $verifix = false; $modified = false; if ($result->resultAvailable) { if ($result->null) { # forcer la valeur null, parce que la valeur actuelle est peut-être une # valeur assimilée à null - $this->input->set(null, $valueKey); + $input->set(null, $valueKey); } elseif ($result->valid && !$result->normalized) { $normalizedValue = $result->normalizedValue; if ($normalizedValue !== null) { # la valeur normalisée est disponible - $this->input->set($normalizedValue); + $input->set($normalizedValue); $result->normalizedValue = null; $modified = true; } else { @@ -238,75 +234,80 @@ class ScalarWrapper extends Wrapper { } if ($verifix) { - $value = $this->input->get($valueKey); - $schema = $this->schema; + $value = $input->get($valueKey); /** @var func $normalizerFunc */ $normalizerFunc = $schema->normalizerFunc; if ($normalizerFunc !== null) { - $context = new WrapperContext($schema, $this, $this->input, $valueKey, $result); + $context = new WrapperContext($schema, $this, $input, $valueKey, $result); $orig = $value; $value = $normalizerFunc->invoke([$orig, $context]); $modified = $value !== $orig; } else { - $modified = $this->type->verifix($value, $result, $this->schema); + $modified = $this->type->verifix($value, $result, $schema); } - if ($result->valid) $this->input->set($value, $valueKey); + if ($result->valid) $input->set($value, $valueKey); } if (!$result->valid) $result->throw($throw ?? $this->throw); return $modified; } function getResult(): ScalarResult { - return $this->result; + /** @var ScalarResult $result */ + $result = $this->context->result; + return $result; } function isPresent(): bool { - return $this->result->present; + return $this->context->result->present; } function getType(): IType { - return $this->type; + return $this->context->type; } function isAvailable(): bool { - return $this->result->available; + return $this->context->result->available; } function isValid(): bool { - return $this->result->valid; + return $this->context->result->valid; } function isNormalized(): bool { - return $this->result->normalized; + return $this->context->result->normalized; } function get($default=null) { - if ($this->result->available) return $this->input->get($this->valueKey); + $context = $this->context; + if ($context->result->available) return $context->input->get($context->valueKey); else return $default; } function set($value, ?bool $verifix=null): ScalarWrapper { - $this->input->set($value, $this->valueKey); + $context = $this->context; + $context->input->set($value, $context->valueKey); $this->analyze(); if ($verifix ?? $this->verifix) $this->verifix(); return $this; } function unset(?bool $verifix=null): ScalarWrapper { - $this->input->unset($this->valueKey); + $context = $this->context; + $context->input->unset($context->valueKey); $this->analyze(); if ($verifix ?? $this->verifix) $this->verifix(); return $this; } function format($format=null): string { - $value = $this->input->get($this->valueKey); + $context = $this->context; + $value = $context->input->get($context->valueKey); /** @var func $formatterFunc */ - $formatterFunc = $this->schema->formatterFunc; + $formatterFunc = $context->schema->formatterFunc; if ($formatterFunc !== null) { # la fonction formatter n'a pas forcément accès au format de la définition # le lui fournir ici - $format ??= $this->schema->format; + $format ??= $context->schema->format; return $formatterFunc->invoke([$value, $format]); } else { # on assume que le type a été initialisé avec le format de la définition From bb311708d7b5ef8c45cc22da941c04c5d3372e49 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Tue, 18 Mar 2025 10:43:43 +0400 Subject: [PATCH 03/27] modifs.mineures sans commentaires --- src/schema/_scalar/ScalarResult.php | 37 +++++++---------------------- 1 file changed, 8 insertions(+), 29 deletions(-) diff --git a/src/schema/_scalar/ScalarResult.php b/src/schema/_scalar/ScalarResult.php index cb568d5..1dbd2b6 100644 --- a/src/schema/_scalar/ScalarResult.php +++ b/src/schema/_scalar/ScalarResult.php @@ -46,19 +46,6 @@ class ScalarResult extends Result { $this->result[$name] = $value; } - protected static function replace_key(string &$message, ?string $key): void { - if ($key) { - $message = str_replace("{key}", $key, $message); - } else { - $message = str_replace("{key}: ", "", $message); - $message = str_replace("cette valeur", "la valeur", $message); - } - } - - protected static function replace_orig(string &$message, $origValue): void { - $message = str_replace("{orig}", strval($origValue), $message); - } - protected function getMessage(string $key, ScalarSchema $schema): string { $message = cl::get($schema->messages, $key); if ($message !== null) return $message; @@ -75,10 +62,8 @@ class ScalarResult extends Result { $this->normalized = true; return ref_analyze::NORMALIZED; } else { - $messageKey = $this->messageKey = "missing"; - $message = $this->getMessage($messageKey, $schema); - self::replace_key($message, $schema->name); - $this->message = $message; + $this->messageKey = $messageKey = "missing"; + $this->message = $this->getMessage($messageKey, $schema); return ref_analyze::MISSING; } } @@ -93,10 +78,8 @@ class ScalarResult extends Result { $this->normalized = true; return ref_analyze::NORMALIZED; } else { - $messageKey = $this->messageKey = "unavailable"; - $message = $this->getMessage($messageKey, $schema); - self::replace_key($message, $schema->name); - $this->message = $message; + $this->messageKey = $messageKey = "unavailable"; + $this->message = $this->getMessage($messageKey, $schema); return ref_analyze::UNAVAILABLE; } } @@ -111,10 +94,8 @@ class ScalarResult extends Result { $this->normalized = true; return ref_analyze::NORMALIZED; } else { - $messageKey = $this->messageKey = "null"; - $message = $this->getMessage($messageKey, $schema); - self::replace_key($message, $schema->name); - $this->message = $message; + $this->messageKey = $messageKey = "null"; + $this->message = $this->getMessage($messageKey, $schema); return ref_analyze::NULL; } } @@ -126,13 +107,11 @@ class ScalarResult extends Result { $this->null = false; $this->valid = false; $this->origValue = $value; - $messageKey = $this->messageKey = "invalid"; + $this->messageKey = $messageKey = "invalid"; $message = $this->getMessage($messageKey, $schema); - self::replace_key($message, $schema->name); - self::replace_orig($message, $schema->orig); if ($t !== null) { $tmessage = ValueException::get_message($t); - if ($tmessage) $message .= ": $tmessage"; + if ($tmessage) $message = $tmessage; } $this->message = $message; return ref_analyze::INVALID; From 91e6c0dcd2d1eec7b176f77e58fc19696ea451ff Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Tue, 18 Mar 2025 10:48:50 +0400 Subject: [PATCH 04/27] modifs.mineures sans commentaires --- src/schema/Result.php | 5 ++++- src/schema/_scalar/ScalarResult.php | 13 +++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/schema/Result.php b/src/schema/Result.php index 3ccb261..46f08ee 100644 --- a/src/schema/Result.php +++ b/src/schema/Result.php @@ -5,6 +5,7 @@ use IteratorAggregate; use nur\sery\wip\schema\_assoc\AssocResult; use nur\sery\wip\schema\_list\ListResult; use nur\sery\wip\schema\_scalar\ScalarResult; +use Throwable; /** * Class Result: résultat de l'analyse ou de la normalisation d'une valeur @@ -17,6 +18,8 @@ use nur\sery\wip\schema\_scalar\ScalarResult; * @property bool $normalized si la valeur est valide, est-elle normalisée? * @property string|null $messageKey clé de message si la valeur n'est pas valide * @property string|null $message message si la valeur n'est pas valide + * @property Throwable|null $exception l'exception qui a fait échouer la + * validation le cas échéant * @property string|null $origValue valeur originale avant extraction et analyse * @property mixed|null $normalizedValue la valeur normalisée si elle est * disponible, null sinon. ce champ est utilisé comme optimisation si la valeur @@ -26,7 +29,7 @@ abstract class Result implements IteratorAggregate { const KEYS = [ "resultAvailable", "present", "available", "null", "valid", "normalized", - "messageKey", "message", + "messageKey", "message", "exception", "origValue", "normalizedValue", ]; diff --git a/src/schema/_scalar/ScalarResult.php b/src/schema/_scalar/ScalarResult.php index 1dbd2b6..572d936 100644 --- a/src/schema/_scalar/ScalarResult.php +++ b/src/schema/_scalar/ScalarResult.php @@ -100,7 +100,7 @@ class ScalarResult extends Result { } } - function setInvalid($value, ScalarSchema $schema, ?Throwable $t=null): int { + function setInvalid($value, ScalarSchema $schema, ?Throwable $exception=null): int { $this->resultAvailable = true; $this->present = true; $this->available = true; @@ -109,11 +109,12 @@ class ScalarResult extends Result { $this->origValue = $value; $this->messageKey = $messageKey = "invalid"; $message = $this->getMessage($messageKey, $schema); - if ($t !== null) { - $tmessage = ValueException::get_message($t); + if ($exception !== null) { + $tmessage = ValueException::get_message($exception); if ($tmessage) $message = $tmessage; } $this->message = $message; + $this->exception = $exception; return ref_analyze::INVALID; } @@ -138,6 +139,10 @@ class ScalarResult extends Result { } function throw(bool $throw): void { - if ($throw) throw new ValueException($this->message); + if ($throw) { + $exception = $this->exception; + if ($exception !== null) throw $exception; + else throw new ValueException($this->message); + } } } From 189c7aba6832fac661a2741cb67c234dbdcbf056 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Tue, 18 Mar 2025 13:30:02 +0400 Subject: [PATCH 05/27] modifs.mineures sans commentaires --- src/schema/Schema.php | 7 ++ src/schema/TODO.md | 7 +- src/schema/Wrapper.php | 17 +++ src/schema/WrapperContext.php | 16 ++- src/schema/_assoc/AssocResult.php | 33 +++--- src/schema/_assoc/AssocSchema.php | 25 ++++- src/schema/_assoc/AssocWrapper.php | 113 ++++++++++---------- src/schema/_assoc/AssocWrapperContext.php | 21 ++++ src/schema/_list/ListSchema.php | 17 ++- src/schema/_scalar/ScalarResult.php | 5 +- src/schema/_scalar/ScalarSchema.php | 12 +++ src/schema/_scalar/ScalarWrapper.php | 59 ++++------ tests/wip/schema/_assoc/AssocSchemaTest.php | 5 +- 13 files changed, 206 insertions(+), 131 deletions(-) create mode 100644 src/schema/_assoc/AssocWrapperContext.php diff --git a/src/schema/Schema.php b/src/schema/Schema.php index 55f1304..a7721f4 100644 --- a/src/schema/Schema.php +++ b/src/schema/Schema.php @@ -269,6 +269,13 @@ abstract class Schema implements ArrayAccess { return $this->_definition; } + /** + * retourner la liste des clés valides pour l'accès aux valeurs et résultats + */ + abstract function getKeys(): array; + + abstract function getSchema($key): Schema; + /** retourner true si le schéma est de nature tableau associatif */ function isAssoc(?AssocSchema &$schema=null): bool { return false; } /** retourner true si le schéma est de nature liste */ diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 46e80ce..73b4aca 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -1,15 +1,12 @@ # nulib\schema -* plus de {key} ni {orig} dans messages - * les messages standard ne sont utilisés que s'il n'y a pas de message dans - l'exception - * si instance de UserException, prendre le message "non technique" pour - résultat * valeurs composite/computed * analyse / vérification de la valeur complète après calcul du résultat, si tous les résultats sont bons * calcul des valeurs composites/computed par une fonction avant/après l'analyse globale si résultat ok + * fonction getter_func, setter_func, deleter_func pour les propriétés de type + computed * tdate et tdatetime. qu'en est-il des autres classes (delay, etc.) * possibilité de spécifier le format de la date à analyser * ScalarSchema::from_property() diff --git a/src/schema/Wrapper.php b/src/schema/Wrapper.php index d8cafed..f567702 100644 --- a/src/schema/Wrapper.php +++ b/src/schema/Wrapper.php @@ -3,6 +3,7 @@ namespace nur\sery\wip\schema; use ArrayAccess; use IteratorAggregate; +use nulib\php\func; use nur\sery\wip\schema\_assoc\AssocWrapper; use nur\sery\wip\schema\_list\ListWrapper; use nur\sery\wip\schema\_scalar\ScalarWrapper; @@ -67,6 +68,22 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { /** supprimer la valeur */ abstract function unset(): self; + protected function _format(WrapperContext $context, $format=null): string { + $value = $context->input->get($context->valueKey); + /** @var func $formatterFunc */ + $formatterFunc = $context->schema->formatterFunc; + if ($formatterFunc !== null) { + # la fonction formatter n'a pas forcément accès au format de la définition + # le lui fournir ici + $format ??= $context->schema->format; + return $formatterFunc->invoke([$value, $format, $context, $this]); + } else { + # on assume que le type a été initialisé avec le format de la définition + # le cas échéant + return $context->type->format($value, $format); + } + } + /** formatter la valeur pour affichage */ abstract function format($format=null): string; diff --git a/src/schema/WrapperContext.php b/src/schema/WrapperContext.php index 071ed7b..440b8c6 100644 --- a/src/schema/WrapperContext.php +++ b/src/schema/WrapperContext.php @@ -5,21 +5,29 @@ use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\types\IType; class WrapperContext { - function __construct(Schema $schema, Wrapper $wrapper, ?Input $input, $valueKey, Result $result) { + function __construct(Schema $schema, ?Input $input, $valueKey, ?Result $result, ?array $params) { + $this->params = $params; + $this->verifix = $params["verifix"] ?? true; + $this->throw = $params["throw"] ?? null; + $this->schema = $schema; - $this->wrapper = $wrapper; + //$this->wrapper = $wrapper; if ($input !== null) $this->input = $input; $this->valueKey = $valueKey; $this->type = null; - $this->result = $result; + if ($result !== null) $this->result = $result; $this->origValue = null; $this->value = null; } + public ?array $params; + public bool $verifix; + public ?bool $throw; + /** schéma de la valeur */ public Schema $schema; /** instance de Wrapper associé à ce contexte */ - public Wrapper $wrapper; + //public Wrapper $wrapper; /** source et destination de la valeur */ public Input $input; /** @var string|int|null clé de la valeur dans le tableau destination */ diff --git a/src/schema/_assoc/AssocResult.php b/src/schema/_assoc/AssocResult.php index 8ac0c77..76a2a74 100644 --- a/src/schema/_assoc/AssocResult.php +++ b/src/schema/_assoc/AssocResult.php @@ -5,41 +5,38 @@ use nulib\ValueException; use nur\sery\wip\schema\Result; class AssocResult extends Result { - function __construct(Result $arrayResult, array &$keyResults) { - $this->arrayResult = $arrayResult; - $this->keyResults =& $keyResults; - $this->result =& $this->arrayResult; + function __construct(AssocWrapperContext $context) { + $this->context = $context; parent::__construct(); } function isAssoc(?AssocResult &$result=null): bool { $result = $this; return true;} - protected Result $arrayResult; - - /** @var Result[] */ - protected array $keyResults; + protected AssocWrapperContext $context; function getKeys(): array { - return array_keys($this->keyResults); + return $this->context->keys; } protected Result $result; - function select($key): Result { + function select($key): AssocResult { + $context = $this->context; if ($key === null) { - $this->result =& $this->arrayResult; - } elseif (array_key_exists($key, $this->keyResults)) { - $this->result =& $this->keyResults[$key]; - } else { - throw ValueException::invalid_key($key); + $this->result = $context->arrayResult; + return $this; } + $wrapper = $context->keyWrappers[$key] ?? null; + if ($wrapper === null) throw ValueException::invalid_key($key); + $this->result = $wrapper->getResult(); return $this; } function reset(): void { - $this->arrayResult->reset(); - foreach ($this->keyResults as $result) { - $result->reset(); + $context = $this->context; + $context->arrayResult->reset(); + foreach ($context->keyWrappers as $wrapper) { + $wrapper->getResult()->reset(); } } diff --git a/src/schema/_assoc/AssocSchema.php b/src/schema/_assoc/AssocSchema.php index cabcc38..017a6fd 100644 --- a/src/schema/_assoc/AssocSchema.php +++ b/src/schema/_assoc/AssocSchema.php @@ -3,6 +3,8 @@ namespace nur\sery\wip\schema\_assoc; use nulib\cl; use nulib\ref\schema\ref_schema; +use nulib\ValueException; +use nur\sery\wip\schema\_scalar\ScalarWrapper; use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\Wrapper; @@ -50,6 +52,11 @@ class AssocSchema extends Schema { self::_ensure_schema_instances($definition); } $this->definition = $definition; + $keys = []; + foreach ($definition["schema"] as $key => $schema) { + if (!$schema["computed"]) $keys[] = $key; + } + $this->keys = $keys; } function isAssoc(?AssocSchema &$schema=null): bool { @@ -57,12 +64,28 @@ class AssocSchema extends Schema { return true; } + protected array $keys; + + function getKeys(): array { + return $this->keys; + } + + function getSchema($key): Schema { + if ($key === null) return $this; + $schema = $this->definition["schema"][$key] ?? null; + if ($schema === null) throw ValueException::invalid_key($key); + return $schema; + } + protected function newWrapper(): AssocWrapper { return new AssocWrapper($this); } function getWrapper(&$array=null, $arrayKey=null, ?Wrapper &$wrapper=null): AssocWrapper { + # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception + # cf le code similaire dans ScalarWrapper::__construct() + $verifix = $array !== null || $wrapper !== null; if (!($wrapper instanceof AssocWrapper)) $wrapper = $this->newWrapper(); - return $wrapper->reset($array, $arrayKey); + return $wrapper->reset($array, $arrayKey, $verifix); } } diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index ea2981c..5ce88b1 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -3,59 +3,43 @@ namespace nur\sery\wip\schema\_assoc; use nulib\ValueException; use nur\sery\wip\schema\_scalar\ScalarResult; -use nur\sery\wip\schema\_scalar\ScalarWrapper; use nur\sery\wip\schema\input\Input; -use nur\sery\wip\schema\Result; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; +use nur\sery\wip\schema\WrapperContext; class AssocWrapper extends Wrapper { function __construct(AssocSchema $schema, &$array=null, $arrayKey=null, ?array $params=null) { - $verifix = $params["verifix"] ?? true; - $throw = $params["throw"] ?? null; + $definitionSchema = $schema->getDefinition()["schema"]; + $keys = $schema->getKeys(); + $keyTypes = []; + $keyWrappers = []; + foreach ($keys as $key) { + $keyTypes[$key] = null; + $keyWrappers[$key] = $schema->getSchema($key)->getWrapper(); + } + $this->context = $context = new AssocWrapperContext($schema, null, null, null, $params); + $context->arrayResult = new ScalarResult(); + $context->keys = $keys; + $context->keyTypes = $keyTypes; + $context->keyWrappers = $keyWrappers; + $context->result = new AssocResult($context); + + $throw = $context->throw; if ($array !== null && $throw === null) { # Si $value est null, ne pas lancer d'exception, parce qu'on considère que # c'est une initialisation sans conséquences $throw = true; } - $this->schema = $schema; - $this->verifix = $verifix; - $this->throw = $throw ?? false; - $this->result = new AssocResult(); + $context->throw = $throw ?? false; $this->reset($array, $arrayKey); - $this->throw = $throw ?? true; + $context->throw = $throw ?? true; } function isAssoc(?AssocWrapper &$wrapper=null): bool { $wrapper = $this; return true; } - protected bool $verifix; - - protected bool $throw; - - /** schéma de ce tableau */ - protected AssocSchema $schema; - - /** source et destination de la valeur */ - protected Input $input; - - /** @var string|int|null clé du tableau dans le tableau destination */ - protected $arrayKey; - - protected IType $arrayType; - - protected ScalarResult $arrayResult; - - /** @var IType[] */ - protected array $keyTypes; - - /** @var Result[] */ - protected array $keyResults; - - protected AssocResult $result; - - protected ?array $keys; - - protected ?array $wrappers; + /** @var AssocWrapperContext */ + protected WrapperContext $context; protected function newInput(&$value): Input { return new Input($value); @@ -64,73 +48,84 @@ class AssocWrapper extends Wrapper { function reset(&$array, $arrayKey=null, ?bool $verifix=null): Wrapper { if ($array instanceof Input) $input = $array; else $input = $this->newInput($array); - $this->input = $input; - $this->arrayKey = $arrayKey; + $context = $this->context; + $context->input = $input; + $context->valueKey = $arrayKey; $this->analyze(); - if ($verifix ?? $this->verifix) $this->verifix(); + if ($verifix ?? $context->verifix) $this->verifix(); return $this; } function getKeys(): array { - return $this->keys; + return $this->context->keys; } - function select($key=null): ScalarWrapper { - $wrapper = $this->wrappers[$key] ?? null; - if ($key !== null) return $wrapper; - throw ValueException::invalid_key($key); + /** @param string|int|null $key */ + function select($key=null): Wrapper { + if ($key === null) return $this; + $wrapper = $this->context->keyWrappers[$key] ?? null; + if ($wrapper === null) throw ValueException::invalid_key($key); + return $wrapper; } - /** @param Result[] $results */ - function verifix(?bool $throw=null, ?array &$results=null): bool { + protected function analyze(): int { + return 0; #XXX } + function verifix(?bool $throw=null): bool { + return false; #XXX + } function getResult(): AssocResult { - return $this->result; + /** @var AssocResult $result */ + $result = $this->context->result; + return $result; } function isPresent(): bool { - return $this->result->present; + return $this->context->result->present; } function getType(): IType { - return $this->arrayType; + return $this->context->type; } function isAvailable(): bool { - return $this->result->available; + return $this->context->result->available; } function isValid(): bool { - return $this->result->valid; + return $this->context->result->valid; } function isNormalized(): bool { - return $this->result->normalized; + return $this->context->result->normalized; } function get($default=null) { - if ($this->result->available) return $this->input->get($this->arrayKey); + $context = $this->context; + if ($context->result->available) return $context->input->get($context->valueKey); else return $default; } function set($value, ?bool $verifix=null): AssocWrapper { - $this->input->set($value, $this->arrayKey); + $context = $this->context; + $context->input->set($value, $context->valueKey); $this->analyze(); - if ($verifix ?? $this->verifix) $this->verifix(); + if ($verifix ?? $context->verifix) $this->verifix(); return $this; } function unset(?bool $verifix=null): AssocWrapper { - $this->input->unset($this->arrayKey); + $context = $this->context; + $context->input->unset($context->valueKey); $this->analyze(); - if ($verifix ?? $this->verifix) $this->verifix(); + if ($verifix ?? $context->verifix) $this->verifix(); return $this; } function format($format = null): string { - // TODO: Implement format() method. + return $this->_format($this->context, $format); } function ensureKeys(): bool { diff --git a/src/schema/_assoc/AssocWrapperContext.php b/src/schema/_assoc/AssocWrapperContext.php new file mode 100644 index 0000000..ed25436 --- /dev/null +++ b/src/schema/_assoc/AssocWrapperContext.php @@ -0,0 +1,21 @@ +newWrapper(); - return $wrapper->reset($value, $valueKey); + return $wrapper->reset($value, $valueKey, $verifix); } } diff --git a/src/schema/_scalar/ScalarResult.php b/src/schema/_scalar/ScalarResult.php index 572d936..cc28149 100644 --- a/src/schema/_scalar/ScalarResult.php +++ b/src/schema/_scalar/ScalarResult.php @@ -15,7 +15,7 @@ class ScalarResult extends Result { function isScalar(?ScalarResult &$result=null): bool { $result = $this; return true; } function getKeys(): array { - return [null]; + return ScalarSchema::KEYS; } function select($key): Result { @@ -23,8 +23,7 @@ class ScalarResult extends Result { return $this; } - /** @var array */ - protected $result; + protected array $result; function reset(): void { $this->result = array_merge( diff --git a/src/schema/_scalar/ScalarSchema.php b/src/schema/_scalar/ScalarSchema.php index 44e2ac5..8ff264b 100644 --- a/src/schema/_scalar/ScalarSchema.php +++ b/src/schema/_scalar/ScalarSchema.php @@ -2,6 +2,7 @@ namespace nur\sery\wip\schema\_scalar; use nulib\ref\schema\ref_schema; +use nulib\ValueException; use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; @@ -66,6 +67,17 @@ class ScalarSchema extends Schema { return true; } + const KEYS = [null]; + + function getKeys(): array { + return self::KEYS; + } + + function getSchema($key): Schema { + if ($key !== null) throw ValueException::invalid_key($key); + return $this; + } + protected function newWrapper(): ScalarWrapper { return new ScalarWrapper($this); } diff --git a/src/schema/_scalar/ScalarWrapper.php b/src/schema/_scalar/ScalarWrapper.php index 5bcb847..3ff48fb 100644 --- a/src/schema/_scalar/ScalarWrapper.php +++ b/src/schema/_scalar/ScalarWrapper.php @@ -12,28 +12,23 @@ use nur\sery\wip\schema\Wrapper; class ScalarWrapper extends Wrapper { function __construct(ScalarSchema $schema, &$value=null, $valueKey=null, ?array $params=null) { - $verifix = $params["verifix"] ?? true; - $throw = $params["throw"] ?? null; + $this->context = $context = new WrapperContext($schema, null, null, new ScalarResult(), $params); + + $throw = $context->throw; if ($value !== null && $throw === null) { # Si $value est null, ne pas lancer d'exception, parce qu'on considère que # c'est une initialisation sans conséquences $throw = true; } - $this->context = new WrapperContext($schema, $this, null, null, new ScalarResult()); - $this->verifix = $verifix; - $this->throw = $throw ?? false; + $context->throw = $throw ?? false; $this->reset($value, $valueKey); - $this->throw = $throw ?? true; + $context->throw = $throw ?? true; } function isScalar(?ScalarWrapper &$wrapper=null): bool { $wrapper = $this; return true; } protected WrapperContext $context; - protected bool $verifix; - - protected bool $throw; - protected function newInput(&$value): Input { return new Input($value); } @@ -41,16 +36,17 @@ class ScalarWrapper extends Wrapper { function reset(&$value, $valueKey=null, ?bool $verifix=null): Wrapper { if ($value instanceof Input) $input = $value; else $input = $this->newInput($value); - $this->context->input = $input; - $this->context->valueKey = $valueKey; - $this->context->type = null; + $context = $this->context; + $context->input = $input; + $context->valueKey = $valueKey; + $context->type = null; $this->analyze(); - if ($verifix ?? $this->verifix) $this->verifix(); + if ($verifix ?? $context->verifix) $this->verifix(); return $this; } function getKeys(): array { - return [null]; + return ScalarSchema::KEYS; } /** @param string|int|null $key */ @@ -164,7 +160,7 @@ class ScalarWrapper extends Wrapper { /** @var func $analyzerFunc */ $analyzerFunc = $schema->analyzerFunc; - if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context]); + if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context, $this]); else $what = $this->analyze0(); if ($what !== ref_analyze::STRING) return $what; @@ -172,7 +168,7 @@ class ScalarWrapper extends Wrapper { try { /** @var func $extractorFunc */ $extractorFunc = $schema->extractorFunc; - if ($extractorFunc !== null) $extracted = $extractorFunc->invoke([$value, $context]); + if ($extractorFunc !== null) $extracted = $extractorFunc->invoke([$value, $context, $this]); else $extracted = $context->type->extract($value); $context->value = $extracted; } catch (ValueException $e) { @@ -183,7 +179,7 @@ class ScalarWrapper extends Wrapper { try { /** @var func $parserFunc */ $parserFunc = $schema->parserFunc; - if ($parserFunc !== null) $parsed = $parserFunc->invoke([$extracted, $context]); + if ($parserFunc !== null) $parsed = $parserFunc->invoke([$extracted, $context, $this]); else $parsed = $context->type->parse($extracted); $context->value = $parsed; } catch (ValueException $e) { @@ -209,7 +205,6 @@ class ScalarWrapper extends Wrapper { /** @var ScalarResult $result */ $result = $context->result; - $verifix = false; $modified = false; if ($result->resultAvailable) { @@ -238,16 +233,15 @@ class ScalarWrapper extends Wrapper { /** @var func $normalizerFunc */ $normalizerFunc = $schema->normalizerFunc; if ($normalizerFunc !== null) { - $context = new WrapperContext($schema, $this, $input, $valueKey, $result); $orig = $value; - $value = $normalizerFunc->invoke([$orig, $context]); + $value = $normalizerFunc->invoke([$orig, $context, $this]); $modified = $value !== $orig; } else { - $modified = $this->type->verifix($value, $result, $schema); + $modified = $context->type->verifix($value, $result, $schema); } if ($result->valid) $input->set($value, $valueKey); } - if (!$result->valid) $result->throw($throw ?? $this->throw); + if (!$result->valid) $result->throw($throw ?? $context->throw); return $modified; } @@ -287,7 +281,7 @@ class ScalarWrapper extends Wrapper { $context = $this->context; $context->input->set($value, $context->valueKey); $this->analyze(); - if ($verifix ?? $this->verifix) $this->verifix(); + if ($verifix ?? $context->verifix) $this->verifix(); return $this; } @@ -295,24 +289,11 @@ class ScalarWrapper extends Wrapper { $context = $this->context; $context->input->unset($context->valueKey); $this->analyze(); - if ($verifix ?? $this->verifix) $this->verifix(); + if ($verifix ?? $context->verifix) $this->verifix(); return $this; } function format($format=null): string { - $context = $this->context; - $value = $context->input->get($context->valueKey); - /** @var func $formatterFunc */ - $formatterFunc = $context->schema->formatterFunc; - if ($formatterFunc !== null) { - # la fonction formatter n'a pas forcément accès au format de la définition - # le lui fournir ici - $format ??= $context->schema->format; - return $formatterFunc->invoke([$value, $format]); - } else { - # on assume que le type a été initialisé avec le format de la définition - # le cas échéant - return $this->type->format($value, $format); - } + return $this->_format($this->context, $format); } } diff --git a/tests/wip/schema/_assoc/AssocSchemaTest.php b/tests/wip/schema/_assoc/AssocSchemaTest.php index 4ac9fca..8f78dd4 100644 --- a/tests/wip/schema/_assoc/AssocSchemaTest.php +++ b/tests/wip/schema/_assoc/AssocSchemaTest.php @@ -90,6 +90,9 @@ class AssocSchemaTest extends TestCase { "name" => "c", "pkey" => "c", "header" => "c", ], ]), $schema->getDefinition()); - yaml::dump($schema->getDefinition()); + //yaml::dump($schema->getDefinition()); + + $wrapper = $schema->getWrapper(); + $wrapper->getKeys(); } } From d148850c1273ebfcf006dce3e94f387dd4a978ef Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Tue, 18 Mar 2025 17:37:55 +0400 Subject: [PATCH 06/27] modifs.mineures sans commentaires --- src/schema/Schema.php | 10 +- src/schema/TODO.md | 5 + src/schema/Wrapper.php | 139 +++++++++++++++--- src/schema/WrapperContext.php | 35 +++-- src/schema/_assoc/AssocSchema.php | 16 +- src/schema/_assoc/AssocWrapper.php | 69 +-------- src/schema/_list/ListSchema.php | 4 +- src/schema/_scalar/ScalarSchema.php | 16 +- src/schema/_scalar/ScalarWrapper.php | 101 ++++--------- tests/wip/schema/_assoc/AssocSchemaTest.php | 4 +- tests/wip/schema/_scalar/ScalarSchemaTest.php | 32 ++-- .../wip/schema/_scalar/ScalarWrapperTest.php | 12 +- 12 files changed, 223 insertions(+), 220 deletions(-) diff --git a/src/schema/Schema.php b/src/schema/Schema.php index a7721f4..4d1a422 100644 --- a/src/schema/Schema.php +++ b/src/schema/Schema.php @@ -80,7 +80,7 @@ abstract class Schema implements ArrayAccess { # schéma d'un scalaire quelconque), on ne l'autorise pas ici throw SchemaException::invalid_schema("definition is required"); } - return self::ns($schema, $definition)->getWrapper($value, $valueKey, $wrapper); + return self::ns($schema, $definition)->getWrapper($value, $valueKey, null, $wrapper); } protected static function have_nature(array $definition, ?string &$nature=null): bool { @@ -98,7 +98,7 @@ abstract class Schema implements ArrayAccess { return false; } - protected static function _normalize(&$definition, $definitionKey=null): void { + protected static function _normalize_definition(&$definition, $definitionKey=null): void { if (!is_array($definition)) $definition = [$definition]; # s'assurer que toutes les clés existent avec leur valeur par défaut $index = 0; @@ -192,11 +192,11 @@ abstract class Schema implements ArrayAccess { switch ($nature[0] ?? null) { case "assoc": foreach ($definition["schema"] as $key => &$keydef) { - self::_normalize($keydef, $key); + self::_normalize_definition($keydef, $key); }; unset($keydef); break; case "list": - self::_normalize($definition["schema"]); + self::_normalize_definition($definition["schema"]); break; } } @@ -285,7 +285,7 @@ abstract class Schema implements ArrayAccess { abstract protected function newWrapper(): Wrapper; - abstract function getWrapper(&$value=null, $valueKey=null, ?Wrapper &$wrapper=null): Wrapper; + abstract function getWrapper(&$value=null, $valueKey=null, ?array $params=null, ?Wrapper &$wrapper=null): Wrapper; ############################################################################# # key & properties diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 73b4aca..b41abbe 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -1,5 +1,10 @@ # nulib\schema +* faire PropertyAccess +* si l'argument de Input() est un objet, utiliser PropertyAccess au lieu de KeyAccess +* possibilité de forcer l'un ou l'autre +* ensureKeys() et orderKeys() se fait au niveau de access + * valeurs composite/computed * analyse / vérification de la valeur complète après calcul du résultat, si tous les résultats sont bons diff --git a/src/schema/Wrapper.php b/src/schema/Wrapper.php index f567702..7d6361f 100644 --- a/src/schema/Wrapper.php +++ b/src/schema/Wrapper.php @@ -6,7 +6,9 @@ use IteratorAggregate; use nulib\php\func; use nur\sery\wip\schema\_assoc\AssocWrapper; use nur\sery\wip\schema\_list\ListWrapper; +use nur\sery\wip\schema\_scalar\ScalarResult; use nur\sery\wip\schema\_scalar\ScalarWrapper; +use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\types\IType; abstract class Wrapper implements ArrayAccess, IteratorAggregate { @@ -14,8 +16,81 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { function isList(?ListWrapper &$wrapper=null): bool { return false; } function isScalar(?ScalarWrapper &$wrapper=null): bool { return false; } - /** spécifier la valeur destination gérée par cet objet */ - abstract function reset(&$value, $valueKey=null, ?bool $verifix=null): self; + protected WrapperContext $context; + + /** changer les paramètres de gestion des valeurs */ + function resetParams(?array $params): void { + $this->context->resetParams($params); + } + + protected function afterModify(?array $params, bool $reset=true): void { + $context = $this->context; + if ($reset) { + $context->type = null; + $context->result->reset(); + $context->analyzed = false; + $context->normalized = false; + } + if ($params["analyze"] ?? $context->analyze) { + $this->analyze($params); + } + if ($context->analyzed) { + if ($params["normalize"] ?? $context->normalize) { + $this->normalize($params); + } + } + } + + protected function newInput(&$value): Input { + return new Input($value); + } + + /** + * spécifier la valeur destination gérée par cet objet. + * + * @param ?array $params paramètres spécifique à cet appel, qui peuvent être + * différent des paramètres par défaut + */ + abstract function reset(&$value, $valueKey=null, ?array $params=null): self; + + /** analyser la valeur */ + abstract protected function _analyze(?array $params): int; + + function analyze(?array $params=null): bool { + $context = $this->context; + $reanalyze = $params["reanalyze"] ?? false; + if ($context->analyzed && !$reanalyze) return false; + + $this->_analyze($params); + $context->analyzed = true; + return true; + } + + /** normaliser la valeur */ + abstract protected function _normalize(?array $params): bool; + + function normalize(?array $params=null): bool { + $context = $this->context; + + // il faut que la valeur soit analysée avant de la normaliser + $this->analyze($params); + if (!$context->analyzed) return false; + + $renormalize = $params["renormalize"] ?? false; + if ($renormalize || !$context->normalized) { + $modified = $this->_normalize($params); + $context->normalized = true; + } else { + $modified = false; + } + + /** @var ScalarResult $result */ + $result = $context->result; + if (!$result->valid) { + $result->throw($params["throw"] ?? $context->throw); + } + return $modified; + } /** * Obtenir la liste des clés valides pour les valeurs accessibles via cet @@ -39,34 +114,60 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } /** - * obtenir le résultat de l'appel d'une des fonctions {@link set()} ou - * {@link unset()} + * obtenir le résultat de l'analyse de la valeur du wrapper sélectionné + * + * cette fonction doit être appelée après {@link set()} ou {@link unset()} et + * après que le wrapper aie été sélectionné avec {@link select()} */ - abstract function getResult(): Result; + function getResult(): Result { + return $this->context->result; + } /** retourner true si la valeur existe */ - abstract function isPresent(): bool; + function isPresent(): bool { + return $this->context->result->present; + } /** retourner le type associé à la valeur */ - abstract function getType(): IType; + function getType(): IType { + return $this->context->type; + } /** retourner true si la valeur est disponible */ - abstract function isAvailable(): bool; + function isAvailable(): bool { + return $this->context->result->available; + } /** retourner true si la valeur est valide */ - abstract function isValid(): bool; + function isValid(): bool { + return $this->context->result->valid; + } /** retourner true si la valeur est dans sa forme normalisée */ - abstract function isNormalized(): bool; + function isNormalized(): bool { + return $this->context->result->normalized; + } - /** obtenir la valeur */ - abstract function get($default=null); - /** remplacer la valeur */ - abstract function set($value): self; + function get($default=null) { + $context = $this->context; + if ($context->result->available) return $context->input->get($context->valueKey); + else return $default; + } - /** supprimer la valeur */ - abstract function unset(): self; + function set($value, ?array $params=null): self { + $context = $this->context; + $context->input->set($value, $context->valueKey); + $this->afterModify($params); + return $this; + } + + function unset(?array $params=null): self { + $context = $this->context; + $context->input->unset($context->valueKey); + $this->afterModify($params); + return $this; + } protected function _format(WrapperContext $context, $format=null): string { $value = $context->input->get($context->valueKey); @@ -85,7 +186,9 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } /** formatter la valeur pour affichage */ - abstract function format($format=null): string; + function format($format=null): string { + return $this->_format($this->context, $format); + } ############################################################################# # key & properties @@ -95,7 +198,7 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } function offsetGet($offset) { - return $this->select($offset); + return $this->select($offset)->get(); } function offsetSet($offset, $value): void { diff --git a/src/schema/WrapperContext.php b/src/schema/WrapperContext.php index 440b8c6..6e523e4 100644 --- a/src/schema/WrapperContext.php +++ b/src/schema/WrapperContext.php @@ -5,39 +5,44 @@ use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\types\IType; class WrapperContext { - function __construct(Schema $schema, ?Input $input, $valueKey, ?Result $result, ?array $params) { - $this->params = $params; - $this->verifix = $params["verifix"] ?? true; - $this->throw = $params["throw"] ?? null; - + function __construct(Schema $schema, ?Input $input, $valueKey, ?array $params) { + $this->resetParams($params); $this->schema = $schema; - //$this->wrapper = $wrapper; if ($input !== null) $this->input = $input; $this->valueKey = $valueKey; - $this->type = null; - if ($result !== null) $this->result = $result; $this->origValue = null; $this->value = null; + $this->type = null; + $this->result = null; } public ?array $params; - public bool $verifix; + public bool $analyze, $analyzed; + public bool $normalize, $normalized; public ?bool $throw; + function resetParams(?array $params): void { + $this->params = $params; + $this->analyze = $params["analyze"] ?? true; + $this->normalize = $params["normalize"] ?? true; + $this->throw = $params["throw"] ?? true; + } + /** schéma de la valeur */ public Schema $schema; - /** instance de Wrapper associé à ce contexte */ - //public Wrapper $wrapper; /** source et destination de la valeur */ public Input $input; /** @var string|int|null clé de la valeur dans le tableau destination */ public $valueKey; - /** type de la valeur après analyse */ - public ?IType $type; - /** résultat de l'analyse de la valeur */ - public Result $result; /** @var mixed */ public $origValue; /** @var mixed */ public $value; + + /** @var string|int|null clé sélectionnée */ + public $selectedKey; + /** type de la valeur de la clé sélectionnée après analyse */ + public ?IType $type; + /** résultat de l'analyse de la valeur de la clé sélectionnée */ + public ?Result $result; } diff --git a/src/schema/_assoc/AssocSchema.php b/src/schema/_assoc/AssocSchema.php index 017a6fd..d7bb88e 100644 --- a/src/schema/_assoc/AssocSchema.php +++ b/src/schema/_assoc/AssocSchema.php @@ -4,7 +4,6 @@ namespace nur\sery\wip\schema\_assoc; use nulib\cl; use nulib\ref\schema\ref_schema; use nulib\ValueException; -use nur\sery\wip\schema\_scalar\ScalarWrapper; use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\Wrapper; @@ -17,7 +16,7 @@ class AssocSchema extends Schema { /** * indiquer si $definition est une définition de schéma de nature tableau - * associatif que {@link normalize()} pourrait normaliser + * associatif que {@link normalize_definition()} pourrait normaliser */ static function isa_definition($definition): bool { if (!is_array($definition)) return false; @@ -29,7 +28,7 @@ class AssocSchema extends Schema { return !cl::have_num_keys($definition); } - static function normalize($definition, $definitionKey=null): array { + static function normalize_definition($definition, $definitionKey=null): array { if (!is_array($definition)) $definition = [$definition]; if (!self::have_nature($definition)) { $definition = [ @@ -38,7 +37,7 @@ class AssocSchema extends Schema { "schema" => $definition, ]; } - self::_normalize($definition, $definitionKey); + self::_normalize_definition($definition, $definitionKey); self::_ensure_nature($definition, "assoc", "array"); return $definition; } @@ -46,7 +45,7 @@ class AssocSchema extends Schema { function __construct($definition=null, $definitionKey=null, bool $normalize=true) { if ($definition === null) $definition = static::SCHEMA; if ($normalize) { - $definition = self::normalize($definition, $definitionKey); + $definition = self::normalize_definition($definition, $definitionKey); $this->_definition = $definition; self::_ensure_type($definition); self::_ensure_schema_instances($definition); @@ -81,11 +80,12 @@ class AssocSchema extends Schema { return new AssocWrapper($this); } - function getWrapper(&$array=null, $arrayKey=null, ?Wrapper &$wrapper=null): AssocWrapper { + function getWrapper(&$value=null, $valueKey=null, ?array $params=null, ?Wrapper &$wrapper=null): AssocWrapper { # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception # cf le code similaire dans ScalarWrapper::__construct() - $verifix = $array !== null || $wrapper !== null; + $verifix = $value !== null || $wrapper !== null; if (!($wrapper instanceof AssocWrapper)) $wrapper = $this->newWrapper(); - return $wrapper->reset($array, $arrayKey, $verifix); + if ($params !== null) $wrapper->resetParams($params); + return $wrapper->reset($value, $valueKey, $verifix); } } diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index 5ce88b1..f7a3a38 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -10,7 +10,6 @@ use nur\sery\wip\schema\WrapperContext; class AssocWrapper extends Wrapper { function __construct(AssocSchema $schema, &$array=null, $arrayKey=null, ?array $params=null) { - $definitionSchema = $schema->getDefinition()["schema"]; $keys = $schema->getKeys(); $keyTypes = []; $keyWrappers = []; @@ -18,7 +17,7 @@ class AssocWrapper extends Wrapper { $keyTypes[$key] = null; $keyWrappers[$key] = $schema->getSchema($key)->getWrapper(); } - $this->context = $context = new AssocWrapperContext($schema, null, null, null, $params); + $this->context = $context = new AssocWrapperContext($schema, null, null, $params); $context->arrayResult = new ScalarResult(); $context->keys = $keys; $context->keyTypes = $keyTypes; @@ -41,18 +40,13 @@ class AssocWrapper extends Wrapper { /** @var AssocWrapperContext */ protected WrapperContext $context; - protected function newInput(&$value): Input { - return new Input($value); - } - - function reset(&$array, $arrayKey=null, ?bool $verifix=null): Wrapper { + function reset(&$array, $arrayKey=null, ?array $params=null): Wrapper { if ($array instanceof Input) $input = $array; else $input = $this->newInput($array); $context = $this->context; $context->input = $input; $context->valueKey = $arrayKey; - $this->analyze(); - if ($verifix ?? $context->verifix) $this->verifix(); + $this->afterModify($params); return $this; } @@ -62,72 +56,17 @@ class AssocWrapper extends Wrapper { /** @param string|int|null $key */ function select($key=null): Wrapper { + #XXX il faut que context contiennent les informations pour la clé sélectionnée if ($key === null) return $this; $wrapper = $this->context->keyWrappers[$key] ?? null; if ($wrapper === null) throw ValueException::invalid_key($key); return $wrapper; } - protected function analyze(): int { - return 0; #XXX - } - - function verifix(?bool $throw=null): bool { - return false; #XXX - } - - function getResult(): AssocResult { - /** @var AssocResult $result */ - $result = $this->context->result; - return $result; - } - - function isPresent(): bool { - return $this->context->result->present; - } - - function getType(): IType { - return $this->context->type; - } - - function isAvailable(): bool { - return $this->context->result->available; - } - - function isValid(): bool { - return $this->context->result->valid; - } - function isNormalized(): bool { return $this->context->result->normalized; } - function get($default=null) { - $context = $this->context; - if ($context->result->available) return $context->input->get($context->valueKey); - else return $default; - } - - function set($value, ?bool $verifix=null): AssocWrapper { - $context = $this->context; - $context->input->set($value, $context->valueKey); - $this->analyze(); - if ($verifix ?? $context->verifix) $this->verifix(); - return $this; - } - - function unset(?bool $verifix=null): AssocWrapper { - $context = $this->context; - $context->input->unset($context->valueKey); - $this->analyze(); - if ($verifix ?? $context->verifix) $this->verifix(); - return $this; - } - - function format($format = null): string { - return $this->_format($this->context, $format); - } - function ensureKeys(): bool { } function orderKeys(): bool { diff --git a/src/schema/_list/ListSchema.php b/src/schema/_list/ListSchema.php index 24dadda..4887e95 100644 --- a/src/schema/_list/ListSchema.php +++ b/src/schema/_list/ListSchema.php @@ -35,7 +35,7 @@ class ListSchema extends Schema { "schema" => $definition[0], ]; } - self::_normalize($definition, $definitionKey); + self::_normalize_definition($definition, $definitionKey); self::_ensure_nature($definition, "list", "array"); return $definition; } @@ -71,7 +71,7 @@ class ListSchema extends Schema { return new ListWrapper($this); } - function getWrapper(&$value=null, $valueKey=null, ?Wrapper &$wrapper=null): ListWrapper { + function getWrapper(&$value=null, $valueKey=null, ?array $params = null, ?Wrapper &$wrapper=null): ListWrapper { # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception # cf le code similaire dans ScalarWrapper::__construct() $verifix = $value !== null || $wrapper !== null; diff --git a/src/schema/_scalar/ScalarSchema.php b/src/schema/_scalar/ScalarSchema.php index 8ff264b..1621e5b 100644 --- a/src/schema/_scalar/ScalarSchema.php +++ b/src/schema/_scalar/ScalarSchema.php @@ -4,7 +4,6 @@ namespace nur\sery\wip\schema\_scalar; use nulib\ref\schema\ref_schema; use nulib\ValueException; use nur\sery\wip\schema\Schema; -use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; /** @@ -16,7 +15,7 @@ class ScalarSchema extends Schema { /** * indiquer si $definition est une définition de schéma scalaire que - * {@link normalize()} pourrait normaliser + * {@link normalize_definition()} pourrait normaliser */ static function isa_definition($definition): bool { # chaine ou null @@ -45,8 +44,8 @@ class ScalarSchema extends Schema { return $haveIndex0 && $count > 1; } - static function normalize($definition, $definitionKey=null): array { - self::_normalize($definition, $definitionKey); + static function normalize_definition($definition, $definitionKey=null): array { + self::_normalize_definition($definition, $definitionKey); self::_ensure_nature($definition, "scalar"); return $definition; } @@ -54,7 +53,7 @@ class ScalarSchema extends Schema { function __construct($definition=null, $definitionKey=null, bool $normalize=true) { if ($definition === null) $definition = static::SCHEMA; if ($normalize) { - $definition = self::normalize($definition, $definitionKey); + $definition = self::normalize_definition($definition, $definitionKey); $this->_definition = $definition; self::_ensure_type($definition); self::_ensure_schema_instances($definition); @@ -82,11 +81,12 @@ class ScalarSchema extends Schema { return new ScalarWrapper($this); } - function getWrapper(&$value=null, $valueKey=null, ?Wrapper &$wrapper=null): ScalarWrapper { + function getWrapper(&$value=null, $valueKey=null, ?array $params=null, ?Wrapper &$wrapper=null): ScalarWrapper { # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception # cf le code similaire dans ScalarWrapper::__construct() - $verifix = $value !== null || $wrapper !== null; + $dontNormalize = $value === null && $wrapper === null; if (!($wrapper instanceof ScalarWrapper)) $wrapper = $this->newWrapper(); - return $wrapper->reset($value, $valueKey, $verifix); + if ($params !== null) $wrapper->resetParams($params); + return $wrapper->reset($value, $valueKey, $dontNormalize? ["normalize" => false]: null); } } diff --git a/src/schema/_scalar/ScalarWrapper.php b/src/schema/_scalar/ScalarWrapper.php index 3ff48fb..3a33684 100644 --- a/src/schema/_scalar/ScalarWrapper.php +++ b/src/schema/_scalar/ScalarWrapper.php @@ -4,22 +4,31 @@ namespace nur\sery\wip\schema\_scalar; use nulib\php\func; use nulib\ref\schema\ref_analyze; use nulib\ValueException; -use nur\sery\wip\schema\WrapperContext; use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\types; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; +use nur\sery\wip\schema\WrapperContext; +/** + * Class ScalarWrapper + * + * @method ScalarResult getResult() + * @method self set() + * @method self unset() + */ class ScalarWrapper extends Wrapper { function __construct(ScalarSchema $schema, &$value=null, $valueKey=null, ?array $params=null) { - $this->context = $context = new WrapperContext($schema, null, null, new ScalarResult(), $params); + $this->context = $context = new WrapperContext($schema, null, null, $params); + $context->result = new ScalarResult(); - $throw = $context->throw; - if ($value !== null && $throw === null) { - # Si $value est null, ne pas lancer d'exception, parce qu'on considère que - # c'est une initialisation sans conséquences - $throw = true; - } + # calculer manuellemet throw ici parce que WrapperContext le met à true par + # défaut. on veut pouvoir mettre temporairement throw à false si jamais il + # n'est pas spécifié par l'utilisateur + $throw = $params["throw"] ?? null; + # Si $value est null, ne pas lancer d'exception, parce qu'on considère que + # c'est une initialisation sans conséquences + if ($throw === null && $value !== null) $throw = true; $context->throw = $throw ?? false; $this->reset($value, $valueKey); $context->throw = $throw ?? true; @@ -29,19 +38,13 @@ class ScalarWrapper extends Wrapper { protected WrapperContext $context; - protected function newInput(&$value): Input { - return new Input($value); - } - - function reset(&$value, $valueKey=null, ?bool $verifix=null): Wrapper { + function reset(&$value, $valueKey=null, ?array $params=null): Wrapper { + $context = $this->context; if ($value instanceof Input) $input = $value; else $input = $this->newInput($value); - $context = $this->context; $context->input = $input; $context->valueKey = $valueKey; - $context->type = null; - $this->analyze(); - if ($verifix ?? $context->verifix) $this->verifix(); + $this->afterModify($params); return $this; } @@ -56,7 +59,7 @@ class ScalarWrapper extends Wrapper { } /** analyser la valeur et résoudre son type */ - protected function analyze0(): int { + protected function _analyze0(): int { $context = $this->context; /** @var ScalarSchema $schema */ $schema = $context->schema; @@ -123,7 +126,7 @@ class ScalarWrapper extends Wrapper { $type = $firstType; } } - $context->type = $this->type = $type; + $context->type = $type; if (!$type->isAvailable($input, $valueKey)) { if ($default !== null) { @@ -148,7 +151,7 @@ class ScalarWrapper extends Wrapper { } } - protected function analyze(): int { + protected function _analyze(?array $params): int { $context = $this->context; /** @var ScalarSchema $schema */ $schema = $context->schema; @@ -156,12 +159,11 @@ class ScalarWrapper extends Wrapper { $valueKey = $context->valueKey; /** @var ScalarResult $result */ $result = $context->result; - $result->reset(); /** @var func $analyzerFunc */ $analyzerFunc = $schema->analyzerFunc; if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context, $this]); - else $what = $this->analyze0(); + else $what = $this->_analyze0(); if ($what !== ref_analyze::STRING) return $what; $value = $context->value; @@ -196,7 +198,7 @@ class ScalarWrapper extends Wrapper { } } - function verifix(?bool $throw=null): bool { + protected function _normalize(?array $params): bool { $context = $this->context; /** @var ScalarSchema $schema */ $schema = $context->schema; @@ -241,59 +243,6 @@ class ScalarWrapper extends Wrapper { } if ($result->valid) $input->set($value, $valueKey); } - if (!$result->valid) $result->throw($throw ?? $context->throw); return $modified; } - - function getResult(): ScalarResult { - /** @var ScalarResult $result */ - $result = $this->context->result; - return $result; - } - - function isPresent(): bool { - return $this->context->result->present; - } - - function getType(): IType { - return $this->context->type; - } - - function isAvailable(): bool { - return $this->context->result->available; - } - - function isValid(): bool { - return $this->context->result->valid; - } - - function isNormalized(): bool { - return $this->context->result->normalized; - } - - function get($default=null) { - $context = $this->context; - if ($context->result->available) return $context->input->get($context->valueKey); - else return $default; - } - - function set($value, ?bool $verifix=null): ScalarWrapper { - $context = $this->context; - $context->input->set($value, $context->valueKey); - $this->analyze(); - if ($verifix ?? $context->verifix) $this->verifix(); - return $this; - } - - function unset(?bool $verifix=null): ScalarWrapper { - $context = $this->context; - $context->input->unset($context->valueKey); - $this->analyze(); - if ($verifix ?? $context->verifix) $this->verifix(); - return $this; - } - - function format($format=null): string { - return $this->_format($this->context, $format); - } } diff --git a/tests/wip/schema/_assoc/AssocSchemaTest.php b/tests/wip/schema/_assoc/AssocSchemaTest.php index 8f78dd4..384f5d6 100644 --- a/tests/wip/schema/_assoc/AssocSchemaTest.php +++ b/tests/wip/schema/_assoc/AssocSchemaTest.php @@ -44,7 +44,7 @@ class AssocSchemaTest extends TestCase { "type" => ["string"], "nullable" => false, "name" => "a", "pkey" => "a", "header" => "a", ], - ]), AssocSchema::normalize(["a" => "string"])); + ]), AssocSchema::normalize_definition(["a" => "string"])); self::assertSame(self::schema([ "type" => ["array"], "nullable" => true, @@ -61,7 +61,7 @@ class AssocSchemaTest extends TestCase { "type" => ["bool"], "nullable" => false, "name" => "c", "pkey" => "c", "header" => "c", ], - ]), AssocSchema::normalize([ + ]), AssocSchema::normalize_definition([ "a" => "string", "b" => "int", "c" => "bool", diff --git a/tests/wip/schema/_scalar/ScalarSchemaTest.php b/tests/wip/schema/_scalar/ScalarSchemaTest.php index c862fa5..a5b6cee 100644 --- a/tests/wip/schema/_scalar/ScalarSchemaTest.php +++ b/tests/wip/schema/_scalar/ScalarSchemaTest.php @@ -32,33 +32,33 @@ class ScalarSchemaTest extends TestCase { } function testNormalize() { - self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize(null)); - self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize([])); - self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize([null])); + self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize_definition(null)); + self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize_definition([])); + self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize_definition([null])); self::assertException(SchemaException::class, function () { - ScalarSchema::normalize([[]]); + ScalarSchema::normalize_definition([[]]); }); self::assertException(SchemaException::class, function () { - ScalarSchema::normalize([[null]]); + ScalarSchema::normalize_definition([[null]]); }); $string = self::schema(["type" => ["string"], "nullable" => false]); - self::assertSame($string, ScalarSchema::normalize("string")); - self::assertSame($string, ScalarSchema::normalize(["string"])); + self::assertSame($string, ScalarSchema::normalize_definition("string")); + self::assertSame($string, ScalarSchema::normalize_definition(["string"])); $nstring = self::schema(["type" => ["string"]]); - self::assertSame($nstring, ScalarSchema::normalize(["?string"])); - self::assertSame($nstring, ScalarSchema::normalize(["?string|null"])); - self::assertSame($nstring, ScalarSchema::normalize(["string|null"])); - self::assertSame($nstring, ScalarSchema::normalize([["?string", "null"]])); - self::assertSame($nstring, ScalarSchema::normalize([["string", "null"]])); - self::assertSame($nstring, ScalarSchema::normalize([["string", null]])); + self::assertSame($nstring, ScalarSchema::normalize_definition(["?string"])); + self::assertSame($nstring, ScalarSchema::normalize_definition(["?string|null"])); + self::assertSame($nstring, ScalarSchema::normalize_definition(["string|null"])); + self::assertSame($nstring, ScalarSchema::normalize_definition([["?string", "null"]])); + self::assertSame($nstring, ScalarSchema::normalize_definition([["string", "null"]])); + self::assertSame($nstring, ScalarSchema::normalize_definition([["string", null]])); $key = self::schema(["type" => ["string", "int"], "nullable" => false]); - self::assertSame($key, ScalarSchema::normalize("string|int")); + self::assertSame($key, ScalarSchema::normalize_definition("string|int")); $nkey = self::schema(["type" => ["string", "int"], "nullable" => true]); - self::assertSame($nkey, ScalarSchema::normalize("?string|int")); - self::assertSame($nkey, ScalarSchema::normalize("string|?int")); + self::assertSame($nkey, ScalarSchema::normalize_definition("?string|int")); + self::assertSame($nkey, ScalarSchema::normalize_definition("string|?int")); } } diff --git a/tests/wip/schema/_scalar/ScalarWrapperTest.php b/tests/wip/schema/_scalar/ScalarWrapperTest.php index 6e9326b..a78e548 100644 --- a/tests/wip/schema/_scalar/ScalarWrapperTest.php +++ b/tests/wip/schema/_scalar/ScalarWrapperTest.php @@ -15,19 +15,21 @@ class ScalarWrapperTest extends TestCase { self::assertSame($normalized, $wrapper->isNormalized(), "normalized"); } - function checkVerifix(ScalarSchema $schema, $orig, bool $verifix, $value, bool $present, bool $available, bool $valid, bool $normalized, ?array $inputParams=null): void { + function checkVerifix(ScalarSchema $schema, $orig, bool $normalize, $value, bool $present, bool $available, bool $valid, bool $normalized, ?array $inputParams=null): void { $wrapper = $schema->getWrapper(); + $wrapper->resetParams(["normalize" => $normalize]); if ($inputParams !== null) $input = new Input($orig, $inputParams); else $input = $orig; - $wrapper->reset($input, null, $verifix); + $wrapper->reset($input); $this->checkValue($wrapper, $value, $present, $available, $valid, $normalized); } - function checkException(ScalarSchema $schema, $orig, bool $verifix, string $exceptionClass, ?array $inputParams=null) { + function checkException(ScalarSchema $schema, $orig, bool $normalize, string $exceptionClass, ?array $inputParams=null) { $wrapper = $schema->getWrapper(); if ($inputParams !== null) $orig = new Input($orig, $inputParams); - self::assertException($exceptionClass, function() use ($wrapper, &$orig, $verifix) { - $wrapper->reset($orig, null, $verifix); + self::assertException($exceptionClass, function() use ($wrapper, &$orig, $normalize) { + $wrapper->resetParams(["normalize" => $normalize]); + $wrapper->reset($orig); }); } From 3608b02749e13a24c88f761b2e5b11baa7552752 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 06:38:19 +0400 Subject: [PATCH 07/27] modifs.mineures sans commentaires --- src/schema/Result.php | 7 - src/schema/Schema.php | 12 +- src/schema/TODO.md | 4 +- src/schema/Wrapper.php | 65 ++++++---- src/schema/WrapperContext.php | 1 + src/schema/_assoc/AssocResult.php | 50 -------- src/schema/_assoc/AssocSchema.php | 14 +- src/schema/_assoc/AssocWrapper.php | 120 ++++++++++++++---- src/schema/_assoc/AssocWrapperContext.php | 11 +- src/schema/_scalar/ScalarSchema.php | 11 +- src/schema/_scalar/ScalarWrapper.php | 12 +- tests/wip/schema/_assoc/AssocSchemaTest.php | 9 +- tests/wip/schema/_scalar/ScalarSchemaTest.php | 6 +- 13 files changed, 186 insertions(+), 136 deletions(-) delete mode 100644 src/schema/_assoc/AssocResult.php diff --git a/src/schema/Result.php b/src/schema/Result.php index 46f08ee..21c2b7f 100644 --- a/src/schema/Result.php +++ b/src/schema/Result.php @@ -2,9 +2,6 @@ namespace nur\sery\wip\schema; use IteratorAggregate; -use nur\sery\wip\schema\_assoc\AssocResult; -use nur\sery\wip\schema\_list\ListResult; -use nur\sery\wip\schema\_scalar\ScalarResult; use Throwable; /** @@ -37,10 +34,6 @@ abstract class Result implements IteratorAggregate { $this->reset(); } - function isAssoc(?AssocResult &$result=null): bool { return false; } - function isList(?ListResult &$result=null): bool { return false; } - function isScalar(?ScalarResult &$result=null): bool { return false; } - /** * Obtenir la liste des clés valides pour les valeurs accessibles via cet * objet diff --git a/src/schema/Schema.php b/src/schema/Schema.php index 4d1a422..aef756d 100644 --- a/src/schema/Schema.php +++ b/src/schema/Schema.php @@ -98,18 +98,18 @@ abstract class Schema implements ArrayAccess { return false; } - protected static function _normalize_definition(&$definition, $definitionKey=null): void { + protected static function _normalize_definition(&$definition, $definitionKey=null, ?array $natureMetaschema=null): void { if (!is_array($definition)) $definition = [$definition]; # s'assurer que toutes les clés existent avec leur valeur par défaut $index = 0; - foreach (array_keys(ref_schema::SCALAR_METASCHEMA) as $key) { + foreach (array_keys(ref_schema::VALUE_METASCHEMA) as $key) { if (!array_key_exists($key, $definition)) { if (array_key_exists($index, $definition)) { $definition[$key] = $definition[$index]; unset($definition[$index]); $index++; } else { - $definition[$key] = ref_schema::SCALAR_METASCHEMA[$key][1]; + $definition[$key] = ref_schema::VALUE_METASCHEMA[$key][1]; } } } @@ -161,6 +161,12 @@ abstract class Schema implements ArrayAccess { # nature $nature = $definition[""]; tarray::ensure_array($nature); + $natureMetaschema ??= ref_schema::NATURE_METASCHEMA; + foreach (array_keys($natureMetaschema) as $key) { + if (!array_key_exists($key, $nature)) { + $nature[$key] = $natureMetaschema[$key][1]; + } + } $definition[""] = $nature; # name, pkey, header $name = $definition["name"]; diff --git a/src/schema/TODO.md b/src/schema/TODO.md index b41abbe..745781f 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -2,8 +2,8 @@ * faire PropertyAccess * si l'argument de Input() est un objet, utiliser PropertyAccess au lieu de KeyAccess -* possibilité de forcer l'un ou l'autre -* ensureKeys() et orderKeys() se fait au niveau de access + * possibilité de forcer l'un ou l'autre (paramètre type=value|array|object) +* ensureKeys() et orderKeys() se fait au niveau de access (ou input?) * valeurs composite/computed * analyse / vérification de la valeur complète après calcul du résultat, si diff --git a/src/schema/Wrapper.php b/src/schema/Wrapper.php index 7d6361f..4cf6a9a 100644 --- a/src/schema/Wrapper.php +++ b/src/schema/Wrapper.php @@ -23,14 +23,17 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { $this->context->resetParams($params); } - protected function afterModify(?array $params, bool $reset=true): void { + protected function resetContext($resetSelectedKey): void { $context = $this->context; - if ($reset) { - $context->type = null; - $context->result->reset(); - $context->analyzed = false; - $context->normalized = false; - } + $context->type = null; + $context->result->reset(); + $context->analyzed = false; + $context->normalized = false; + } + + protected function afterModify(?array $params, $resetSelectedKey=false): void { + $context = $this->context; + $this->resetContext($resetSelectedKey); if ($params["analyze"] ?? $context->analyze) { $this->analyze($params); } @@ -51,7 +54,15 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { * @param ?array $params paramètres spécifique à cet appel, qui peuvent être * différent des paramètres par défaut */ - abstract function reset(&$value, $valueKey=null, ?array $params=null): self; + function reset(&$value, $valueKey=null, ?array $params=null): Wrapper { + $context = $this->context; + if ($value instanceof Input) $input = $value; + else $input = $this->newInput($value); + $context->input = $input; + $context->valueKey = $valueKey; + $this->afterModify($params, true); + return $this; + } /** analyser la valeur */ abstract protected function _analyze(?array $params): int; @@ -119,50 +130,50 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { * cette fonction doit être appelée après {@link set()} ou {@link unset()} et * après que le wrapper aie été sélectionné avec {@link select()} */ - function getResult(): Result { + function getResult($key=false): Result { return $this->context->result; } /** retourner true si la valeur existe */ - function isPresent(): bool { - return $this->context->result->present; + function isPresent($key=false): bool { + return $this->getResult()->present; } /** retourner le type associé à la valeur */ - function getType(): IType { + function getType($key=false): IType { return $this->context->type; } /** retourner true si la valeur est disponible */ - function isAvailable(): bool { - return $this->context->result->available; + function isAvailable($key=false): bool { + return $this->getResult()->available; } /** retourner true si la valeur est valide */ - function isValid(): bool { - return $this->context->result->valid; + function isValid($key=false): bool { + return $this->getResult()->valid; } /** retourner true si la valeur est dans sa forme normalisée */ - function isNormalized(): bool { - return $this->context->result->normalized; + function isNormalized($key=false): bool { + return $this->getResult()->normalized; } - function get($default=null) { + function get($default=null, $key=false) { $context = $this->context; - if ($context->result->available) return $context->input->get($context->valueKey); - else return $default; + if (!$context->result->available) return $default; + return $context->input->get($context->valueKey); } - function set($value, ?array $params=null): self { + function set($value, ?array $params=null, $key=false): self { $context = $this->context; $context->input->set($value, $context->valueKey); $this->afterModify($params); return $this; } - function unset(?array $params=null): self { + function unset(?array $params=null, $key=false): self { $context = $this->context; $context->input->unset($context->valueKey); $this->afterModify($params); @@ -186,7 +197,7 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } /** formatter la valeur pour affichage */ - function format($format=null): string { + function format($format=null, $key=false): string { return $this->_format($this->context, $format); } @@ -198,14 +209,14 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } function offsetGet($offset) { - return $this->select($offset)->get(); + return $this->get(null, $offset); } function offsetSet($offset, $value): void { - $this->select($offset)->set($value); + $this->set($value, null, $offset); } function offsetUnset($offset): void { - $this->select($offset)->unset(); + $this->unset(null, $offset); } } diff --git a/src/schema/WrapperContext.php b/src/schema/WrapperContext.php index 6e523e4..d144939 100644 --- a/src/schema/WrapperContext.php +++ b/src/schema/WrapperContext.php @@ -12,6 +12,7 @@ class WrapperContext { $this->valueKey = $valueKey; $this->origValue = null; $this->value = null; + $this->selectedKey = null; $this->type = null; $this->result = null; } diff --git a/src/schema/_assoc/AssocResult.php b/src/schema/_assoc/AssocResult.php deleted file mode 100644 index 76a2a74..0000000 --- a/src/schema/_assoc/AssocResult.php +++ /dev/null @@ -1,50 +0,0 @@ -context = $context; - parent::__construct(); - } - - function isAssoc(?AssocResult &$result=null): bool { $result = $this; return true;} - - protected AssocWrapperContext $context; - - function getKeys(): array { - return $this->context->keys; - } - - protected Result $result; - - function select($key): AssocResult { - $context = $this->context; - if ($key === null) { - $this->result = $context->arrayResult; - return $this; - } - $wrapper = $context->keyWrappers[$key] ?? null; - if ($wrapper === null) throw ValueException::invalid_key($key); - $this->result = $wrapper->getResult(); - return $this; - } - - function reset(): void { - $context = $this->context; - $context->arrayResult->reset(); - foreach ($context->keyWrappers as $wrapper) { - $wrapper->getResult()->reset(); - } - } - - function __get(string $name) { - return $this->result[$name]; - } - - function __set(string $name, $value): void { - $this->result[$name] = $value; - } -} diff --git a/src/schema/_assoc/AssocSchema.php b/src/schema/_assoc/AssocSchema.php index d7bb88e..e49d794 100644 --- a/src/schema/_assoc/AssocSchema.php +++ b/src/schema/_assoc/AssocSchema.php @@ -11,8 +11,11 @@ use nur\sery\wip\schema\Wrapper; * Class AssocSchema */ class AssocSchema extends Schema { - /** @var array meta-schema d'un schéma de nature tableau associatif */ - const METASCHEMA = ref_schema::ASSOC_METASCHEMA; + //const METASCHEMA = ref_schema::VALUE_METASCHEMA; + //const NATURE_METASCHEMA = [ + // ...ref_schema::NATURE_METASCHEMA, + // ...ref_schema::ASSOC_NATURE_METASCHEMA, + //]; /** * indiquer si $definition est une définition de schéma de nature tableau @@ -37,7 +40,8 @@ class AssocSchema extends Schema { "schema" => $definition, ]; } - self::_normalize_definition($definition, $definitionKey); + $natureMetaschema = array_merge(ref_schema::NATURE_METASCHEMA, ref_schema::ASSOC_NATURE_METASCHEMA); + self::_normalize_definition($definition, $definitionKey, $natureMetaschema); self::_ensure_nature($definition, "assoc", "array"); return $definition; } @@ -83,9 +87,9 @@ class AssocSchema extends Schema { function getWrapper(&$value=null, $valueKey=null, ?array $params=null, ?Wrapper &$wrapper=null): AssocWrapper { # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception # cf le code similaire dans ScalarWrapper::__construct() - $verifix = $value !== null || $wrapper !== null; + $dontNormalize = $value === null && $wrapper === null; if (!($wrapper instanceof AssocWrapper)) $wrapper = $this->newWrapper(); if ($params !== null) $wrapper->resetParams($params); - return $wrapper->reset($value, $valueKey, $verifix); + return $wrapper->reset($value, $valueKey, $dontNormalize? ["normalize" => false]: null); } } diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index f7a3a38..029d5b7 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -4,12 +4,13 @@ namespace nur\sery\wip\schema\_assoc; use nulib\ValueException; use nur\sery\wip\schema\_scalar\ScalarResult; use nur\sery\wip\schema\input\Input; +use nur\sery\wip\schema\Result; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; use nur\sery\wip\schema\WrapperContext; class AssocWrapper extends Wrapper { - function __construct(AssocSchema $schema, &$array=null, $arrayKey=null, ?array $params=null) { + function __construct(AssocSchema $schema, &$value=null, $valueKey=null, ?array $params=null) { $keys = $schema->getKeys(); $keyTypes = []; $keyWrappers = []; @@ -22,16 +23,17 @@ class AssocWrapper extends Wrapper { $context->keys = $keys; $context->keyTypes = $keyTypes; $context->keyWrappers = $keyWrappers; - $context->result = new AssocResult($context); + $context->result = $context->arrayResult; - $throw = $context->throw; - if ($array !== null && $throw === null) { - # Si $value est null, ne pas lancer d'exception, parce qu'on considère que - # c'est une initialisation sans conséquences - $throw = true; - } + # calculer manuellemet throw ici parce que WrapperContext le met à true par + # défaut. on veut pouvoir mettre temporairement throw à false si jamais il + # n'est pas spécifié par l'utilisateur + $throw = $params["throw"] ?? null; + # Si $value est null, ne pas lancer d'exception, parce qu'on considère que + # c'est une initialisation sans conséquences + if ($throw === null && $value !== null) $throw = true; $context->throw = $throw ?? false; - $this->reset($array, $arrayKey); + $this->reset($value, $valueKey); $context->throw = $throw ?? true; } @@ -40,35 +42,103 @@ class AssocWrapper extends Wrapper { /** @var AssocWrapperContext */ protected WrapperContext $context; - function reset(&$array, $arrayKey=null, ?array $params=null): Wrapper { - if ($array instanceof Input) $input = $array; - else $input = $this->newInput($array); + protected function resetContext($resetSelectedKey): void { $context = $this->context; - $context->input = $input; - $context->valueKey = $arrayKey; - $this->afterModify($params); - return $this; + $context->arrayResult->reset(); + foreach ($context->keyWrappers as $wrapper) { + $wrapper->getResult()->reset(); + } + $context->analyzed = false; + $context->normalized = false; + if ($resetSelectedKey) { + $context->selectedKey = null; + $context->type = $context->arrayType; + $context->result = $context->arrayResult; + } } function getKeys(): array { return $this->context->keys; } - /** @param string|int|null $key */ - function select($key=null): Wrapper { - #XXX il faut que context contiennent les informations pour la clé sélectionnée - if ($key === null) return $this; - $wrapper = $this->context->keyWrappers[$key] ?? null; + protected function _getWrapper($key): Wrapper { + $wrapper = $context->keyWrappers[$key] ?? null; if ($wrapper === null) throw ValueException::invalid_key($key); return $wrapper; } - function isNormalized(): bool { - return $this->context->result->normalized; + /** @param string|int|null $key */ + function select($key=null): Wrapper { + $context = $this->context; + if ($key === null) { + $context->selectedKey = null; + $context->type = $context->arrayType; + $context->result = $context->arrayResult; + return $this; + } + $wrapper = $this->_getWrapper($key); + $context->selectedKey = $key; + $context->type = $wrapper->getType(); + $context->result = $wrapper->getResult(); + return $wrapper; } - function ensureKeys(): bool { + protected function _analyze(?array $params): int { + return -1; } - function orderKeys(): bool { + + protected function _normalize(?array $params): bool { + return false; + } + + function getResult($key=false): Result { + if ($key === false) return $this->context->result; + elseif ($key === null) return $this->context->arrayResult; + else return $this->_getWrapper($key)->getResult(); + } + + function getType($key=false): IType { + if ($key === false) return $this->context->type; + elseif ($key === null) return $this->context->arrayType; + else return $this->_getWrapper($key)->getType(); + } + + function get($default=null, $key=false) { + $context = $this->context; + if (!$context->arrayResult->available) return $default; + if ($key === false) $key = $context->selectedKey; + if ($key === null) return $context->input->get($context->valueKey); + else return $this->_getWrapper($key)->get($default); + } + + function set($value, ?array $params=null, $key=false): Wrapper { + $context = $this->context; + if ($key === false) $key = $context->selectedKey; + if ($key === null) { + $context->input->set($value, $context->valueKey); + $this->afterModify($params); + } else { + $this->_getWrapper($key)->set($value); + } + return $this; + } + + function unset(?array $params=null, $key=false): Wrapper { + $context = $this->context; + if ($key === false) $key = $context->selectedKey; + if ($key === null) { + $context->input->unset($context->valueKey); + $this->afterModify($params); + } else { + $this->_getWrapper($key)->unset(); + } + return $this; + } + + function format($format=null, $key=false): string { + $context = $this->context; + if ($key === false) $key = $context->selectedKey; + if ($key === null) return $this->_format($context, $format); + else return $this->_getWrapper($key)->format($format); } } diff --git a/src/schema/_assoc/AssocWrapperContext.php b/src/schema/_assoc/AssocWrapperContext.php index ed25436..44fee29 100644 --- a/src/schema/_assoc/AssocWrapperContext.php +++ b/src/schema/_assoc/AssocWrapperContext.php @@ -2,13 +2,22 @@ namespace nur\sery\wip\schema\_assoc; use nur\sery\wip\schema\_scalar\ScalarResult; +use nur\sery\wip\schema\input\Input; +use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; use nur\sery\wip\schema\WrapperContext; class AssocWrapperContext extends WrapperContext { + function __construct(Schema $schema, ?Input $input, $valueKey, ?array $params) { + parent::__construct($schema, $input, $valueKey, $params); + $this->arrayType = null; + $this->arrayResult = null; + } + + public ?IType $arrayType; /** résultat de l'analyse du tableau */ - public ScalarResult $arrayResult; + public ?ScalarResult $arrayResult; /** liste des clés valides */ public array $keys; diff --git a/src/schema/_scalar/ScalarSchema.php b/src/schema/_scalar/ScalarSchema.php index 1621e5b..d726ebb 100644 --- a/src/schema/_scalar/ScalarSchema.php +++ b/src/schema/_scalar/ScalarSchema.php @@ -1,6 +1,7 @@ context; - if ($value instanceof Input) $input = $value; - else $input = $this->newInput($value); - $context->input = $input; - $context->valueKey = $valueKey; - $this->afterModify($params); - return $this; - } - function getKeys(): array { return ScalarSchema::KEYS; } diff --git a/tests/wip/schema/_assoc/AssocSchemaTest.php b/tests/wip/schema/_assoc/AssocSchemaTest.php index 384f5d6..a082855 100644 --- a/tests/wip/schema/_assoc/AssocSchemaTest.php +++ b/tests/wip/schema/_assoc/AssocSchemaTest.php @@ -7,7 +7,14 @@ use nur\sery\wip\schema\_scalar\ScalarSchemaTest; class AssocSchemaTest extends TestCase { const NULL_SCHEMA = [ - "" => ["assoc"], + "" => [ + "assoc", + "compute_func" => null, + "validate_func" => null, + "ensure_array" => false, + "ensure_keys" => true, + "ensure_order" => true, + ], "schema" => null, "type" => [null], "default" => null, diff --git a/tests/wip/schema/_scalar/ScalarSchemaTest.php b/tests/wip/schema/_scalar/ScalarSchemaTest.php index a5b6cee..5742fb8 100644 --- a/tests/wip/schema/_scalar/ScalarSchemaTest.php +++ b/tests/wip/schema/_scalar/ScalarSchemaTest.php @@ -19,7 +19,11 @@ class ScalarSchemaTest extends TestCase { "messages" => null, "formatter_func" => null, "format" => null, - "" => ["scalar"], + "" => [ + "scalar", + "compute_func" => null, + "validate_func" => null, + ], "schema" => null, "name" => null, "pkey" => null, From b9e91bd91745615351ba09a53cb175620cb21391 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 07:18:41 +0400 Subject: [PATCH 08/27] modifs.mineures sans commentaires --- src/schema/_assoc/AssocWrapper.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index 029d5b7..0ee3800 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -23,7 +23,6 @@ class AssocWrapper extends Wrapper { $context->keys = $keys; $context->keyTypes = $keyTypes; $context->keyWrappers = $keyWrappers; - $context->result = $context->arrayResult; # calculer manuellemet throw ici parce que WrapperContext le met à true par # défaut. on veut pouvoir mettre temporairement throw à false si jamais il From 62fc315b9e472bbd595412db90b299cdc1e22e7c Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 08:37:17 +0400 Subject: [PATCH 09/27] modifs.mineures sans commentaires --- src/schema/Wrapper.php | 8 +++--- src/schema/_assoc/AssocSchema.php | 8 +++--- src/schema/_scalar/ScalarSchema.php | 4 +-- tests/wip/schema/_assoc/AssocSchemaTest.php | 31 +++++++++++++++++++-- 4 files changed, 39 insertions(+), 12 deletions(-) diff --git a/src/schema/Wrapper.php b/src/schema/Wrapper.php index 4cf6a9a..d8e1e4d 100644 --- a/src/schema/Wrapper.php +++ b/src/schema/Wrapper.php @@ -136,7 +136,7 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { /** retourner true si la valeur existe */ function isPresent($key=false): bool { - return $this->getResult()->present; + return $this->getResult($key)->present; } /** retourner le type associé à la valeur */ @@ -146,17 +146,17 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { /** retourner true si la valeur est disponible */ function isAvailable($key=false): bool { - return $this->getResult()->available; + return $this->getResult($key)->available; } /** retourner true si la valeur est valide */ function isValid($key=false): bool { - return $this->getResult()->valid; + return $this->getResult($key)->valid; } /** retourner true si la valeur est dans sa forme normalisée */ function isNormalized($key=false): bool { - return $this->getResult()->normalized; + return $this->getResult($key)->normalized; } diff --git a/src/schema/_assoc/AssocSchema.php b/src/schema/_assoc/AssocSchema.php index e49d794..6d3ba16 100644 --- a/src/schema/_assoc/AssocSchema.php +++ b/src/schema/_assoc/AssocSchema.php @@ -85,11 +85,11 @@ class AssocSchema extends Schema { } function getWrapper(&$value=null, $valueKey=null, ?array $params=null, ?Wrapper &$wrapper=null): AssocWrapper { - # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception - # cf le code similaire dans ScalarWrapper::__construct() - $dontNormalize = $value === null && $wrapper === null; + # si pas de valeur ni de wrapper, pas d'analyse et donc pas d'exception + # cf le code similaire dans AssocWrapper::__construct() + $dontAnalyze = $value === null && $wrapper === null; if (!($wrapper instanceof AssocWrapper)) $wrapper = $this->newWrapper(); if ($params !== null) $wrapper->resetParams($params); - return $wrapper->reset($value, $valueKey, $dontNormalize? ["normalize" => false]: null); + return $wrapper->reset($value, $valueKey, $dontAnalyze? ["analyze" => false]: null); } } diff --git a/src/schema/_scalar/ScalarSchema.php b/src/schema/_scalar/ScalarSchema.php index d726ebb..5c14a5c 100644 --- a/src/schema/_scalar/ScalarSchema.php +++ b/src/schema/_scalar/ScalarSchema.php @@ -89,9 +89,9 @@ class ScalarSchema extends Schema { function getWrapper(&$value=null, $valueKey=null, ?array $params=null, ?Wrapper &$wrapper=null): ScalarWrapper { # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception # cf le code similaire dans ScalarWrapper::__construct() - $dontNormalize = $value === null && $wrapper === null; + $dontAnalyze = $value === null && $wrapper === null; if (!($wrapper instanceof ScalarWrapper)) $wrapper = $this->newWrapper(); if ($params !== null) $wrapper->resetParams($params); - return $wrapper->reset($value, $valueKey, $dontNormalize? ["normalize" => false]: null); + return $wrapper->reset($value, $valueKey, $dontAnalyze? ["analyze" => false]: null); } } diff --git a/tests/wip/schema/_assoc/AssocSchemaTest.php b/tests/wip/schema/_assoc/AssocSchemaTest.php index a082855..38586bd 100644 --- a/tests/wip/schema/_assoc/AssocSchemaTest.php +++ b/tests/wip/schema/_assoc/AssocSchemaTest.php @@ -98,8 +98,35 @@ class AssocSchemaTest extends TestCase { ], ]), $schema->getDefinition()); //yaml::dump($schema->getDefinition()); + } - $wrapper = $schema->getWrapper(); - $wrapper->getKeys(); + function testWrapper() { + $schema = new AssocSchema([ + "a" => "string", + "b" => "int", + "c" => "bool", + ]); + + $array = ["c" => false, "a" => " string "]; + $schema->getWrapper($array); + self::assertSame([ + "a" => "string", + "b" => null, + "c" => false, + ], $array); + + $array = ["c" => false, "a" => " string "]; + $schema->getWrapper($array, null, ["ensure_order" => false]); + self::assertSame([ + "c" => false, + "a" => "string", + "b" => null, + ], $array); + + $array = ["a" => " string "]; + $schema->getWrapper($array, null, ["ensure_keys" => false]); + self::assertSame([ + "a" => "string", + ], $array); } } From 9328aac9e9cb75717f726eae81cca1f619e18064 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 10:06:53 +0400 Subject: [PATCH 10/27] modifs.mineures sans commentaires --- src/schema/Wrapper.php | 11 ++-- src/schema/WrapperContext.php | 19 +++--- src/schema/_assoc/AssocSchema.php | 6 -- src/schema/_assoc/AssocWrapper.php | 72 ++++++++--------------- src/schema/_assoc/AssocWrapperContext.php | 18 +----- src/schema/_scalar/ScalarResult.php | 11 ++-- src/schema/_scalar/ScalarSchema.php | 6 -- src/schema/_scalar/ScalarWrapper.php | 41 +++++++------ 8 files changed, 67 insertions(+), 117 deletions(-) diff --git a/src/schema/Wrapper.php b/src/schema/Wrapper.php index d8e1e4d..43cc54b 100644 --- a/src/schema/Wrapper.php +++ b/src/schema/Wrapper.php @@ -65,31 +65,31 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } /** analyser la valeur */ - abstract protected function _analyze(?array $params): int; + abstract static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int; function analyze(?array $params=null): bool { $context = $this->context; $reanalyze = $params["reanalyze"] ?? false; if ($context->analyzed && !$reanalyze) return false; - $this->_analyze($params); + static::_analyze($params, $context, $this); $context->analyzed = true; return true; } /** normaliser la valeur */ - abstract protected function _normalize(?array $params): bool; + abstract static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool; function normalize(?array $params=null): bool { $context = $this->context; // il faut que la valeur soit analysée avant de la normaliser - $this->analyze($params); + static::analyze($params); if (!$context->analyzed) return false; $renormalize = $params["renormalize"] ?? false; if ($renormalize || !$context->normalized) { - $modified = $this->_normalize($params); + $modified = static::_normalize($params, $context, $this); $context->normalized = true; } else { $modified = false; @@ -159,7 +159,6 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { return $this->getResult($key)->normalized; } - function get($default=null, $key=false) { $context = $this->context; if (!$context->result->available) return $default; diff --git a/src/schema/WrapperContext.php b/src/schema/WrapperContext.php index d144939..58a7fe8 100644 --- a/src/schema/WrapperContext.php +++ b/src/schema/WrapperContext.php @@ -10,16 +10,11 @@ class WrapperContext { $this->schema = $schema; if ($input !== null) $this->input = $input; $this->valueKey = $valueKey; - $this->origValue = null; - $this->value = null; - $this->selectedKey = null; - $this->type = null; - $this->result = null; } public ?array $params; - public bool $analyze, $analyzed; - public bool $normalize, $normalized; + public bool $analyze, $analyzed = false; + public bool $normalize, $normalized = false; public ?bool $throw; function resetParams(?array $params): void { @@ -36,14 +31,14 @@ class WrapperContext { /** @var string|int|null clé de la valeur dans le tableau destination */ public $valueKey; /** @var mixed */ - public $origValue; + public $origValue = null; /** @var mixed */ - public $value; + public $value = null; /** @var string|int|null clé sélectionnée */ - public $selectedKey; + public $selectedKey = null; /** type de la valeur de la clé sélectionnée après analyse */ - public ?IType $type; + public ?IType $type = null; /** résultat de l'analyse de la valeur de la clé sélectionnée */ - public ?Result $result; + public ?Result $result = null; } diff --git a/src/schema/_assoc/AssocSchema.php b/src/schema/_assoc/AssocSchema.php index 6d3ba16..b9fac49 100644 --- a/src/schema/_assoc/AssocSchema.php +++ b/src/schema/_assoc/AssocSchema.php @@ -11,12 +11,6 @@ use nur\sery\wip\schema\Wrapper; * Class AssocSchema */ class AssocSchema extends Schema { - //const METASCHEMA = ref_schema::VALUE_METASCHEMA; - //const NATURE_METASCHEMA = [ - // ...ref_schema::NATURE_METASCHEMA, - // ...ref_schema::ASSOC_NATURE_METASCHEMA, - //]; - /** * indiquer si $definition est une définition de schéma de nature tableau * associatif que {@link normalize_definition()} pourrait normaliser diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index 0ee3800..a071c62 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -2,8 +2,7 @@ namespace nur\sery\wip\schema\_assoc; use nulib\ValueException; -use nur\sery\wip\schema\_scalar\ScalarResult; -use nur\sery\wip\schema\input\Input; +use nur\sery\wip\schema\_scalar\ScalarWrapper; use nur\sery\wip\schema\Result; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; @@ -12,16 +11,13 @@ use nur\sery\wip\schema\WrapperContext; class AssocWrapper extends Wrapper { function __construct(AssocSchema $schema, &$value=null, $valueKey=null, ?array $params=null) { $keys = $schema->getKeys(); - $keyTypes = []; $keyWrappers = []; foreach ($keys as $key) { - $keyTypes[$key] = null; $keyWrappers[$key] = $schema->getSchema($key)->getWrapper(); } $this->context = $context = new AssocWrapperContext($schema, null, null, $params); - $context->arrayResult = new ScalarResult(); + $context->arrayWrapper = new ScalarWrapper($schema, $dummy, null, null, $context); $context->keys = $keys; - $context->keyTypes = $keyTypes; $context->keyWrappers = $keyWrappers; # calculer manuellemet throw ici parce que WrapperContext le met à true par @@ -43,17 +39,13 @@ class AssocWrapper extends Wrapper { protected function resetContext($resetSelectedKey): void { $context = $this->context; - $context->arrayResult->reset(); + $context->arrayWrapper->getResult()->reset(); foreach ($context->keyWrappers as $wrapper) { $wrapper->getResult()->reset(); } $context->analyzed = false; $context->normalized = false; - if ($resetSelectedKey) { - $context->selectedKey = null; - $context->type = $context->arrayType; - $context->result = $context->arrayResult; - } + if ($resetSelectedKey) $context->selectedKey = null; } function getKeys(): array { @@ -61,6 +53,7 @@ class AssocWrapper extends Wrapper { } protected function _getWrapper($key): Wrapper { + if ($key === null) return $this->context->arrayWrapper; $wrapper = $context->keyWrappers[$key] ?? null; if ($wrapper === null) throw ValueException::invalid_key($key); return $wrapper; @@ -68,76 +61,57 @@ class AssocWrapper extends Wrapper { /** @param string|int|null $key */ function select($key=null): Wrapper { - $context = $this->context; - if ($key === null) { - $context->selectedKey = null; - $context->type = $context->arrayType; - $context->result = $context->arrayResult; - return $this; - } $wrapper = $this->_getWrapper($key); - $context->selectedKey = $key; - $context->type = $wrapper->getType(); - $context->result = $wrapper->getResult(); + $this->context->selectedKey = $key; return $wrapper; } - protected function _analyze(?array $params): int { - return -1; + /** + * @param AssocWrapperContext $context + * @param AssocWrapper $wrapper + */ + static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int { + return ScalarWrapper::_analyze($params, $context, $wrapper); } - protected function _normalize(?array $params): bool { - return false; + static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool { + return ScalarWrapper::_normalize($params, $context, $wrapper); } function getResult($key=false): Result { - if ($key === false) return $this->context->result; - elseif ($key === null) return $this->context->arrayResult; - else return $this->_getWrapper($key)->getResult(); + if ($key === false) $key = $this->context->selectedKey; + return $this->_getWrapper($key)->getResult(); } function getType($key=false): IType { - if ($key === false) return $this->context->type; - elseif ($key === null) return $this->context->arrayType; - else return $this->_getWrapper($key)->getType(); + if ($key === false) $key = $this->context->selectedKey; + return $this->_getWrapper($key)->getType(); } function get($default=null, $key=false) { $context = $this->context; - if (!$context->arrayResult->available) return $default; + if (!$context->arrayWrapper->isAvailable()) return $default; if ($key === false) $key = $context->selectedKey; - if ($key === null) return $context->input->get($context->valueKey); - else return $this->_getWrapper($key)->get($default); + return $this->_getWrapper($key)->get($default); } function set($value, ?array $params=null, $key=false): Wrapper { $context = $this->context; if ($key === false) $key = $context->selectedKey; - if ($key === null) { - $context->input->set($value, $context->valueKey); - $this->afterModify($params); - } else { - $this->_getWrapper($key)->set($value); - } + $this->_getWrapper($key)->set($value); return $this; } function unset(?array $params=null, $key=false): Wrapper { $context = $this->context; if ($key === false) $key = $context->selectedKey; - if ($key === null) { - $context->input->unset($context->valueKey); - $this->afterModify($params); - } else { - $this->_getWrapper($key)->unset(); - } + $this->_getWrapper($key)->unset(); return $this; } function format($format=null, $key=false): string { $context = $this->context; if ($key === false) $key = $context->selectedKey; - if ($key === null) return $this->_format($context, $format); - else return $this->_getWrapper($key)->format($format); + return $this->_getWrapper($key)->format($format); } } diff --git a/src/schema/_assoc/AssocWrapperContext.php b/src/schema/_assoc/AssocWrapperContext.php index 44fee29..a1a4693 100644 --- a/src/schema/_assoc/AssocWrapperContext.php +++ b/src/schema/_assoc/AssocWrapperContext.php @@ -1,30 +1,16 @@ arrayType = null; - $this->arrayResult = null; - } - - public ?IType $arrayType; - /** résultat de l'analyse du tableau */ - public ?ScalarResult $arrayResult; + public ?ScalarWrapper $arrayWrapper = null; /** liste des clés valides */ public array $keys; - /** @var ?IType[] */ - public array $keyTypes; - /** @var Wrapper[] */ public array $keyWrappers; } diff --git a/src/schema/_scalar/ScalarResult.php b/src/schema/_scalar/ScalarResult.php index cc28149..caf4c31 100644 --- a/src/schema/_scalar/ScalarResult.php +++ b/src/schema/_scalar/ScalarResult.php @@ -6,6 +6,7 @@ use nulib\ref\schema\ref_analyze; use nulib\ref\schema\ref_schema; use nulib\ValueException; use nur\sery\wip\schema\Result; +use nur\sery\wip\schema\Schema; use Throwable; /** @@ -45,13 +46,13 @@ class ScalarResult extends Result { $this->result[$name] = $value; } - protected function getMessage(string $key, ScalarSchema $schema): string { + protected function getMessage(string $key, Schema $schema): string { $message = cl::get($schema->messages, $key); if ($message !== null) return $message; return cl::get(ref_schema::MESSAGES, $key); } - function setMissing(ScalarSchema $schema): int { + function setMissing( Schema $schema): int { $this->resultAvailable = true; $this->present = false; $this->available = false; @@ -67,7 +68,7 @@ class ScalarResult extends Result { } } - function setUnavailable(ScalarSchema $schema): int { + function setUnavailable( Schema $schema): int { $this->resultAvailable = true; $this->present = true; $this->available = false; @@ -83,7 +84,7 @@ class ScalarResult extends Result { } } - function setNull(ScalarSchema $schema): int { + function setNull( Schema $schema): int { $this->resultAvailable = true; $this->present = true; $this->available = true; @@ -99,7 +100,7 @@ class ScalarResult extends Result { } } - function setInvalid($value, ScalarSchema $schema, ?Throwable $exception=null): int { + function setInvalid($value, Schema $schema, ?Throwable $exception=null): int { $this->resultAvailable = true; $this->present = true; $this->available = true; diff --git a/src/schema/_scalar/ScalarSchema.php b/src/schema/_scalar/ScalarSchema.php index 5c14a5c..597a34b 100644 --- a/src/schema/_scalar/ScalarSchema.php +++ b/src/schema/_scalar/ScalarSchema.php @@ -11,12 +11,6 @@ use nur\sery\wip\schema\Wrapper; * Class ScalarSchema */ class ScalarSchema extends Schema { - //const METASCHEMA = ref_schema::VALUE_METASCHEMA; - //const NATURE_METASCHEMA = [ - // ...ref_schema::NATURE_METASCHEMA, - // ...ref_schema::SCALAR_NATURE_METASCHEMA, - //]; - /** * indiquer si $definition est une définition de schéma scalaire que * {@link normalize_definition()} pourrait normaliser diff --git a/src/schema/_scalar/ScalarWrapper.php b/src/schema/_scalar/ScalarWrapper.php index 6f48a41..31f9ba9 100644 --- a/src/schema/_scalar/ScalarWrapper.php +++ b/src/schema/_scalar/ScalarWrapper.php @@ -4,6 +4,9 @@ namespace nur\sery\wip\schema\_scalar; use nulib\php\func; use nulib\ref\schema\ref_analyze; use nulib\ValueException; +use nur\sery\wip\schema\_assoc\AssocWrapper; +use nur\sery\wip\schema\_assoc\AssocWrapperContext; +use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\types; use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\Wrapper; @@ -12,15 +15,16 @@ use nur\sery\wip\schema\WrapperContext; /** * Class ScalarWrapper * - * @method ScalarWrapper reset() - * @method ScalarResult getResult() - * @method self set() - * @method self unset() + * @method ScalarWrapper reset(&$value, $valueKey=null, ?array $params=null) + * @method ScalarResult getResult($key=false) + * @method self set($value, ?array $params=null, $key=false) + * @method self unset(?array $params=null, $key=false) */ class ScalarWrapper extends Wrapper { - function __construct(ScalarSchema $schema, &$value=null, $valueKey=null, ?array $params=null) { - $this->context = $context = new WrapperContext($schema, null, null, $params); + function __construct(Schema $schema, &$value=null, $valueKey=null, ?array $params=null, ?WrapperContext $context=null) { + if ($context === null) $context = new WrapperContext($schema, null, null, $params); $context->result = new ScalarResult(); + $this->context = $context; # calculer manuellemet throw ici parce que WrapperContext le met à true par # défaut. on veut pouvoir mettre temporairement throw à false si jamais il @@ -49,8 +53,7 @@ class ScalarWrapper extends Wrapper { } /** analyser la valeur et résoudre son type */ - protected function _analyze0(): int { - $context = $this->context; + protected static function _analyze0(WrapperContext $context): int { /** @var ScalarSchema $schema */ $schema = $context->schema; $input = $context->input; @@ -141,8 +144,10 @@ class ScalarWrapper extends Wrapper { } } - protected function _analyze(?array $params): int { - $context = $this->context; + /** + * @param ScalarWrapper $wrapper + */ + static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int { /** @var ScalarSchema $schema */ $schema = $context->schema; $input = $context->input; @@ -152,15 +157,15 @@ class ScalarWrapper extends Wrapper { /** @var func $analyzerFunc */ $analyzerFunc = $schema->analyzerFunc; - if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context, $this]); - else $what = $this->_analyze0(); + if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context, $wrapper]); + else $what = self::_analyze0($context); if ($what !== ref_analyze::STRING) return $what; $value = $context->value; try { /** @var func $extractorFunc */ $extractorFunc = $schema->extractorFunc; - if ($extractorFunc !== null) $extracted = $extractorFunc->invoke([$value, $context, $this]); + if ($extractorFunc !== null) $extracted = $extractorFunc->invoke([$value, $context, $wrapper]); else $extracted = $context->type->extract($value); $context->value = $extracted; } catch (ValueException $e) { @@ -171,7 +176,7 @@ class ScalarWrapper extends Wrapper { try { /** @var func $parserFunc */ $parserFunc = $schema->parserFunc; - if ($parserFunc !== null) $parsed = $parserFunc->invoke([$extracted, $context, $this]); + if ($parserFunc !== null) $parsed = $parserFunc->invoke([$extracted, $context, $wrapper]); else $parsed = $context->type->parse($extracted); $context->value = $parsed; } catch (ValueException $e) { @@ -188,8 +193,10 @@ class ScalarWrapper extends Wrapper { } } - protected function _normalize(?array $params): bool { - $context = $this->context; + /** + * @param ScalarWrapper $wrapper + */ + static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool { /** @var ScalarSchema $schema */ $schema = $context->schema; $input = $context->input; @@ -226,7 +233,7 @@ class ScalarWrapper extends Wrapper { $normalizerFunc = $schema->normalizerFunc; if ($normalizerFunc !== null) { $orig = $value; - $value = $normalizerFunc->invoke([$orig, $context, $this]); + $value = $normalizerFunc->invoke([$orig, $context, $wrapper]); $modified = $value !== $orig; } else { $modified = $context->type->verifix($value, $result, $schema); From ef7e8551aa4da50e25dc6d6c912632f2fde07097 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 13:49:36 +0400 Subject: [PATCH 11/27] modifs.mineures sans commentaires --- src/schema/_assoc/AssocWrapper.php | 19 ++++++++++++++++++- src/schema/_assoc/AssocWrapperContext.php | 13 +++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index a071c62..05fad7d 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -2,6 +2,7 @@ namespace nur\sery\wip\schema\_assoc; use nulib\ValueException; +use nur\sery\wip\schema\_scalar\ScalarResult; use nur\sery\wip\schema\_scalar\ScalarWrapper; use nur\sery\wip\schema\Result; use nur\sery\wip\schema\types\IType; @@ -71,7 +72,23 @@ class AssocWrapper extends Wrapper { * @param AssocWrapper $wrapper */ static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int { - return ScalarWrapper::_analyze($params, $context, $wrapper); + if ($context->ensureArray) { + $array = $context->input->get(); + if ($array === null) $context->input->set([]); + } + $what = ScalarWrapper::_analyze($params, $context, $wrapper); + /** @var ScalarResult $result */ + $result = $context->result; + if (!$result->valid) return $what; + foreach ($context->keyWrappers as $wrapper) { + $wrapper->analyze($params); + if (!$wrapper->isValid()) { + $result->setInvalid(null, $context->schema, $wrapper->getResult()->exception); + break; + #XXX + } + } + return $what; } static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool { diff --git a/src/schema/_assoc/AssocWrapperContext.php b/src/schema/_assoc/AssocWrapperContext.php index a1a4693..07b9f79 100644 --- a/src/schema/_assoc/AssocWrapperContext.php +++ b/src/schema/_assoc/AssocWrapperContext.php @@ -2,10 +2,23 @@ namespace nur\sery\wip\schema\_assoc; use nur\sery\wip\schema\_scalar\ScalarWrapper; +use nur\sery\wip\schema\input\Input; +use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\Wrapper; use nur\sery\wip\schema\WrapperContext; class AssocWrapperContext extends WrapperContext { + function __construct(Schema $schema, ?Input $input, $valueKey, ?array $params) { + parent::__construct($schema, $input, $valueKey, $params); + $this->ensureArray = $params["ensure_array"] ?? false; + $this->ensureKeys = $params["ensure_keys"] ?? true; + $this->ensureOrder = $params["ensure_order"] ?? true; + } + + public bool $ensureArray; + public bool $ensureKeys; + public bool $ensureOrder; + public ?ScalarWrapper $arrayWrapper = null; /** liste des clés valides */ From 1fc4e7637b9686e8f821bd7e58c2db93eb70ae87 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 16:10:26 +0400 Subject: [PATCH 12/27] modifs.mineures sans commentaires --- src/php/access/AbstractAccess.php | 10 +++ src/php/access/ChainAccess.php | 57 ++++++++++++++ src/php/access/FormAccess.php | 84 +++++++++++++-------- src/php/access/GetAccess.php | 30 ++------ src/php/access/IAccess.php | 3 + src/php/access/IGetter.php | 6 ++ src/php/access/KeyAccess.php | 36 +++++---- src/php/access/PostAccess.php | 30 ++------ src/php/access/ShadowAccess.php | 9 +++ src/php/access/ValueAccess.php | 20 +++-- src/schema/Wrapper.php | 8 +- src/schema/WrapperContext.php | 10 ++- src/schema/_assoc/AssocWrapper.php | 28 +++++-- src/schema/_assoc/AssocWrapperContext.php | 10 ++- src/schema/_scalar/ScalarResult.php | 24 ++++++ src/schema/_scalar/ScalarWrapper.php | 4 +- src/schema/input/ChainInput.php | 5 ++ src/schema/input/IInput.php | 18 +++++ src/schema/input/Input.php | 6 +- tests/wip/schema/_assoc/AssocSchemaTest.php | 13 ++++ 20 files changed, 288 insertions(+), 123 deletions(-) create mode 100644 src/php/access/ChainAccess.php create mode 100644 src/schema/input/ChainInput.php create mode 100644 src/schema/input/IInput.php diff --git a/src/php/access/AbstractAccess.php b/src/php/access/AbstractAccess.php index 21dda22..f162ca5 100644 --- a/src/php/access/AbstractAccess.php +++ b/src/php/access/AbstractAccess.php @@ -8,6 +8,16 @@ use nulib\cl; * de {@link IAccess} */ abstract class AbstractAccess implements IAccess { + function __construct(?array $params=null) { + $this->allowEmpty = $params["allow_empty"] ?? true; + } + + protected bool $allowEmpty; + + function isAllowEmpty(): bool { + return $this->allowEmpty; + } + function inc(): int { $value = (int)$this->get(); $this->set(++$value); diff --git a/src/php/access/ChainAccess.php b/src/php/access/ChainAccess.php new file mode 100644 index 0000000..d08be7f --- /dev/null +++ b/src/php/access/ChainAccess.php @@ -0,0 +1,57 @@ +access = $access; + $this->key = $key; + } + + protected IAccess $access; + + /** @var int|string|array */ + protected $key; + + function isAllowEmpty(): bool { + return $this->access->isAllowEmpty(); + } + + function exists(): bool { + $key = $this->key; + if ($key === null) return false; + if (!$this->access->exists()) return false; + return cl::phas($this->access->get(), $key); + } + + function available(): bool { + $key = $this->key; + if ($key === null) return false; + if (!$this->access->available()) return false; + $array = $this->access->get(); + if (!cl::phas($array, $key)) return false; + return $this->isAllowEmpty() || cl::pget($array, $key) !== ""; + } + + function get($default=null) { + return cl::pget($this->access->get($default), $this->key); + } + + function set($value): void { + $array = $this->access->get(); + cl::pset($array, $this->key, $value); + $this->access->set($array); + } + + function del(): void { + $array = $this->access->get(); + cl::pdel($array, $this->key); + $this->access->set($array); + } + + function addKey($key): IAccess { + return new ChainAccess($this->access, cl::merge($this->key, $key)); + } +} diff --git a/src/php/access/FormAccess.php b/src/php/access/FormAccess.php index 7b3840d..db8d09a 100644 --- a/src/php/access/FormAccess.php +++ b/src/php/access/FormAccess.php @@ -8,66 +8,88 @@ use nulib\cl; */ class FormAccess extends AbstractAccess { function __construct($key, ?array $params=null) { + parent::__construct($params); $this->key = $key; - $this->allowEmpty = $params["allow_empty"] ?? false; } - /** @var int|string */ + /** @var int|string|array */ protected $key; - protected bool $allowEmpty; - - function exists(): bool { + protected function _exists(array $first, ?array $second=null): bool { $key = $this->key; if ($key === null) return false; - return array_key_exists($key, $_POST) || array_key_exists($key, $_GET); + if (cl::phas($first, $key)) return true; + return $second !== null && cl::phas($second, $key); } - public function available(): bool { + function exists(): bool { + return $this->_exists($_POST, $_GET); + } + + protected function _available(array $first, ?array $second=null): bool { $key = $this->key; if ($key === null) return false; - if (array_key_exists($key, $_POST)) { - return $this->allowEmpty || $_POST[$key] !== ""; - } elseif (array_key_exists($key, $_GET)) { - return $this->allowEmpty || $_GET[$key] !== ""; + if (cl::phas($first, $key)) { + return $this->allowEmpty || cl::pget($first, $key) !== ""; + } elseif ($second !== null && cl::phas($second, $key)) { + return $this->allowEmpty || cl::pget($second, $key) !== ""; } else { return false; } } - function get($default=null) { + public function available(): bool { + return $this->_available($_POST, $_GET); + } + + protected function _get($default, array $first, ?array $second=null) { $key = $this->key; if ($key === null) return $default; - if (array_key_exists($key, $_POST)) { - $value = $_POST[$key]; - if ($value === "" && !$this->allowEmpty) return $default; - return $value; - } elseif (array_key_exists($key, $_GET)) { - $value = $_GET[$key]; - if ($value === "" && !$this->allowEmpty) return $default; - return $value; + if (cl::phas($first, $key)) { + $value = cl::pget($first, $key); + if ($value !== "" || $this->allowEmpty) return $value; + } elseif ($second !== null && cl::phas($second, $key)) { + $value = cl::pget($second, $key); + if ($value !== "" || $this->allowEmpty) return $value; + } + return $default; + } + + function get($default=null) { + return $this->_get($default, $_POST, $_GET); + } + + function _set($value, array &$first, ?array &$second=null): void { + $key = $this->key; + if ($key === null) return; + if ($second !== null && !cl::phas($first, $key) && cl::phas($second, $key)) { + cl::pset($second, $key, $value); } else { - return $default; + cl::pset($first, $key, $value); } } function set($value): void { + $this->_set($value, $_POST, $_GET); + } + + function _del(array &$first, ?array &$second=null): void { $key = $this->key; if ($key === null) return; - if (!array_key_exists($key, $_POST) && array_key_exists($key, $_GET)) { - cl::set($_GET, $key, $value); + if ($second !== null && !cl::phas($first, $key) && cl::phas($second, $key)) { + cl::pdel($second, $key); } else { - cl::set($_POST, $key, $value); + cl::pdel($first, $key); } } function del(): void { - $key = $this->key; - if ($key === null) return; - if (!array_key_exists($key, $_POST) && array_key_exists($key, $_GET)) { - cl::del($_GET, $key); - } else { - cl::del($_POST, $key); - } + $this->_del($_POST, $_GET); + } + + function addKey($key): self { + return new static(cl::merge($this->key, $key), [ + "allow_empty" => $this->allowEmpty + ]); } } diff --git a/src/php/access/GetAccess.php b/src/php/access/GetAccess.php index 4b67367..ed42023 100644 --- a/src/php/access/GetAccess.php +++ b/src/php/access/GetAccess.php @@ -8,42 +8,22 @@ use nulib\cl; */ class GetAccess extends FormAccess { function exists(): bool { - $key = $this->key; - if ($key === null) return false; - return array_key_exists($key, $_GET); + return $this->_exists($_GET); } public function available(): bool { - $key = $this->key; - if ($key === null) return false; - if (array_key_exists($key, $_GET)) { - return $this->allowEmpty || $_GET[$key] !== ""; - } else { - return false; - } + return $this->_available($_GET); } function get($default=null) { - $key = $this->key; - if ($key === null) return $default; - if (array_key_exists($key, $_GET)) { - $value = $_GET[$key]; - if ($value === "" && !$this->allowEmpty) return $default; - return $value; - } else { - return $default; - } + return $this->_get($default, $_GET); } function set($value): void { - $key = $this->key; - if ($key === null) return; - cl::set($_GET, $key, $value); + $this->_set($value, $_GET); } function del(): void { - $key = $this->key; - if ($key === null) return; - cl::del($_GET, $key); + $this->_del($_GET); } } diff --git a/src/php/access/IAccess.php b/src/php/access/IAccess.php index 2581c8b..7987c4c 100644 --- a/src/php/access/IAccess.php +++ b/src/php/access/IAccess.php @@ -25,4 +25,7 @@ interface IAccess extends IGetter, ISetter, IDeleter { * tableau si $key===null */ function append($value, $key=null): void; + + /** retourner une instance permettant d'accéder à $value[$key] */ + function addKey($key): IAccess; } diff --git a/src/php/access/IGetter.php b/src/php/access/IGetter.php index d4b1b9c..430d908 100644 --- a/src/php/access/IGetter.php +++ b/src/php/access/IGetter.php @@ -11,6 +11,12 @@ interface IGetter { */ function exists(): bool; + /** + * @return bool true si cet objet autorise les chaines vides. si c'est le cas, + * {@link exists()} et {@link available()} sont fonctionnellement identiques + */ + function isAllowEmpty(): bool; + /** @return bool true si la valeur existe et est utilisable, false sinon */ function available(): bool; diff --git a/src/php/access/KeyAccess.php b/src/php/access/KeyAccess.php index 2421c5a..2f7b4c4 100644 --- a/src/php/access/KeyAccess.php +++ b/src/php/access/KeyAccess.php @@ -9,61 +9,67 @@ use nulib\cl; */ class KeyAccess extends AbstractAccess { function __construct(&$array, $key, ?array $params=null) { + parent::__construct($params); $this->array =& $array; $this->key = $key; $this->allowNull = $params["allow_null"] ?? true; $this->allowFalse = $params["allow_false"] ?? false; - $this->allowEmpty = $params["allow_empty"] ?? true; } /** @var array|ArrayAccess */ protected $array; - function reset(&$array): self { - $this->array =& $array; - return $this; - } - - /** @var int|string */ + /** @var int|string|array */ protected $key; protected bool $allowNull; protected bool $allowFalse; - protected bool $allowEmpty; + function reset(&$array): self { + $this->array =& $array; + return $this; + } function exists(): bool { $key = $this->key; if ($key === null) return false; - return cl::has($this->array, $key); + return cl::phas($this->array, $key); } function available(): bool { if (!$this->exists()) return false; - $value = cl::get($this->array, $this->key); + $value = cl::pget($this->array, $this->key); + if ($value === "") return $this->allowEmpty; if ($value === null) return $this->allowNull; if ($value === false) return $this->allowFalse; - if ($value === "") return $this->allowEmpty; return true; } function get($default=null) { if ($this->key === null) return $default; - $value = cl::get($this->array, $this->key, $default); + $value = cl::pget($this->array, $this->key, $default); + if ($value === "" && !$this->allowEmpty) return $default; if ($value === null && !$this->allowNull) return $default; if ($value === false && !$this->allowFalse) return $default; - if ($value === "" && !$this->allowEmpty) return $default; return $value; } function set($value): void { if ($this->key === null) return; - cl::set($this->array, $this->key, $value); + cl::pset($this->array, $this->key, $value); } function del(): void { if ($this->key === null) return; - cl::del($this->array, $this->key); + cl::pdel($this->array, $this->key); + } + + function addKey($key): self { + return new KeyAccess($this->array, cl::merge($this->key, $key), [ + "allow_empty" => $this->allowEmpty, + "allow_null" => $this->allowNull, + "allow_false" => $this->allowFalse, + ]); } } diff --git a/src/php/access/PostAccess.php b/src/php/access/PostAccess.php index 1756964..e9c7f13 100644 --- a/src/php/access/PostAccess.php +++ b/src/php/access/PostAccess.php @@ -8,42 +8,22 @@ use nulib\cl; */ class PostAccess extends FormAccess { function exists(): bool { - $key = $this->key; - if ($key === null) return false; - return array_key_exists($key, $_POST); + return $this->_exists($_POST); } public function available(): bool { - $key = $this->key; - if ($key === null) return false; - if (array_key_exists($key, $_POST)) { - return $this->allowEmpty || $_POST[$key] !== ""; - } else { - return false; - } + return $this->_available($_POST); } function get($default=null) { - $key = $this->key; - if ($key === null) return $default; - if (array_key_exists($key, $_POST)) { - $value = $_POST[$key]; - if ($value === "" && !$this->allowEmpty) return $default; - return $value; - } else { - return $default; - } + return $this->_get($default, $_POST); } function set($value): void { - $key = $this->key; - if ($key === null) return; - cl::set($_POST, $key, $value); + $this->_set($value, $_POST); } function del(): void { - $key = $this->key; - if ($key === null) return; - cl::del($_POST, $key); + $this->_del($_POST); } } diff --git a/src/php/access/ShadowAccess.php b/src/php/access/ShadowAccess.php index 229bad1..e4f1211 100644 --- a/src/php/access/ShadowAccess.php +++ b/src/php/access/ShadowAccess.php @@ -16,6 +16,7 @@ namespace nur\sery\wip\php\access; */ class ShadowAccess extends AbstractAccess { function __construct(IAccess $reader, IAccess $writer) { + parent::__construct(); $this->reader = $reader; $this->writer = $writer; $this->getter = $reader; @@ -27,6 +28,10 @@ class ShadowAccess extends AbstractAccess { protected IGetter $getter; + public function isAllowEmpty(): bool { + return $this->getter->isAllowEmpty(); + } + function exists(): bool { return $this->getter->exists(); } @@ -48,4 +53,8 @@ class ShadowAccess extends AbstractAccess { $this->writer->del(); $this->getter = $this->reader; } + + function addKey($key): IAccess { + return new ChainAccess($this, $key); + } } diff --git a/src/php/access/ValueAccess.php b/src/php/access/ValueAccess.php index 624092f..3b95431 100644 --- a/src/php/access/ValueAccess.php +++ b/src/php/access/ValueAccess.php @@ -6,25 +6,23 @@ namespace nur\sery\wip\php\access; */ class ValueAccess extends AbstractAccess { function __construct(&$value, ?array $params=null) { + parent::__construct($params); $this->value =& $value; $this->allowNull = $params["allow_null"] ?? false; $this->allowFalse = $params["allow_false"] ?? true; - $this->allowEmpty = $params["allow_empty"] ?? true; } /** @var mixed */ protected $value; - function reset(&$value): self { - $this->value =& $value; - return $this; - } - protected bool $allowNull; protected bool $allowFalse; - protected bool $allowEmpty; + function reset(&$value): self { + $this->value =& $value; + return $this; + } function exists(): bool { return $this->allowNull || $this->value !== null; @@ -53,4 +51,12 @@ class ValueAccess extends AbstractAccess { function del(): void { $this->value = null; } + + function addKey($key): KeyAccess { + return new KeyAccess($this->value, $key, [ + "allow_empty" => $this->allowEmpty, + "allow_null" => $this->allowNull, + "allow_false" => $this->allowFalse, + ]); + } } diff --git a/src/schema/Wrapper.php b/src/schema/Wrapper.php index 43cc54b..7c558e8 100644 --- a/src/schema/Wrapper.php +++ b/src/schema/Wrapper.php @@ -65,20 +65,20 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { } /** analyser la valeur */ - abstract static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int; + abstract static function _analyze(WrapperContext $context, Wrapper $wrapper, ?array $params): int; function analyze(?array $params=null): bool { $context = $this->context; $reanalyze = $params["reanalyze"] ?? false; if ($context->analyzed && !$reanalyze) return false; - static::_analyze($params, $context, $this); + static::_analyze($context, $this, $params); $context->analyzed = true; return true; } /** normaliser la valeur */ - abstract static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool; + abstract static function _normalize(WrapperContext $context, Wrapper $wrapper, ?array $params): bool; function normalize(?array $params=null): bool { $context = $this->context; @@ -89,7 +89,7 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate { $renormalize = $params["renormalize"] ?? false; if ($renormalize || !$context->normalized) { - $modified = static::_normalize($params, $context, $this); + $modified = static::_normalize($context, $this, $params); $context->normalized = true; } else { $modified = false; diff --git a/src/schema/WrapperContext.php b/src/schema/WrapperContext.php index 58a7fe8..d22a81f 100644 --- a/src/schema/WrapperContext.php +++ b/src/schema/WrapperContext.php @@ -5,6 +5,10 @@ use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\types\IType; class WrapperContext { + const DEFAULT_ANALYZE = true; + const DEFAULT_NORMALIZE = true; + const DEFAULT_THROW = true; + function __construct(Schema $schema, ?Input $input, $valueKey, ?array $params) { $this->resetParams($params); $this->schema = $schema; @@ -19,9 +23,9 @@ class WrapperContext { function resetParams(?array $params): void { $this->params = $params; - $this->analyze = $params["analyze"] ?? true; - $this->normalize = $params["normalize"] ?? true; - $this->throw = $params["throw"] ?? true; + $this->analyze = $params["analyze"] ?? self::DEFAULT_ANALYZE; + $this->normalize = $params["normalize"] ?? self::DEFAULT_NORMALIZE; + $this->throw = $params["throw"] ?? self::DEFAULT_THROW; } /** schéma de la valeur */ diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index 05fad7d..5b71446 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -1,9 +1,11 @@ selectedKey = null; } + function reset(&$value, $valueKey=null, ?array $params=null): Wrapper { + $context = $this->context; + if ($value instanceof Input) $input = $value; + else $input = $this->newInput($value); + $context->input = $input; + $context->valueKey = $valueKey; + foreach ($context->keyWrappers as $key => $wrapper) { + $wrapper->reset($input->subInput($valueKey), $key); + } + $this->afterModify($params, true); + return $this; + } + function getKeys(): array { return $this->context->keys; } @@ -71,28 +86,27 @@ class AssocWrapper extends Wrapper { * @param AssocWrapperContext $context * @param AssocWrapper $wrapper */ - static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int { + static function _analyze(WrapperContext $context, Wrapper $wrapper, ?array $params): int { if ($context->ensureArray) { $array = $context->input->get(); if ($array === null) $context->input->set([]); } - $what = ScalarWrapper::_analyze($params, $context, $wrapper); + $what = ScalarWrapper::_analyze($context, $wrapper, $params); /** @var ScalarResult $result */ $result = $context->result; if (!$result->valid) return $what; foreach ($context->keyWrappers as $wrapper) { $wrapper->analyze($params); if (!$wrapper->isValid()) { - $result->setInvalid(null, $context->schema, $wrapper->getResult()->exception); - break; - #XXX + $what = ref_analyze::INVALID; + $result->addInvalidMessage($wrapper); } } return $what; } - static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool { - return ScalarWrapper::_normalize($params, $context, $wrapper); + static function _normalize(WrapperContext $context, Wrapper $wrapper, ?array $params): bool { + return ScalarWrapper::_normalize($context, $wrapper, $params); } function getResult($key=false): Result { diff --git a/src/schema/_assoc/AssocWrapperContext.php b/src/schema/_assoc/AssocWrapperContext.php index 07b9f79..c504197 100644 --- a/src/schema/_assoc/AssocWrapperContext.php +++ b/src/schema/_assoc/AssocWrapperContext.php @@ -8,11 +8,15 @@ use nur\sery\wip\schema\Wrapper; use nur\sery\wip\schema\WrapperContext; class AssocWrapperContext extends WrapperContext { + const DEFAULT_ENSURE_ARRAY = false; + const DEFAULT_ENSURE_KEYS = true; + const DEFAULT_ENSURE_ORDER = true; + function __construct(Schema $schema, ?Input $input, $valueKey, ?array $params) { parent::__construct($schema, $input, $valueKey, $params); - $this->ensureArray = $params["ensure_array"] ?? false; - $this->ensureKeys = $params["ensure_keys"] ?? true; - $this->ensureOrder = $params["ensure_order"] ?? true; + $this->ensureArray = $params["ensure_array"] ?? self::DEFAULT_ENSURE_ARRAY; + $this->ensureKeys = $params["ensure_keys"] ?? self::DEFAULT_ENSURE_KEYS; + $this->ensureOrder = $params["ensure_order"] ?? self::DEFAULT_ENSURE_ORDER; } public bool $ensureArray; diff --git a/src/schema/_scalar/ScalarResult.php b/src/schema/_scalar/ScalarResult.php index caf4c31..59453eb 100644 --- a/src/schema/_scalar/ScalarResult.php +++ b/src/schema/_scalar/ScalarResult.php @@ -7,6 +7,7 @@ use nulib\ref\schema\ref_schema; use nulib\ValueException; use nur\sery\wip\schema\Result; use nur\sery\wip\schema\Schema; +use nur\sery\wip\schema\Wrapper; use Throwable; /** @@ -118,6 +119,29 @@ class ScalarResult extends Result { return ref_analyze::INVALID; } + function addInvalidMessage(Wrapper $wrapper): void { + $this->resultAvailable = true; + $this->present = true; + $this->available = true; + $this->null = false; + $this->valid = false; + $this->messageKey = "invalid"; + $result = $wrapper->getResult(); + $resultException = $result->exception; + $resultMessage = $result->message; + if ($resultException !== null) { + $tmessage = ValueException::get_message($resultException); + if ($tmessage) { + if ($resultMessage !== null) $resultMessage .= ": "; + $resultMessage .= $tmessage; + } + } + $message = $this->message; + if ($message) $message .= "\n"; + $message .= $resultMessage; + $this->message = $message; + } + function setValid($normalizedValue=null): int { $this->resultAvailable = true; $this->present = true; diff --git a/src/schema/_scalar/ScalarWrapper.php b/src/schema/_scalar/ScalarWrapper.php index 31f9ba9..f9ba7db 100644 --- a/src/schema/_scalar/ScalarWrapper.php +++ b/src/schema/_scalar/ScalarWrapper.php @@ -147,7 +147,7 @@ class ScalarWrapper extends Wrapper { /** * @param ScalarWrapper $wrapper */ - static function _analyze(?array $params, WrapperContext $context, Wrapper $wrapper): int { + static function _analyze(WrapperContext $context, Wrapper $wrapper, ?array $params): int { /** @var ScalarSchema $schema */ $schema = $context->schema; $input = $context->input; @@ -196,7 +196,7 @@ class ScalarWrapper extends Wrapper { /** * @param ScalarWrapper $wrapper */ - static function _normalize(?array $params, WrapperContext $context, Wrapper $wrapper): bool { + static function _normalize(WrapperContext $context, Wrapper $wrapper, ?array $params): bool { /** @var ScalarSchema $schema */ $schema = $context->schema; $input = $context->input; diff --git a/src/schema/input/ChainInput.php b/src/schema/input/ChainInput.php new file mode 100644 index 0000000..6e26061 --- /dev/null +++ b/src/schema/input/ChainInput.php @@ -0,0 +1,5 @@ +access($key)->del(); } + + function addKey($key): IInput { + return new ChainInput($this, $key); + } } diff --git a/tests/wip/schema/_assoc/AssocSchemaTest.php b/tests/wip/schema/_assoc/AssocSchemaTest.php index 38586bd..0ab3763 100644 --- a/tests/wip/schema/_assoc/AssocSchemaTest.php +++ b/tests/wip/schema/_assoc/AssocSchemaTest.php @@ -101,6 +101,19 @@ class AssocSchemaTest extends TestCase { } function testWrapper() { + $schema = new AssocSchema([ + "a" => "?string", + "b" => "?int", + "c" => "?bool", + ]); + $array = ["a" => " string ", "b" => " 42 ", "c" => false]; + $schema->getWrapper($array); + self::assertSame([ + "a" => "string", + "b" => 42, + "c" => false, + ], $array); + $schema = new AssocSchema([ "a" => "string", "b" => "int", From 39af99ffa4890cca1b5783d24ccd28e568f51222 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 16:56:36 +0400 Subject: [PATCH 13/27] modifs.mineures sans commentaires --- .../{ChainAccess.php => ChainKeyAccess.php} | 4 +- src/php/access/PropertyAccess.php | 95 +++++++++++++++++++ src/php/access/ShadowAccess.php | 2 +- 3 files changed, 98 insertions(+), 3 deletions(-) rename src/php/access/{ChainAccess.php => ChainKeyAccess.php} (91%) create mode 100644 src/php/access/PropertyAccess.php diff --git a/src/php/access/ChainAccess.php b/src/php/access/ChainKeyAccess.php similarity index 91% rename from src/php/access/ChainAccess.php rename to src/php/access/ChainKeyAccess.php index d08be7f..f2460f8 100644 --- a/src/php/access/ChainAccess.php +++ b/src/php/access/ChainKeyAccess.php @@ -3,7 +3,7 @@ namespace nur\sery\wip\php\access; use nulib\cl; -class ChainAccess extends AbstractAccess { +class ChainKeyAccess extends AbstractAccess { function __construct(IAccess $access, $key) { parent::__construct(); $this->access = $access; @@ -52,6 +52,6 @@ class ChainAccess extends AbstractAccess { } function addKey($key): IAccess { - return new ChainAccess($this->access, cl::merge($this->key, $key)); + return new ChainKeyAccess($this->access, cl::merge($this->key, $key)); } } diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php new file mode 100644 index 0000000..1550173 --- /dev/null +++ b/src/php/access/PropertyAccess.php @@ -0,0 +1,95 @@ +object =& $object; + $this->class = new ReflectionClass($object); + $this->name = $name; + $this->allowNull = $params["allow_null"] ?? true; + $this->allowFalse = $params["allow_false"] ?? false; + } + + protected object $object; + + protected ReflectionClass $class; + + protected string $name; + + protected bool $allowNull; + + protected bool $allowFalse; + + function reset(object &$object): self { + $this->object =& $object; + return $this; + } + + function exists(): bool { + return $this->class->hasProperty($this->name) + || property_exists($this->object, $this->name); + } + + protected function _property(): ReflectionProperty { + $property = $this->class->getProperty($this->name); + $property->setAccessible(true); + return $property; + } + + protected function _get($default=null) { + try { + return $this->_property()->getValue($this->object); + } catch (ReflectionException $e) { + } + $name = $this->name; + if (property_exists($this->object, $name)) { + return $this->object->$name; + } else { + return $default; + } + } + + function available(): bool { + if (!$this->exists()) return false; + $value = $this->_get(); + if ($value === "") return $this->allowEmpty; + if ($value === null) return $this->allowNull; + if ($value === false) return $this->allowFalse; + return true; + } + + function get($default=null) { + if (!$this->exists()) return $default; + $value = $this->_get(); + if ($value === "" && !$this->allowEmpty) return $default; + if ($value === null && !$this->allowNull) return $default; + if ($value === false && !$this->allowFalse) return $default; + return $value; + } + + protected function _set($value): void { + try { + $this->_property()->setValue($this->object, $value); + } catch (ReflectionException $e) { + $name = $this->name; + $this->object->$name = $value; + } + } + + function set($value): void { + $this->_set($value); + } + + function del(): void { + $this->_set(null); + } + + function addKey($key): IAccess { + return new ChainKeyAccess($this, $key); + } +} diff --git a/src/php/access/ShadowAccess.php b/src/php/access/ShadowAccess.php index e4f1211..ab0e33a 100644 --- a/src/php/access/ShadowAccess.php +++ b/src/php/access/ShadowAccess.php @@ -55,6 +55,6 @@ class ShadowAccess extends AbstractAccess { } function addKey($key): IAccess { - return new ChainAccess($this, $key); + return new ChainKeyAccess($this, $key); } } From c5bfa3940cd599db1882888fd6ef25ed8b75b03c Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 17:03:12 +0400 Subject: [PATCH 14/27] modifs.mineures sans commentaires --- src/php/access/PropertyAccess.php | 39 ++++++++++++++++--------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php index 1550173..fe09704 100644 --- a/src/php/access/PropertyAccess.php +++ b/src/php/access/PropertyAccess.php @@ -9,18 +9,25 @@ class PropertyAccess extends AbstractAccess { function __construct(object &$object, $name, ?array $params=null) { parent::__construct($params); $this->object =& $object; - $this->class = new ReflectionClass($object); $this->name = $name; + $class = new ReflectionClass($object); + try { + $property = $class->getProperty($this->name); + $property->setAccessible(true); + } catch (ReflectionException $e) { + $property = null; + } + $this->property = $property; $this->allowNull = $params["allow_null"] ?? true; $this->allowFalse = $params["allow_false"] ?? false; } protected object $object; - protected ReflectionClass $class; - protected string $name; + protected ?ReflectionProperty $property; + protected bool $allowNull; protected bool $allowFalse; @@ -31,23 +38,16 @@ class PropertyAccess extends AbstractAccess { } function exists(): bool { - return $this->class->hasProperty($this->name) + return $this->property !== null || property_exists($this->object, $this->name); } - protected function _property(): ReflectionProperty { - $property = $this->class->getProperty($this->name); - $property->setAccessible(true); - return $property; - } - protected function _get($default=null) { - try { - return $this->_property()->getValue($this->object); - } catch (ReflectionException $e) { - } $name = $this->name; - if (property_exists($this->object, $name)) { + $property = $this->property; + if ($property !== null) { + return $property->getValue($this->object); + } elseif (property_exists($this->object, $name)) { return $this->object->$name; } else { return $default; @@ -73,10 +73,11 @@ class PropertyAccess extends AbstractAccess { } protected function _set($value): void { - try { - $this->_property()->setValue($this->object, $value); - } catch (ReflectionException $e) { - $name = $this->name; + $name = $this->name; + $property = $this->property; + if ($property !== null) { + $property->setValue($this->object, $value); + } else { $this->object->$name = $value; } } From baa770d969b9bed7d804e77e8ef79b0cee942222 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 17:05:26 +0400 Subject: [PATCH 15/27] modifs.mineures sans commentaires --- src/php/access/PropertyAccess.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php index fe09704..ec823c1 100644 --- a/src/php/access/PropertyAccess.php +++ b/src/php/access/PropertyAccess.php @@ -6,9 +6,9 @@ use ReflectionException; use ReflectionProperty; class PropertyAccess extends AbstractAccess { - function __construct(object &$object, $name, ?array $params=null) { + function __construct(object $object, $name, ?array $params=null) { parent::__construct($params); - $this->object =& $object; + $this->object = $object; $this->name = $name; $class = new ReflectionClass($object); try { @@ -32,8 +32,8 @@ class PropertyAccess extends AbstractAccess { protected bool $allowFalse; - function reset(object &$object): self { - $this->object =& $object; + function reset(object $object): self { + $this->object = $object; return $this; } From 19f6f9c9e1b47fef1cc3bec739424a3e9bf4d7e7 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 18:31:49 +0400 Subject: [PATCH 16/27] modifs.mineures sans commentaires --- src/php/access/ChainAccess.php | 150 ++++++++++++++++++++++++++++++ src/php/access/ChainKeyAccess.php | 57 ------------ src/php/access/PropertyAccess.php | 2 +- src/php/access/ShadowAccess.php | 2 +- 4 files changed, 152 insertions(+), 59 deletions(-) create mode 100644 src/php/access/ChainAccess.php delete mode 100644 src/php/access/ChainKeyAccess.php diff --git a/src/php/access/ChainAccess.php b/src/php/access/ChainAccess.php new file mode 100644 index 0000000..cd3d1cd --- /dev/null +++ b/src/php/access/ChainAccess.php @@ -0,0 +1,150 @@ +access = $access; + $this->key = $key; + $this->accessType = $params["access_type"] ?? self::ACCESS_AUTO; + } + + protected IAccess $access; + + /** @var int|string|array */ + protected $key; + + protected int $accessType; + + protected function _accessType($access, $key): int { + $accessType = $this->accessType; + if ($accessType === self::ACCESS_AUTO) { + if (is_object($access) && is_string($key)) { + $accessType = self::ACCESS_PROPERTY; + } else { + $accessType = self::ACCESS_KEY; + } + } + return $accessType; + } + + protected function _has(): bool { + $src = $this->access->get(); + $key = $this->key; + $accessType = $this->_accessType($src, $key); + if ($accessType === self::ACCESS_KEY) { + return cl::phas($src, $key); + } elseif ($accessType === self::ACCESS_PROPERTY) { + $class = new ReflectionClass($src); + return $class->hasProperty($key) || property_exists($src, $key); + } else { + throw StateException::unexpected_state(); + } + } + + protected function _get($default=null) { + $src = $this->access->get(); + $key = $this->key; + $accessType = $this->_accessType($src, $key); + if ($accessType === self::ACCESS_KEY) { + return cl::pget($src, $key); + } elseif ($accessType === self::ACCESS_PROPERTY) { + $class = new ReflectionClass($src); + try { + $property = $class->getProperty($key); + $property->setAccessible(true); + } catch (ReflectionException $e) { + $property = null; + } + if ($property !== null) { + return $property->getValue($src); + } elseif (property_exists($src, $key)) { + return $src->$key; + } else { + return $default; + } + } else { + throw StateException::unexpected_state(); + } + } + + protected function _pset(object $dest, $name, $value): void { + $class = new ReflectionClass($dest); + try { + $property = $class->getProperty($name); + $property->setAccessible(true); + } catch (ReflectionException $e) { + $property = null; + } + if ($property !== null) { + $property->setValue($dest, $value); + } else { + $dest->$name = $value; + } + } + + function isAllowEmpty(): bool { + return $this->access->isAllowEmpty(); + } + + function exists(): bool { + if ($this->key === null) return false; + if (!$this->access->exists()) return false; + return $this->_has(); + } + + function available(): bool { + if ($this->key === null) return false; + if (!$this->access->available()) return false; + if (!$this->_has()) return false; + return $this->isAllowEmpty() || $this->_get() !== ""; + } + + function get($default=null) { + return $this->_get($default); + } + + function set($value): void { + $dest = $this->access->get(); + $key = $this->key; + $accessType = $this->_accessType($dest, $key); + if ($accessType === self::ACCESS_KEY) { + cl::pset($dest, $key, $value); + $this->access->set($dest); + } elseif ($accessType === self::ACCESS_PROPERTY) { + $this->_pset($dest, $key, $value); + } else { + throw StateException::unexpected_state(); + } + } + + function del(): void { + $dest = $this->access->get(); + $key = $this->key; + $accessType = $this->_accessType($dest, $key); + if ($accessType === self::ACCESS_KEY) { + cl::pdel($dest, $key); + $this->access->set($dest); + } elseif ($accessType === self::ACCESS_PROPERTY) { + $this->_pset($dest, $key, null); + } else { + throw StateException::unexpected_state(); + } + } + + function addKey($key, ?array $params=null): IAccess { + $accessType = $params["access_type"] ?? self::ACCESS_AUTO; + if ($accessType === self::ACCESS_KEY && $accessType === $this->accessType) { + return new ChainAccess($this->access, cl::merge($this->key, $key)); + } else { + return new ChainAccess($this, $key); + } + } +} diff --git a/src/php/access/ChainKeyAccess.php b/src/php/access/ChainKeyAccess.php deleted file mode 100644 index f2460f8..0000000 --- a/src/php/access/ChainKeyAccess.php +++ /dev/null @@ -1,57 +0,0 @@ -access = $access; - $this->key = $key; - } - - protected IAccess $access; - - /** @var int|string|array */ - protected $key; - - function isAllowEmpty(): bool { - return $this->access->isAllowEmpty(); - } - - function exists(): bool { - $key = $this->key; - if ($key === null) return false; - if (!$this->access->exists()) return false; - return cl::phas($this->access->get(), $key); - } - - function available(): bool { - $key = $this->key; - if ($key === null) return false; - if (!$this->access->available()) return false; - $array = $this->access->get(); - if (!cl::phas($array, $key)) return false; - return $this->isAllowEmpty() || cl::pget($array, $key) !== ""; - } - - function get($default=null) { - return cl::pget($this->access->get($default), $this->key); - } - - function set($value): void { - $array = $this->access->get(); - cl::pset($array, $this->key, $value); - $this->access->set($array); - } - - function del(): void { - $array = $this->access->get(); - cl::pdel($array, $this->key); - $this->access->set($array); - } - - function addKey($key): IAccess { - return new ChainKeyAccess($this->access, cl::merge($this->key, $key)); - } -} diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php index ec823c1..832ea88 100644 --- a/src/php/access/PropertyAccess.php +++ b/src/php/access/PropertyAccess.php @@ -91,6 +91,6 @@ class PropertyAccess extends AbstractAccess { } function addKey($key): IAccess { - return new ChainKeyAccess($this, $key); + return new ChainAccess($this, $key); } } diff --git a/src/php/access/ShadowAccess.php b/src/php/access/ShadowAccess.php index ab0e33a..e4f1211 100644 --- a/src/php/access/ShadowAccess.php +++ b/src/php/access/ShadowAccess.php @@ -55,6 +55,6 @@ class ShadowAccess extends AbstractAccess { } function addKey($key): IAccess { - return new ChainKeyAccess($this, $key); + return new ChainAccess($this, $key); } } From f4e252a6e0a716e1743a7bab861336008937d560 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 19:32:27 +0400 Subject: [PATCH 17/27] modifs.mineures sans commentaires --- src/php/access/AbstractAccess.php | 4 +- src/php/access/FormAccess.php | 2 + src/php/access/KeyAccess.php | 88 ++++++++++++++++-------- src/php/access/ValueAccess.php | 62 ----------------- src/schema/input/Input.php | 44 ++++-------- tests/wip/php/access/KeyAccessTest.php | 64 ++++++++++++++++- tests/wip/php/access/ValueAccessTest.php | 69 ------------------- 7 files changed, 143 insertions(+), 190 deletions(-) delete mode 100644 src/php/access/ValueAccess.php delete mode 100644 tests/wip/php/access/ValueAccessTest.php diff --git a/src/php/access/AbstractAccess.php b/src/php/access/AbstractAccess.php index f162ca5..417d2cb 100644 --- a/src/php/access/AbstractAccess.php +++ b/src/php/access/AbstractAccess.php @@ -8,8 +8,10 @@ use nulib\cl; * de {@link IAccess} */ abstract class AbstractAccess implements IAccess { + const ALLOW_EMPTY = true; + function __construct(?array $params=null) { - $this->allowEmpty = $params["allow_empty"] ?? true; + $this->allowEmpty = $params["allow_empty"] ?? static::ALLOW_EMPTY; } protected bool $allowEmpty; diff --git a/src/php/access/FormAccess.php b/src/php/access/FormAccess.php index db8d09a..92c2a8c 100644 --- a/src/php/access/FormAccess.php +++ b/src/php/access/FormAccess.php @@ -7,6 +7,8 @@ use nulib\cl; * Class FormAccess: accès à une valeur de $_POST puis $_GET, dans cet ordre */ class FormAccess extends AbstractAccess { + const ALLOW_EMPTY = false; + function __construct($key, ?array $params=null) { parent::__construct($params); $this->key = $key; diff --git a/src/php/access/KeyAccess.php b/src/php/access/KeyAccess.php index 2f7b4c4..b6e5979 100644 --- a/src/php/access/KeyAccess.php +++ b/src/php/access/KeyAccess.php @@ -3,70 +3,102 @@ namespace nur\sery\wip\php\access; use ArrayAccess; use nulib\cl; +use stdClass; /** - * Class KeyAccess: accès à une valeur d'une clé dans un tableau + * Class KeyAccess: accès + * - soit à une valeur d'un chemin de clé dans un tableau (si $key !== null) + * - soit à une valeur scalaire (si $key === null) */ class KeyAccess extends AbstractAccess { - function __construct(&$array, $key, ?array $params=null) { + const ALLOW_NULL = null; + const ALLOW_FALSE = null; + + function __construct(&$dest, $key=null, ?array $params=null) { parent::__construct($params); - $this->array =& $array; + $this->dest =& $dest; $this->key = $key; - $this->allowNull = $params["allow_null"] ?? true; - $this->allowFalse = $params["allow_false"] ?? false; + $this->allowNull = $params["allow_null"] ?? static::ALLOW_NULL; + $this->allowFalse = $params["allow_false"] ?? static::ALLOW_FALSE; } - /** @var array|ArrayAccess */ - protected $array; + /** @var mixed|array|ArrayAccess */ + protected $dest; - /** @var int|string|array */ + /** @var null|int|string|array */ protected $key; - protected bool $allowNull; - - protected bool $allowFalse; - - function reset(&$array): self { - $this->array =& $array; + function reset(&$dest, $key=null): self { + $this->dest =& $dest; + $this->key = $key; return $this; } + function resetKey($key=null): self { + $this->key = $key; + return $this; + } + + protected ?bool $allowNull; + + protected function isAllowNull(): bool { + $allowNull = $this->allowNull; + if ($allowNull !== null) return $allowNull; + return $this->key !== null; + } + + protected ?bool $allowFalse; + + protected function isAllowFalse(): bool { + $allowFalse = $this->allowFalse; + if ($allowFalse !== null) return $allowFalse; + return $this->key === null; + } + function exists(): bool { $key = $this->key; - if ($key === null) return false; - return cl::phas($this->array, $key); + if ($key === null) { + return $this->isAllowNull() || $this->dest !== null; + } else { + return cl::phas($this->dest, $key); + } } function available(): bool { if (!$this->exists()) return false; - $value = cl::pget($this->array, $this->key); + $key = $this->key; + if ($key === null) $value = $this->dest; + else $value = cl::pget($this->dest, $key); if ($value === "") return $this->allowEmpty; - if ($value === null) return $this->allowNull; - if ($value === false) return $this->allowFalse; + if ($value === null) return $this->isAllowNull(); + if ($value === false) return $this->isAllowFalse(); return true; } function get($default=null) { - if ($this->key === null) return $default; - $value = cl::pget($this->array, $this->key, $default); + $key = $this->key; + if ($key === null) $value = $this->dest; + else $value = cl::pget($this->dest, $key, $default); if ($value === "" && !$this->allowEmpty) return $default; - if ($value === null && !$this->allowNull) return $default; - if ($value === false && !$this->allowFalse) return $default; + if ($value === null && !$this->isAllowNull()) return $default; + if ($value === false && !$this->isAllowFalse()) return $default; return $value; } function set($value): void { - if ($this->key === null) return; - cl::pset($this->array, $this->key, $value); + $key = $this->key; + if ($key === null) $this->dest = $value; + else cl::pset($this->dest, $key, $value); } function del(): void { - if ($this->key === null) return; - cl::pdel($this->array, $this->key); + $key = $this->key; + if ($key === null) $this->dest = null; + else cl::pdel($this->dest, $key); } function addKey($key): self { - return new KeyAccess($this->array, cl::merge($this->key, $key), [ + return new KeyAccess($this->dest, cl::merge($this->key, $key), [ "allow_empty" => $this->allowEmpty, "allow_null" => $this->allowNull, "allow_false" => $this->allowFalse, diff --git a/src/php/access/ValueAccess.php b/src/php/access/ValueAccess.php deleted file mode 100644 index 3b95431..0000000 --- a/src/php/access/ValueAccess.php +++ /dev/null @@ -1,62 +0,0 @@ -value =& $value; - $this->allowNull = $params["allow_null"] ?? false; - $this->allowFalse = $params["allow_false"] ?? true; - } - - /** @var mixed */ - protected $value; - - protected bool $allowNull; - - protected bool $allowFalse; - - function reset(&$value): self { - $this->value =& $value; - return $this; - } - - function exists(): bool { - return $this->allowNull || $this->value !== null; - } - - function available(): bool { - if (!$this->exists()) return false; - $value = $this->value; - if ($value === false) return $this->allowFalse; - if ($value === "") return $this->allowEmpty; - return true; - } - - function get($default=null) { - $value = $this->value; - if ($value === null && !$this->allowNull) return $default; - if ($value === false && !$this->allowFalse) return $default; - if ($value === "" && !$this->allowEmpty) return $default; - return $value; - } - - function set($value): void { - $this->value = $value; - } - - function del(): void { - $this->value = null; - } - - function addKey($key): KeyAccess { - return new KeyAccess($this->value, $key, [ - "allow_empty" => $this->allowEmpty, - "allow_null" => $this->allowNull, - "allow_false" => $this->allowFalse, - ]); - } -} diff --git a/src/schema/input/Input.php b/src/schema/input/Input.php index 1ee3c7e..6c63ed9 100644 --- a/src/schema/input/Input.php +++ b/src/schema/input/Input.php @@ -1,9 +1,8 @@ value =& $value; - $this->allowEmpty = $params["allow_empty"] ?? static::ALLOW_EMPTY; - } - - /** @var mixed */ - protected $value; - - /** - * @var bool comment considérer une chaine vide: "" si allowEmpty, null sinon - */ - protected $allowEmpty; - - protected ?ValueAccess $valueAccess = null; - protected ?array $keyAccess = null; - - protected function access($key): IAccess { - if ($key === null) { - return $this->valueAccess ??= new ValueAccess($this->value, [ + function __construct(&$dest=null, ?array $params=null) { + if (is_object($dest)) { + $this->access = new PropertyAccess($dest, null, [ + "allow_empty" => $params["allow_empty"] ?? static::ALLOW_EMPTY, "allow_null" => true, - "allow_empty" => $this->allowEmpty, ]); } else { - return $this->keyAccess[$key] ??= new KeyAccess($this->value, $key, [ - "allow_empty" => $this->allowEmpty, + $this->access = new KeyAccess($dest, null, [ + "allow_empty" => $params["allow_empty"] ?? static::ALLOW_EMPTY, + "allow_null" => true, ]); } } + protected KeyAccess $access; + /** tester si la valeur existe sans tenir compte de $allowEmpty */ function isPresent($key=null): bool { - return $this->access($key)->exists(); + return $this->access->resetKey($key)->exists(); } /** tester si la valeur est disponible en tenant compte de $allowEmpty */ function isAvailable($key=null): bool { - return $this->access($key)->available(); + return $this->access->resetKey($key)->available(); } function get($key=null) { - return $this->access($key)->get(); + return $this->access->resetKey($key)->get(); } function set($value, $key=null): void { - $this->access($key)->set($value); + $this->access->resetKey($key)->set($value); } function unset($key=null): void { - $this->access($key)->del(); + $this->access->resetKey($key)->del(); } function addKey($key): IInput { diff --git a/tests/wip/php/access/KeyAccessTest.php b/tests/wip/php/access/KeyAccessTest.php index 2b1c8ff..d71eb8e 100644 --- a/tests/wip/php/access/KeyAccessTest.php +++ b/tests/wip/php/access/KeyAccessTest.php @@ -5,7 +5,69 @@ use nulib\tests\TestCase; use stdClass; class KeyAccessTest extends TestCase { - function testAccess() { + function testValueAccess() { + $default = new stdClass(); + + # + $i = null; + $a = new KeyAccess($i); + self::assertFalse($a->exists()); + self::assertFalse($a->available()); + self::assertSame($default, $a->get($default)); + + $i = false; + $a = new KeyAccess($i); + self::assertTrue($a->exists()); + self::assertTrue($a->available()); + self::assertSame(false, $a->get($default)); + + $i = ""; + $a = new KeyAccess($i); + self::assertTrue($a->exists()); + self::assertTrue($a->available()); + self::assertSame("", $a->get($default)); + + # + $i = null; + $a = new KeyAccess($i, null, ["allow_null" => false]); + self::assertFalse($a->exists()); + self::assertFalse($a->available()); + self::assertSame($default, $a->get($default)); + + $i = null; + $a = new KeyAccess($i, null, ["allow_null" => true]); + self::assertTrue($a->exists()); + self::assertTrue($a->available()); + self::assertSame(null, $a->get($default)); + + # + $i = false; + $a = new KeyAccess($i, null, ["allow_false" => false]); + self::assertTrue($a->exists()); + self::assertFalse($a->available()); + self::assertSame($default, $a->get($default)); + + $i = false; + $a = new KeyAccess($i, null, ["allow_false" => true]); + self::assertTrue($a->exists()); + self::assertTrue($a->available()); + self::assertSame(false, $a->get($default)); + + # + $i = ""; + $a = new KeyAccess($i, null, ["allow_empty" => false]); + self::assertTrue($a->exists()); + self::assertFalse($a->available()); + self::assertSame($default, $a->get($default)); + + $i = ""; + $a = new KeyAccess($i, null, ["allow_empty" => true]); + self::assertTrue($a->exists()); + self::assertTrue($a->available()); + self::assertSame("", $a->get($default)); + } + + function testArrayAccess() { $default = new stdClass(); $array = ["null" => null, "false" => false, "empty" => ""]; diff --git a/tests/wip/php/access/ValueAccessTest.php b/tests/wip/php/access/ValueAccessTest.php deleted file mode 100644 index 3bd9333..0000000 --- a/tests/wip/php/access/ValueAccessTest.php +++ /dev/null @@ -1,69 +0,0 @@ -exists()); - self::assertFalse($a->available()); - self::assertSame($default, $a->get($default)); - - $i = false; - $a = new ValueAccess($i); - self::assertTrue($a->exists()); - self::assertTrue($a->available()); - self::assertSame(false, $a->get($default)); - - $i = ""; - $a = new ValueAccess($i); - self::assertTrue($a->exists()); - self::assertTrue($a->available()); - self::assertSame("", $a->get($default)); - - # - $i = null; - $a = new ValueAccess($i, ["allow_null" => false]); - self::assertFalse($a->exists()); - self::assertFalse($a->available()); - self::assertSame($default, $a->get($default)); - - $i = null; - $a = new ValueAccess($i, ["allow_null" => true]); - self::assertTrue($a->exists()); - self::assertTrue($a->available()); - self::assertSame(null, $a->get($default)); - - # - $i = false; - $a = new ValueAccess($i, ["allow_false" => false]); - self::assertTrue($a->exists()); - self::assertFalse($a->available()); - self::assertSame($default, $a->get($default)); - - $i = false; - $a = new ValueAccess($i, ["allow_false" => true]); - self::assertTrue($a->exists()); - self::assertTrue($a->available()); - self::assertSame(false, $a->get($default)); - - # - $i = ""; - $a = new ValueAccess($i, ["allow_empty" => false]); - self::assertTrue($a->exists()); - self::assertFalse($a->available()); - self::assertSame($default, $a->get($default)); - - $i = ""; - $a = new ValueAccess($i, ["allow_empty" => true]); - self::assertTrue($a->exists()); - self::assertTrue($a->available()); - self::assertSame("", $a->get($default)); - } -} From 6e8245dbcb58caec8f4c786c3959c1ceb3d7e405 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Wed, 19 Mar 2025 20:34:46 +0400 Subject: [PATCH 18/27] modifs.mineures sans commentaires --- src/php/access/KeyAccess.php | 3 +- src/php/access/PropertyAccess.php | 49 +++++++++++++++++++++++-------- src/schema/input/Input.php | 3 +- 3 files changed, 39 insertions(+), 16 deletions(-) diff --git a/src/php/access/KeyAccess.php b/src/php/access/KeyAccess.php index b6e5979..b65b86d 100644 --- a/src/php/access/KeyAccess.php +++ b/src/php/access/KeyAccess.php @@ -3,7 +3,6 @@ namespace nur\sery\wip\php\access; use ArrayAccess; use nulib\cl; -use stdClass; /** * Class KeyAccess: accès @@ -13,7 +12,7 @@ use stdClass; class KeyAccess extends AbstractAccess { const ALLOW_NULL = null; const ALLOW_FALSE = null; - + function __construct(&$dest, $key=null, ?array $params=null) { parent::__construct($params); $this->dest =& $dest; diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php index 832ea88..d27493f 100644 --- a/src/php/access/PropertyAccess.php +++ b/src/php/access/PropertyAccess.php @@ -6,7 +6,10 @@ use ReflectionException; use ReflectionProperty; class PropertyAccess extends AbstractAccess { - function __construct(object $object, $name, ?array $params=null) { + const ALLOW_NULL = true; + const ALLOW_FALSE = false; + + function __construct(object $object, ?string $name=null, ?array $params=null) { parent::__construct($params); $this->object = $object; $this->name = $name; @@ -18,34 +21,44 @@ class PropertyAccess extends AbstractAccess { $property = null; } $this->property = $property; - $this->allowNull = $params["allow_null"] ?? true; - $this->allowFalse = $params["allow_false"] ?? false; + $this->allowNull = $params["allow_null"] ?? static::ALLOW_NULL; + $this->allowFalse = $params["allow_false"] ?? static::ALLOW_FALSE; } protected object $object; - protected string $name; + protected ?string $name; protected ?ReflectionProperty $property; + function reset(object $object, ?string $name=null): self { + $this->object = $object; + $this->name = $name; + return $this; + } + + function resetKey($name=null): self { + $this->name = $name; + return $this; + } + protected bool $allowNull; protected bool $allowFalse; - function reset(object $object): self { - $this->object = $object; - return $this; - } - function exists(): bool { - return $this->property !== null - || property_exists($this->object, $this->name); + $name = $this->name; + return $name === null + || $this->property !== null + || property_exists($this->object, $name); } protected function _get($default=null) { $name = $this->name; $property = $this->property; - if ($property !== null) { + if ($name === null) { + return $this->object; + } elseif ($property !== null) { return $property->getValue($this->object); } elseif (property_exists($this->object, $name)) { return $this->object->$name; @@ -75,7 +88,17 @@ class PropertyAccess extends AbstractAccess { protected function _set($value): void { $name = $this->name; $property = $this->property; - if ($property !== null) { + if ($name === null) { + $this->object = $value; + $class = new ReflectionClass($value); + try { + $property = $class->getProperty($this->name); + $property->setAccessible(true); + } catch (ReflectionException $e) { + $property = null; + } + $this->property = $property; + } elseif ($property !== null) { $property->setValue($this->object, $value); } else { $this->object->$name = $value; diff --git a/src/schema/input/Input.php b/src/schema/input/Input.php index 6c63ed9..e951a62 100644 --- a/src/schema/input/Input.php +++ b/src/schema/input/Input.php @@ -1,6 +1,7 @@ Date: Thu, 20 Mar 2025 08:01:50 +0400 Subject: [PATCH 19/27] modifs.mineures sans commentaires --- src/php/access/ChainAccess.php | 35 ++++++--- src/php/access/FormAccess.php | 22 ++++-- src/php/access/KeyAccess.php | 23 ++++-- src/php/access/PropertyAccess.php | 85 +++++++++++++-------- src/schema/TODO.md | 3 - src/schema/_assoc/AssocWrapper.php | 28 ++++--- src/schema/_scalar/ScalarWrapper.php | 12 +-- src/schema/input/ChainInput.php | 5 -- src/schema/input/FormInput.php | 16 ++-- src/schema/input/GetInput.php | 6 +- src/schema/input/IInput.php | 18 ----- src/schema/input/Input.php | 36 ++++++--- src/schema/input/PostInput.php | 6 +- src/schema/types/IType.php | 4 +- src/schema/types/tarray.php | 2 +- src/schema/types/tbool.php | 2 +- src/schema/types/tcallable.php | 2 +- src/schema/types/tcontent.php | 2 +- src/schema/types/tfloat.php | 2 +- src/schema/types/tgeneric.php | 2 +- src/schema/types/tint.php | 2 +- src/schema/types/tkey.php | 2 +- src/schema/types/tmixed.php | 2 +- src/schema/types/tpkey.php | 2 +- src/schema/types/trawstring.php | 2 +- tests/wip/schema/_assoc/AssocSchemaTest.php | 27 ++++++- 26 files changed, 214 insertions(+), 134 deletions(-) delete mode 100644 src/schema/input/ChainInput.php delete mode 100644 src/schema/input/IInput.php diff --git a/src/php/access/ChainAccess.php b/src/php/access/ChainAccess.php index cd3d1cd..299c01d 100644 --- a/src/php/access/ChainAccess.php +++ b/src/php/access/ChainAccess.php @@ -9,6 +9,10 @@ use ReflectionException; class ChainAccess extends AbstractAccess { const ACCESS_AUTO = 0, ACCESS_KEY = 1, ACCESS_PROPERTY = 2; + private static function unexpected_access_type(): StateException { + return StateException::unexpected_state("access_type"); + } + function __construct(IAccess $access, $key, ?array $params=null) { parent::__construct(); $this->access = $access; @@ -18,7 +22,7 @@ class ChainAccess extends AbstractAccess { protected IAccess $access; - /** @var int|string|array */ + /** @var null|int|string|array */ protected $key; protected int $accessType; @@ -45,7 +49,7 @@ class ChainAccess extends AbstractAccess { $class = new ReflectionClass($src); return $class->hasProperty($key) || property_exists($src, $key); } else { - throw StateException::unexpected_state(); + throw self::unexpected_access_type(); } } @@ -71,7 +75,7 @@ class ChainAccess extends AbstractAccess { return $default; } } else { - throw StateException::unexpected_state(); + throw self::unexpected_access_type(); } } @@ -95,23 +99,30 @@ class ChainAccess extends AbstractAccess { } function exists(): bool { - if ($this->key === null) return false; if (!$this->access->exists()) return false; + if ($this->key === null) return true; return $this->_has(); } function available(): bool { - if ($this->key === null) return false; if (!$this->access->available()) return false; + if ($this->key === null) return true; if (!$this->_has()) return false; return $this->isAllowEmpty() || $this->_get() !== ""; } function get($default=null) { + if ($this->key === null) { + return $this->access->get($default); + } return $this->_get($default); } function set($value): void { + if ($this->key === null) { + $this->access->set($value); + return; + } $dest = $this->access->get(); $key = $this->key; $accessType = $this->_accessType($dest, $key); @@ -121,11 +132,15 @@ class ChainAccess extends AbstractAccess { } elseif ($accessType === self::ACCESS_PROPERTY) { $this->_pset($dest, $key, $value); } else { - throw StateException::unexpected_state(); + throw self::unexpected_access_type(); } } function del(): void { + if ($this->key === null) { + $this->access->del(); + return; + } $dest = $this->access->get(); $key = $this->key; $accessType = $this->_accessType($dest, $key); @@ -135,14 +150,16 @@ class ChainAccess extends AbstractAccess { } elseif ($accessType === self::ACCESS_PROPERTY) { $this->_pset($dest, $key, null); } else { - throw StateException::unexpected_state(); + throw self::unexpected_access_type(); } } function addKey($key, ?array $params=null): IAccess { - $accessType = $params["access_type"] ?? self::ACCESS_AUTO; + if ($key === null) return $this; + $accessType = $params["access_type"] ?? $this->accessType; if ($accessType === self::ACCESS_KEY && $accessType === $this->accessType) { - return new ChainAccess($this->access, cl::merge($this->key, $key)); + if ($this->key !== null) $key = cl::merge($this->key, $key); + return new ChainAccess($this->access, $key); } else { return new ChainAccess($this, $key); } diff --git a/src/php/access/FormAccess.php b/src/php/access/FormAccess.php index 92c2a8c..2368e75 100644 --- a/src/php/access/FormAccess.php +++ b/src/php/access/FormAccess.php @@ -14,12 +14,12 @@ class FormAccess extends AbstractAccess { $this->key = $key; } - /** @var int|string|array */ + /** @var null|int|string|array */ protected $key; protected function _exists(array $first, ?array $second=null): bool { $key = $this->key; - if ($key === null) return false; + if ($key === null) return true; if (cl::phas($first, $key)) return true; return $second !== null && cl::phas($second, $key); } @@ -30,7 +30,7 @@ class FormAccess extends AbstractAccess { protected function _available(array $first, ?array $second=null): bool { $key = $this->key; - if ($key === null) return false; + if ($key === null) return true; if (cl::phas($first, $key)) { return $this->allowEmpty || cl::pget($first, $key) !== ""; } elseif ($second !== null && cl::phas($second, $key)) { @@ -46,7 +46,7 @@ class FormAccess extends AbstractAccess { protected function _get($default, array $first, ?array $second=null) { $key = $this->key; - if ($key === null) return $default; + if ($key === null) return cl::merge($first, $second); if (cl::phas($first, $key)) { $value = cl::pget($first, $key); if ($value !== "" || $this->allowEmpty) return $value; @@ -63,7 +63,10 @@ class FormAccess extends AbstractAccess { function _set($value, array &$first, ?array &$second=null): void { $key = $this->key; - if ($key === null) return; + if ($key === null) { + # interdire la modification de la destination + return; + } if ($second !== null && !cl::phas($first, $key) && cl::phas($second, $key)) { cl::pset($second, $key, $value); } else { @@ -77,7 +80,10 @@ class FormAccess extends AbstractAccess { function _del(array &$first, ?array &$second=null): void { $key = $this->key; - if ($key === null) return; + if ($key === null) { + # interdire la modification de la destination + return; + } if ($second !== null && !cl::phas($first, $key) && cl::phas($second, $key)) { cl::pdel($second, $key); } else { @@ -90,7 +96,9 @@ class FormAccess extends AbstractAccess { } function addKey($key): self { - return new static(cl::merge($this->key, $key), [ + if ($key === null) return $this; + if ($this->key !== null) $key = cl::merge($this->key, $key); + return new static($key, [ "allow_empty" => $this->allowEmpty ]); } diff --git a/src/php/access/KeyAccess.php b/src/php/access/KeyAccess.php index b65b86d..38bfee5 100644 --- a/src/php/access/KeyAccess.php +++ b/src/php/access/KeyAccess.php @@ -12,15 +12,19 @@ use nulib\cl; class KeyAccess extends AbstractAccess { const ALLOW_NULL = null; const ALLOW_FALSE = null; + const PROTECT_DEST = false; function __construct(&$dest, $key=null, ?array $params=null) { parent::__construct($params); + $this->protectDest = $params["protect_dest"] ?? static::PROTECT_DEST; $this->dest =& $dest; $this->key = $key; $this->allowNull = $params["allow_null"] ?? static::ALLOW_NULL; $this->allowFalse = $params["allow_false"] ?? static::ALLOW_FALSE; } + protected bool $protectDest; + /** @var mixed|array|ArrayAccess */ protected $dest; @@ -86,21 +90,30 @@ class KeyAccess extends AbstractAccess { function set($value): void { $key = $this->key; - if ($key === null) $this->dest = $value; - else cl::pset($this->dest, $key, $value); + if ($key === null) { + if (!$this->protectDest) $this->dest = $value; + } else { + cl::pset($this->dest, $key, $value); + } } function del(): void { $key = $this->key; - if ($key === null) $this->dest = null; - else cl::pdel($this->dest, $key); + if ($key === null) { + if (!$this->protectDest) $this->dest = null; + } else { + cl::pdel($this->dest, $key); + } } function addKey($key): self { - return new KeyAccess($this->dest, cl::merge($this->key, $key), [ + if ($key === null) return $this; + if ($this->key !== null) $key = cl::merge($this->key, $key); + return new KeyAccess($this->dest, $key, [ "allow_empty" => $this->allowEmpty, "allow_null" => $this->allowNull, "allow_false" => $this->allowFalse, + "protect_dest" => $this->protectDest, ]); } } diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php index d27493f..eadf80d 100644 --- a/src/php/access/PropertyAccess.php +++ b/src/php/access/PropertyAccess.php @@ -1,44 +1,65 @@ object = $object; - $this->name = $name; - $class = new ReflectionClass($object); - try { - $property = $class->getProperty($this->name); - $property->setAccessible(true); - } catch (ReflectionException $e) { - $property = null; - } - $this->property = $property; + $this->protectDest = $params["protect_dest"] ?? static::PROTECT_DEST; + $this->mapNames = $params["map_names"] ?? static::MAP_NAMES; + $this->_setName($name); + $this->_setDest($dest); $this->allowNull = $params["allow_null"] ?? static::ALLOW_NULL; $this->allowFalse = $params["allow_false"] ?? static::ALLOW_FALSE; } - protected object $object; + protected bool $protectDest; + + protected ?object $dest; + protected bool $mapNames; protected ?string $name; protected ?ReflectionProperty $property; - function reset(object $object, ?string $name=null): self { - $this->object = $object; + private function _setName(?string $name): void { + if ($this->mapNames) $name = str::us2camel($name); $this->name = $name; + } + + private function _setDest(?object $dest): void { + $this->dest = $dest; + $property = null; + $name = $this->name; + if ($dest !== null && $name !== null) { + $class = new ReflectionClass($dest); + try { + $property = $class->getProperty($name); + $property->setAccessible(true); + } catch (ReflectionException $e) { + } + } + $this->property = $property; + } + + function reset(?object $dest, ?string $name=null): self { + $this->_setName($name); + $this->_setDest($dest); return $this; } function resetKey($name=null): self { - $this->name = $name; + $this->_setName($name); return $this; } @@ -48,20 +69,23 @@ class PropertyAccess extends AbstractAccess { function exists(): bool { $name = $this->name; + if ($this->dest === null) return false; return $name === null || $this->property !== null - || property_exists($this->object, $name); + || property_exists($this->dest, $name); } protected function _get($default=null) { $name = $this->name; $property = $this->property; - if ($name === null) { - return $this->object; + if ($this->dest === null) { + return $default; + } elseif ($name === null) { + return $this->dest; } elseif ($property !== null) { - return $property->getValue($this->object); - } elseif (property_exists($this->object, $name)) { - return $this->object->$name; + return $property->getValue($this->dest); + } elseif (property_exists($this->dest, $name)) { + return $this->dest->$name; } else { return $default; } @@ -88,20 +112,14 @@ class PropertyAccess extends AbstractAccess { protected function _set($value): void { $name = $this->name; $property = $this->property; - if ($name === null) { - $this->object = $value; - $class = new ReflectionClass($value); - try { - $property = $class->getProperty($this->name); - $property->setAccessible(true); - } catch (ReflectionException $e) { - $property = null; - } - $this->property = $property; + if ($this->dest === null) { + throw StateException::unexpected_state("dest is null"); + } elseif ($name === null) { + if (!$this->protectDest) $this->_setDest($value); } elseif ($property !== null) { - $property->setValue($this->object, $value); + $property->setValue($this->dest, $value); } else { - $this->object->$name = $value; + $this->dest->$name = $value; } } @@ -114,6 +132,7 @@ class PropertyAccess extends AbstractAccess { } function addKey($key): IAccess { + if ($key === null) return $this; return new ChainAccess($this, $key); } } diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 745781f..5dce1ef 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -1,8 +1,5 @@ # nulib\schema -* faire PropertyAccess -* si l'argument de Input() est un objet, utiliser PropertyAccess au lieu de KeyAccess - * possibilité de forcer l'un ou l'autre (paramètre type=value|array|object) * ensureKeys() et orderKeys() se fait au niveau de access (ou input?) * valeurs composite/computed diff --git a/src/schema/_assoc/AssocWrapper.php b/src/schema/_assoc/AssocWrapper.php index 5b71446..1add86c 100644 --- a/src/schema/_assoc/AssocWrapper.php +++ b/src/schema/_assoc/AssocWrapper.php @@ -57,8 +57,9 @@ class AssocWrapper extends Wrapper { else $input = $this->newInput($value); $context->input = $input; $context->valueKey = $valueKey; - foreach ($context->keyWrappers as $key => $wrapper) { - $wrapper->reset($input->subInput($valueKey), $key); + foreach ($context->keyWrappers as $key => $keyWrapper) { + $keyInput = $input->addKey($valueKey); + $keyWrapper->reset($keyInput, $key, ["analyze" => false]); } $this->afterModify($params, true); return $this; @@ -88,25 +89,34 @@ class AssocWrapper extends Wrapper { */ static function _analyze(WrapperContext $context, Wrapper $wrapper, ?array $params): int { if ($context->ensureArray) { - $array = $context->input->get(); - if ($array === null) $context->input->set([]); + $valueKey = $context->valueKey; + $array = $context->input->get($valueKey); + if ($array === null) $context->input->set([], $valueKey); } $what = ScalarWrapper::_analyze($context, $wrapper, $params); /** @var ScalarResult $result */ $result = $context->result; if (!$result->valid) return $what; - foreach ($context->keyWrappers as $wrapper) { - $wrapper->analyze($params); - if (!$wrapper->isValid()) { + foreach ($context->keyWrappers as $keyWrapper) { + $keyWrapper->analyze($params); + if (!$keyWrapper->isValid()) { $what = ref_analyze::INVALID; - $result->addInvalidMessage($wrapper); + $result->addInvalidMessage($keyWrapper); } } return $what; } + /** + * @param AssocWrapperContext $context + * @param AssocWrapper $wrapper + */ static function _normalize(WrapperContext $context, Wrapper $wrapper, ?array $params): bool { - return ScalarWrapper::_normalize($context, $wrapper, $params); + $modified = ScalarWrapper::_normalize($context, $wrapper, $params); + foreach ($context->keyWrappers as $keyWrapper) { + if ($keyWrapper->normalize($params)) $modified = true; + } + return $modified; } function getResult($key=false): Result { diff --git a/src/schema/_scalar/ScalarWrapper.php b/src/schema/_scalar/ScalarWrapper.php index f9ba7db..588e8b3 100644 --- a/src/schema/_scalar/ScalarWrapper.php +++ b/src/schema/_scalar/ScalarWrapper.php @@ -204,7 +204,7 @@ class ScalarWrapper extends Wrapper { /** @var ScalarResult $result */ $result = $context->result; - $verifix = false; + $normalize = false; $modified = false; if ($result->resultAvailable) { if ($result->null) { @@ -215,19 +215,19 @@ class ScalarWrapper extends Wrapper { $normalizedValue = $result->normalizedValue; if ($normalizedValue !== null) { # la valeur normalisée est disponible - $input->set($normalizedValue); + $input->set($normalizedValue, $valueKey); $result->normalizedValue = null; $modified = true; } else { # normaliser la valeur - $verifix = true; + $normalize = true; } } } else { - $verifix = true; + $normalize = true; } - if ($verifix) { + if ($normalize) { $value = $input->get($valueKey); /** @var func $normalizerFunc */ $normalizerFunc = $schema->normalizerFunc; @@ -236,7 +236,7 @@ class ScalarWrapper extends Wrapper { $value = $normalizerFunc->invoke([$orig, $context, $wrapper]); $modified = $value !== $orig; } else { - $modified = $context->type->verifix($value, $result, $schema); + $modified = $context->type->normalize($value, $result, $schema); } if ($result->valid) $input->set($value, $valueKey); } diff --git a/src/schema/input/ChainInput.php b/src/schema/input/ChainInput.php deleted file mode 100644 index 6e26061..0000000 --- a/src/schema/input/ChainInput.php +++ /dev/null @@ -1,5 +0,0 @@ - $this->allowEmpty, - ]); + function __construct(&$dest=null, ?array $params=null) { + parent::__construct($dest, $params); + $this->access = new ShadowAccess($this->formAccess($this->access), $this->access); } - protected function access($key): IAccess { - return $this->keyAccess[$key] ??= new ShadowAccess($this->formAccess($key), new KeyAccess($this->value, $key, [ - "allow_empty" => $this->allowEmpty, - ])); + protected function formAccess(IAccess $access): IAccess { + return new FormAccess(null, [ + "allow_empty" => $access->isAllowEmpty(), + ]); } } diff --git a/src/schema/input/GetInput.php b/src/schema/input/GetInput.php index 766c8e5..558e1ab 100644 --- a/src/schema/input/GetInput.php +++ b/src/schema/input/GetInput.php @@ -11,9 +11,9 @@ use nur\sery\wip\php\access\IAccess; * une référence */ class GetInput extends FormInput { - protected function formAccess($key): IAccess { - return new GetAccess($key, [ - "allow_empty" => $this->allowEmpty, + protected function formAccess(IAccess $access): IAccess { + return new GetAccess(null, [ + "allow_empty" => $access->isAllowEmpty(), ]); } } diff --git a/src/schema/input/IInput.php b/src/schema/input/IInput.php deleted file mode 100644 index a25bf55..0000000 --- a/src/schema/input/IInput.php +++ /dev/null @@ -1,18 +0,0 @@ -access = new PropertyAccess($dest, null, [ - "allow_empty" => $params["allow_empty"] ?? static::ALLOW_EMPTY, + "allow_empty" => $allowEmpty, + "allow_null" => true, + ]); + } elseif ($accessType == self::ACCESS_KEY) { + $this->access = new KeyAccess($dest, null, [ + "allow_empty" => $allowEmpty, "allow_null" => true, ]); } else { - $this->access = new KeyAccess($dest, null, [ - "allow_empty" => $params["allow_empty"] ?? static::ALLOW_EMPTY, - "allow_null" => true, - ]); + throw self::unexpected_access_type(); } } @@ -51,7 +66,10 @@ class Input implements IInput { $this->access->resetKey($key)->del(); } - function addKey($key): IInput { - return new ChainInput($this, $key); + function addKey($key): Input { + if ($key === null) return $this; + $input = clone $this; + $input->access = $this->access->addKey($key); + return $input; } } diff --git a/src/schema/input/PostInput.php b/src/schema/input/PostInput.php index bf720ab..9b5fef6 100644 --- a/src/schema/input/PostInput.php +++ b/src/schema/input/PostInput.php @@ -11,9 +11,9 @@ use nur\sery\wip\php\access\PostAccess; * une référence */ class PostInput extends FormInput { - protected function formAccess($key): IAccess { - return new PostAccess($key, [ - "allow_empty" => $this->allowEmpty, + protected function formAccess(IAccess $access): IAccess { + return new PostAccess(null, [ + "allow_empty" => $access->isAllowEmpty(), ]); } } diff --git a/src/schema/types/IType.php b/src/schema/types/IType.php index 36f5fd4..9dbd48a 100644 --- a/src/schema/types/IType.php +++ b/src/schema/types/IType.php @@ -23,7 +23,7 @@ interface IType { /** * @return string la classe des objets gérés par ce format: le type attendu - * par {@link format()} et le type retourné par {@link verifix()} + * par {@link format()} et le type retourné par {@link normalize()} * * Les valeurs "mixed", "bool", "float", "int", "string" et "array" peuvent * aussi être retournées, bien qu'elles ne soient pas à proprement parler des @@ -106,7 +106,7 @@ interface IType { * si la valeur était déjà normalisée, ou si une erreur s'est produite, * retourner false. */ - function verifix(&$value, Result $result, Schema $schema): bool; + function normalize(&$value, Result $result, Schema $schema): bool; /** * formatter la valeur pour affichage. si $value n'est pas null, elle est diff --git a/src/schema/types/tarray.php b/src/schema/types/tarray.php index aba2aab..b62160d 100644 --- a/src/schema/types/tarray.php +++ b/src/schema/types/tarray.php @@ -49,7 +49,7 @@ class tarray extends _tstring { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_array($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/tbool.php b/src/schema/types/tbool.php index 50fa206..5e0795d 100644 --- a/src/schema/types/tbool.php +++ b/src/schema/types/tbool.php @@ -99,7 +99,7 @@ class tbool extends _tformatable { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_bool($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/tcallable.php b/src/schema/types/tcallable.php index f9e95d6..af6be72 100644 --- a/src/schema/types/tcallable.php +++ b/src/schema/types/tcallable.php @@ -43,7 +43,7 @@ class tcallable extends _tsimple { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if ($value instanceof func) { $result->setNormalized(); return false; diff --git a/src/schema/types/tcontent.php b/src/schema/types/tcontent.php index 1dfe455..2bb2912 100644 --- a/src/schema/types/tcontent.php +++ b/src/schema/types/tcontent.php @@ -36,7 +36,7 @@ abstract class tcontent extends _tunion { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_string($value) || is_array($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/tfloat.php b/src/schema/types/tfloat.php index db67257..f1befd1 100644 --- a/src/schema/types/tfloat.php +++ b/src/schema/types/tfloat.php @@ -43,7 +43,7 @@ class tfloat extends _tformatable { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_float($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/tgeneric.php b/src/schema/types/tgeneric.php index 16f86a8..492c57e 100644 --- a/src/schema/types/tgeneric.php +++ b/src/schema/types/tgeneric.php @@ -41,7 +41,7 @@ class tgeneric extends _tsimple { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { $result->setNormalized(); return false; } diff --git a/src/schema/types/tint.php b/src/schema/types/tint.php index 5673ab5..d7e95df 100644 --- a/src/schema/types/tint.php +++ b/src/schema/types/tint.php @@ -45,7 +45,7 @@ class tint extends _tformatable { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_int($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/tkey.php b/src/schema/types/tkey.php index 0e00cb3..6f5072e 100644 --- a/src/schema/types/tkey.php +++ b/src/schema/types/tkey.php @@ -36,7 +36,7 @@ class tkey extends _tunion { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_string($value) || is_int($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/tmixed.php b/src/schema/types/tmixed.php index fa525eb..652e51d 100644 --- a/src/schema/types/tmixed.php +++ b/src/schema/types/tmixed.php @@ -35,7 +35,7 @@ class tmixed extends _tsimple { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { $result->setNormalized(); return false; } diff --git a/src/schema/types/tpkey.php b/src/schema/types/tpkey.php index 14f2e01..e099051 100644 --- a/src/schema/types/tpkey.php +++ b/src/schema/types/tpkey.php @@ -41,7 +41,7 @@ class tpkey extends _tunion { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_string($value) || is_int($value) || is_array($value)) { $result->setNormalized(); return false; diff --git a/src/schema/types/trawstring.php b/src/schema/types/trawstring.php index 4278008..1f09dab 100644 --- a/src/schema/types/trawstring.php +++ b/src/schema/types/trawstring.php @@ -44,7 +44,7 @@ class trawstring extends _tstring { * @var ScalarResult $result * @var ScalarSchema $schema */ - function verifix(&$value, Result $result, Schema $schema): bool { + function normalize(&$value, Result $result, Schema $schema): bool { if (is_string($value)) { $result->setNormalized(); return false; diff --git a/tests/wip/schema/_assoc/AssocSchemaTest.php b/tests/wip/schema/_assoc/AssocSchemaTest.php index 0ab3763..987e845 100644 --- a/tests/wip/schema/_assoc/AssocSchemaTest.php +++ b/tests/wip/schema/_assoc/AssocSchemaTest.php @@ -120,20 +120,36 @@ class AssocSchemaTest extends TestCase { "c" => "bool", ]); + $array = ["a" => " string "]; + $schema->getWrapper($array); + self::assertSame([ + "a" => "string", + "b" => false, + "c" => null, + ], $array); + $array = ["c" => false, "a" => " string "]; $schema->getWrapper($array); self::assertSame([ "a" => "string", - "b" => null, + "b" => false, "c" => false, ], $array); + $array = ["a" => " string "]; + $schema->getWrapper($array, null, ["ensure_order" => false]); + self::assertSame([ + "a" => "string", + "b" => false, + "c" => null, + ], $array); + $array = ["c" => false, "a" => " string "]; $schema->getWrapper($array, null, ["ensure_order" => false]); self::assertSame([ "c" => false, "a" => "string", - "b" => null, + "b" => false, ], $array); $array = ["a" => " string "]; @@ -141,5 +157,12 @@ class AssocSchemaTest extends TestCase { self::assertSame([ "a" => "string", ], $array); + + $array = ["c" => false, "a" => " string "]; + $schema->getWrapper($array, null, ["ensure_keys" => false]); + self::assertSame([ + "a" => "string", + "c" => false, + ], $array); } } From fd9b3b29bc1f3f6de7f669bff9b19549dd71d38f Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Thu, 20 Mar 2025 08:41:31 +0400 Subject: [PATCH 20/27] modifs.mineures sans commentaires --- src/schema/TODO.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 5dce1ef..10c9c00 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -1,6 +1,10 @@ # nulib\schema * ensureKeys() et orderKeys() se fait au niveau de access (ou input?) + * access/input ne pouvant pas connaître les valeurs appropriées, c'est le + schéma qui les génère. ensureKeys($values) + * méthode ensureAssoc() transforme les clés séquentielles en clés associatives +* l'ordre est ensureAssoc \[--> ensureKeys] \[--> orderKeys] * valeurs composite/computed * analyse / vérification de la valeur complète après calcul du résultat, si From e9f4826a94bbbc81e28a9eb528079659ff3f68a0 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Thu, 20 Mar 2025 09:36:01 +0400 Subject: [PATCH 21/27] modifs.mineures sans commentaires --- src/schema/TODO.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 10c9c00..cab4345 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -4,7 +4,7 @@ * access/input ne pouvant pas connaître les valeurs appropriées, c'est le schéma qui les génère. ensureKeys($values) * méthode ensureAssoc() transforme les clés séquentielles en clés associatives -* l'ordre est ensureAssoc \[--> ensureKeys] \[--> orderKeys] +* l'ordre est `ensureAssoc [--> ensureKeys] [--> orderKeys]` * valeurs composite/computed * analyse / vérification de la valeur complète après calcul du résultat, si @@ -17,6 +17,10 @@ * possibilité de spécifier le format de la date à analyser * ScalarSchema::from_property() +* l'argument $format de AssocWrapper::format() est un tableau associatif + `[$key => $format]` + cela permet de spécifier des format spécifiques pour certains champs + * dans AssocSchema, support `[key_prefix]` qui permet de spécifier un préfixe commun aux champs dans le tableau destination, e.g ~~~php From 741a807420d5bcbaa2305b0b789fb4e75a317812 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Thu, 20 Mar 2025 09:38:01 +0400 Subject: [PATCH 22/27] modifs.mineures sans commentaires --- src/schema/TODO.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/schema/TODO.md b/src/schema/TODO.md index cab4345..6ab55f0 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -19,7 +19,9 @@ * l'argument $format de AssocWrapper::format() est un tableau associatif `[$key => $format]` - cela permet de spécifier des format spécifiques pour certains champs + cela permet de spécifier des format spécifiques pour certains champs. + * cela signifie que la valeur de retour n'est pas string :-( + retourner string|array * dans AssocSchema, support `[key_prefix]` qui permet de spécifier un préfixe commun aux champs dans le tableau destination, e.g From c2ec23be30b8ef6c2624420be46772f7142ad80b Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Thu, 20 Mar 2025 09:57:07 +0400 Subject: [PATCH 23/27] modifs.mineures sans commentaires --- src/schema/types/IType.php | 13 ++++++++----- src/schema/types/tarray.php | 15 +++------------ src/schema/types/tbool.php | 13 ++----------- src/schema/types/tcallable.php | 15 +++------------ src/schema/types/tcontent.php | 11 ++++------- src/schema/types/tfloat.php | 13 ++----------- src/schema/types/tgeneric.php | 6 +++--- src/schema/types/tint.php | 13 ++----------- src/schema/types/tkey.php | 11 ++++------- src/schema/types/tmixed.php | 2 +- src/schema/types/tpkey.php | 11 ++++------- src/schema/types/trawstring.php | 9 +++------ 12 files changed, 39 insertions(+), 93 deletions(-) diff --git a/src/schema/types/IType.php b/src/schema/types/IType.php index 9dbd48a..0fbe948 100644 --- a/src/schema/types/IType.php +++ b/src/schema/types/IType.php @@ -98,13 +98,16 @@ interface IType { function parse(string $value); /** - * analyser, corriger éventuellement et normaliser la valeur - * - * NB: si $value est un string. elle doit avoir déjà été traitée au préalable + * normaliser la valeur. elle *doit* déjà être valide. + * Si $value est un string. elle *doit* avoir déjà été traitée au préalable * par extract() et parse() * - * si la valeur était déjà normalisée, ou si une erreur s'est produite, - * retourner false. + * - si $result indique que la valeur est déjà normalisée, cette méthode ne + * fait rien + * - si la valeur était déjà normalisée, mettre à jour $result pour indiquer + * que la valeur est normalisée et retourner false + * - sinon, retourner true pour indiquer qu'il a fallut normaliser la valeur. + * $result n'est pas modifié */ function normalize(&$value, Result $result, Schema $schema): bool; diff --git a/src/schema/types/tarray.php b/src/schema/types/tarray.php index b62160d..a6b2bf9 100644 --- a/src/schema/types/tarray.php +++ b/src/schema/types/tarray.php @@ -37,7 +37,7 @@ class tarray extends _tstring { function isValid($value, ?bool &$normalized=null): bool { $normalized = is_array($value); - return is_scalar($value) || is_array($value); + return $normalized || is_scalar($value); } function parse(string $value) { @@ -50,22 +50,13 @@ class tarray extends _tstring { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_array($value)) { + if ($result->normalized) { + } elseif (is_array($value)) { $result->setNormalized(); - return false; - } elseif (is_string($value)) { - try { - $value = $this->parse($value); - $result->setValid(); - return true; - } catch (ValueException $e) { - } } elseif (is_scalar($value)) { $value = cl::with($value); - $result->setValid(); return true; } - $result->setInvalid($value, $schema); return false; } diff --git a/src/schema/types/tbool.php b/src/schema/types/tbool.php index 5e0795d..dffa9c4 100644 --- a/src/schema/types/tbool.php +++ b/src/schema/types/tbool.php @@ -100,22 +100,13 @@ class tbool extends _tformatable { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_bool($value)) { + if ($result->normalized) { + } elseif (is_bool($value)) { $result->setNormalized(); - return false; - } elseif (is_string($value)) { - try { - $value = $this->parse($value); - $result->setValid(); - return true; - } catch (ValueException $e) { - } } elseif (is_scalar($value)) { $value = boolval($value); - $result->setValid(); return true; } - $result->setInvalid($value, $schema); return false; } diff --git a/src/schema/types/tcallable.php b/src/schema/types/tcallable.php index af6be72..76e2656 100644 --- a/src/schema/types/tcallable.php +++ b/src/schema/types/tcallable.php @@ -27,7 +27,7 @@ class tcallable extends _tsimple { } function isValid($value, ?bool &$normalized=null): bool { - $normalized = is_callable($value); + $normalized = $value instanceof func; return func::check($value); } @@ -44,22 +44,13 @@ class tcallable extends _tsimple { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if ($value instanceof func) { + if ($result->normalized) { + } elseif ($value instanceof func) { $result->setNormalized(); - return false; } elseif (is_callable($value)) { $value = func::with($value); - $result->setNormalized(); return true; - } elseif (is_string($value)) { - try { - $value = $this->parse($value); - $result->setValid(); - return true; - } catch (ValueException $e) { - } } - $result->setInvalid($value, $schema); return false; } diff --git a/src/schema/types/tcontent.php b/src/schema/types/tcontent.php index 2bb2912..0a600f4 100644 --- a/src/schema/types/tcontent.php +++ b/src/schema/types/tcontent.php @@ -25,7 +25,7 @@ abstract class tcontent extends _tunion { function isValid($value, ?bool &$normalized=null): bool { $normalized = is_string($value) || is_array($value); - return is_scalar($value) || is_array($value); + return $normalized || is_scalar($value); } function parse(string $value) { @@ -37,17 +37,14 @@ abstract class tcontent extends _tunion { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_string($value) || is_array($value)) { + if ($result->normalized) { + } elseif (is_string($value) || is_array($value)) { $result->setNormalized(); - return false; } elseif (is_scalar($value)) { $value = strval($value); - $result->setValid(); return true; - } else { - $result->setInvalid($value, $schema); - return false; } + return false; } function format($value, $format=null): string { diff --git a/src/schema/types/tfloat.php b/src/schema/types/tfloat.php index f1befd1..85767b6 100644 --- a/src/schema/types/tfloat.php +++ b/src/schema/types/tfloat.php @@ -44,22 +44,13 @@ class tfloat extends _tformatable { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_float($value)) { + if ($result->normalized) { + } elseif (is_float($value)) { $result->setNormalized(); - return false; - } elseif (is_string($value)) { - try { - $value = $this->parse($value); - $result->setValid(); - return true; - } catch (ValueException $e) { - } } elseif (is_scalar($value)) { $value = floatval($value); - $result->setValid(); return true; } - $result->setInvalid($value, $schema); return false; } } diff --git a/src/schema/types/tgeneric.php b/src/schema/types/tgeneric.php index 492c57e..fe069b8 100644 --- a/src/schema/types/tgeneric.php +++ b/src/schema/types/tgeneric.php @@ -29,8 +29,8 @@ class tgeneric extends _tsimple { } function isValid($value, ?bool &$normalized=null): bool { - $normalized = true; - return $value instanceof $this->class; + $normalized = $value instanceof $this->class; + return $normalized; } function parse(string $value) { @@ -42,7 +42,7 @@ class tgeneric extends _tsimple { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - $result->setNormalized(); + if (!$result->normalized) $result->setNormalized(); return false; } diff --git a/src/schema/types/tint.php b/src/schema/types/tint.php index d7e95df..eddab99 100644 --- a/src/schema/types/tint.php +++ b/src/schema/types/tint.php @@ -46,22 +46,13 @@ class tint extends _tformatable { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_int($value)) { + if ($result->normalized) { + } elseif (is_int($value)) { $result->setNormalized(); - return false; - } elseif (is_string($value)) { - try { - $value = $this->parse($value); - $result->setValid(); - return true; - } catch (ValueException $e) { - } } elseif (is_scalar($value)) { $value = intval($value); - $result->setValid(); return true; } - $result->setInvalid($value, $schema); return false; } } diff --git a/src/schema/types/tkey.php b/src/schema/types/tkey.php index 6f5072e..f1cca27 100644 --- a/src/schema/types/tkey.php +++ b/src/schema/types/tkey.php @@ -25,7 +25,7 @@ class tkey extends _tunion { function isValid($value, ?bool &$normalized=null): bool { $normalized = is_string($value) || is_int($value); - return is_scalar($value); + return $normalized || is_scalar($value); } function parse(string $value) { @@ -37,17 +37,14 @@ class tkey extends _tunion { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_string($value) || is_int($value)) { + if ($result->normalized) { + } elseif (is_string($value) || is_int($value)) { $result->setNormalized(); - return false; } elseif (is_scalar($value)) { $value = strval($value); - $result->setValid(); return true; - } else { - $result->setInvalid($value, $schema); - return false; } + return false; } function format($value, $format=null): string { diff --git a/src/schema/types/tmixed.php b/src/schema/types/tmixed.php index 652e51d..f549204 100644 --- a/src/schema/types/tmixed.php +++ b/src/schema/types/tmixed.php @@ -36,7 +36,7 @@ class tmixed extends _tsimple { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - $result->setNormalized(); + if (!$result->normalized) $result->setNormalized(); return false; } diff --git a/src/schema/types/tpkey.php b/src/schema/types/tpkey.php index e099051..7b2234b 100644 --- a/src/schema/types/tpkey.php +++ b/src/schema/types/tpkey.php @@ -30,7 +30,7 @@ class tpkey extends _tunion { function isValid($value, ?bool &$normalized=null): bool { $normalized = is_string($value) || is_int($value) || is_array($value); - return is_scalar($value) || is_array($value); + return $normalized || is_scalar($value); } function parse(string $value) { @@ -42,17 +42,14 @@ class tpkey extends _tunion { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_string($value) || is_int($value) || is_array($value)) { + if ($result->normalized) { + } elseif (is_string($value) || is_int($value) || is_array($value)) { $result->setNormalized(); - return false; } elseif (is_scalar($value)) { $value = strval($value); - $result->setValid(); return true; - } else { - $result->setInvalid($value, $schema); - return false; } + return false; } function format($value, $format=null): string { diff --git a/src/schema/types/trawstring.php b/src/schema/types/trawstring.php index 1f09dab..674d430 100644 --- a/src/schema/types/trawstring.php +++ b/src/schema/types/trawstring.php @@ -45,17 +45,14 @@ class trawstring extends _tstring { * @var ScalarSchema $schema */ function normalize(&$value, Result $result, Schema $schema): bool { - if (is_string($value)) { + if ($result->normalized) { + } elseif (is_string($value)) { $result->setNormalized(); - return false; } elseif (is_scalar($value)) { $value = strval($value); - $result->setValid(); return true; - } else { - $result->setInvalid($value, $schema); - return false; } + return false; } function format($value, $format=null): string { From e2bec38540bacb483657dccd19d1a489747ae347 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Fri, 21 Mar 2025 07:45:22 +0400 Subject: [PATCH 24/27] modifs.mineures sans commentaires --- src/schema/TODO.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/schema/TODO.md b/src/schema/TODO.md index 6ab55f0..8da8c24 100644 --- a/src/schema/TODO.md +++ b/src/schema/TODO.md @@ -6,6 +6,10 @@ * méthode ensureAssoc() transforme les clés séquentielles en clés associatives * l'ordre est `ensureAssoc [--> ensureKeys] [--> orderKeys]` +* rajouter l'attribut "size" pour spécifier la taille maximale des valeurs + * cela pourrait servir pour générer automatiquement des tables SQL + * ou pour modéliser un schéma FSV + * valeurs composite/computed * analyse / vérification de la valeur complète après calcul du résultat, si tous les résultats sont bons @@ -66,6 +70,8 @@ la définition de ces "circonstances" est encore à faire: soit un paramètre lors de la définition du schéma, soit un truc magique du genre "toutes les - valeurs séquentielles sont des clés du schéma" + valeurs séquentielles sont des clés du schéma", soit un mode automatique + activé par un paramètre où une valeur "val" devient "val"=>true si la clé + "val" existe dans le schéma -*- coding: utf-8 mode: markdown -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8:noeol:binary \ No newline at end of file From 7257654753ad05ecee0e7ea82cadae74e5c983c5 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Sat, 22 Mar 2025 16:42:42 +0400 Subject: [PATCH 25/27] modifs.mineures sans commentaires --- src/php/access/KeyAccess.php | 31 ++++++++++++ tests/wip/php/access/KeyAccessTest.php | 65 ++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) diff --git a/src/php/access/KeyAccess.php b/src/php/access/KeyAccess.php index 38bfee5..79948b2 100644 --- a/src/php/access/KeyAccess.php +++ b/src/php/access/KeyAccess.php @@ -3,6 +3,7 @@ namespace nur\sery\wip\php\access; use ArrayAccess; use nulib\cl; +use nulib\ref\schema\ref_schema; /** * Class KeyAccess: accès @@ -116,4 +117,34 @@ class KeyAccess extends AbstractAccess { "protect_dest" => $this->protectDest, ]); } + + function ensureAssoc(array $keys): void { + $index = 0; + $dest =& $this->dest; + foreach ($keys as $key) { + if ($dest !== null && array_key_exists($key, $dest)) continue; + while (in_array($index, $keys, true)) { + $index++; + } + if ($dest !== null && array_key_exists($index, $dest)) { + $dest[$key] = $dest[$index]; + unset($dest[$index]); + $index++; + } + } + } + + function ensureKeys(array $defaults): void { + $dest =& $this->dest; + $keys = array_keys($defaults); + foreach ($keys as $key) { + if ($dest === null || !array_key_exists($key, $dest)) { + $dest[$key] = $defaults[$key]; + } + } + } + + function ensureOrder(array $keys): void { + $dest =& $this->dest; + } } diff --git a/tests/wip/php/access/KeyAccessTest.php b/tests/wip/php/access/KeyAccessTest.php index d71eb8e..5247d98 100644 --- a/tests/wip/php/access/KeyAccessTest.php +++ b/tests/wip/php/access/KeyAccessTest.php @@ -125,4 +125,69 @@ class KeyAccessTest extends TestCase { self::assertTrue($a->available()); self::assertSame("", $a->get($default)); } + + private function _ensureAssoc(?array $orig, ?array $expected, array $keys) { + $v = $orig; $a = new KeyAccess($v); + $a->ensureAssoc($keys); + self::assertSame($expected, $v); + } + function testEnsureAssoc() { + $keys = ["a", "b", "c"]; + + $this->_ensureAssoc(null, null, $keys); + $this->_ensureAssoc([], [], $keys); + $this->_ensureAssoc([1], ["a" => 1], $keys); + $this->_ensureAssoc([1, 2, 3], ["a" => 1, "b" => 2, "c" => 3], $keys); + $this->_ensureAssoc([1, 2, 3, 4], [3 => 4, "a" => 1, "b" => 2, "c" => 3], $keys); + $this->_ensureAssoc(["c" => 3, 1], ["c" => 3, "a" => 1], $keys); + $this->_ensureAssoc(["c" => 3, "b" => 2, 1], ["c" => 3, "b" => 2, "a" => 1], $keys); + $this->_ensureAssoc(["c" => 3, "b" => 2, "a" => 1], ["c" => 3, "b" => 2, "a" => 1], $keys); + $this->_ensureAssoc(["a" => 1, 2], ["a" => 1, "b" => 2], $keys); + $this->_ensureAssoc([2, "a" => 1], ["a" => 1, "b" => 2], $keys); + + $keys = [0, "a", "b"]; + $this->_ensureAssoc([1], [1], $keys); + $this->_ensureAssoc([1, 2], [1, "a" => 2], $keys); + } + + private function _ensureKeys(?array $orig, ?array $expected, array $defaults) { + $v = $orig; $a = new KeyAccess($v); + $a->ensureKeys($defaults); + self::assertSame($expected, $v); + } + function testEnsureKeys() { + $defaults = ["a" => false, "b" => false, "c" => false]; + + $this->_ensureKeys(null, ["a" => false, "b" => false, "c" => false], $defaults); + $this->_ensureKeys([], ["a" => false, "b" => false, "c" => false], $defaults); + $this->_ensureKeys(["a" => 1], ["a" => 1, "b" => false, "c" => false], $defaults); + $this->_ensureKeys(["a" => 1, "b" => 2, "c" => 3], ["a" => 1, "b" => 2, "c" => 3], $defaults); + $this->_ensureKeys(["x"], ["x", "a" => false, "b" => false, "c" => false], $defaults); + $this->_ensureKeys(["x", "a" => 1], ["x", "a" => 1, "b" => false, "c" => false], $defaults); + $this->_ensureKeys(["a" => 1, "x"], ["a" => 1, "x", "b" => false, "c" => false], $defaults); + $this->_ensureKeys(["a" => 1, "b" => 2, "c" => 3, "x"], ["a" => 1, "b" => 2, "c" => 3, "x"], $defaults); + } + + private function _ensureAssocKeysOrder(?array $orig, ?array $expected, array $defaults) { + $v = $orig; $a = new KeyAccess($v); + $keys = array_keys($defaults); + $a->ensureAssoc($keys); + $a->ensureKeys($defaults); + $a->ensureOrder($keys); + self::assertSame($expected, $v); + } + function testEnsureAssocKeysOrder() { + $defaults = ["a" => false, "b" => false, "c" => false]; + + $this->_ensureAssocKeysOrder(null, ["a" => false, "b" => false, "c" => false], $defaults); + $this->_ensureAssocKeysOrder([], ["a" => false, "b" => false, "c" => false], $defaults); + $this->_ensureAssocKeysOrder([1], ["a" => 1, "b" => false, "c" => false], $defaults); + $this->_ensureAssocKeysOrder([1, 2, 3], ["a" => 1, "b" => 2, "c" => 3], $defaults); + $this->_ensureAssocKeysOrder([1, 2, 3, 4], [3 => 4, "a" => 1, "b" => 2, "c" => 3], $defaults); + $this->_ensureAssocKeysOrder(["c" => 3, 1], ["c" => 3, "a" => 1, "b" => false], $defaults); + $this->_ensureAssocKeysOrder(["c" => 3, "b" => 2, 1], ["c" => 3, "b" => 2, "a" => 1], $defaults); + $this->_ensureAssocKeysOrder(["c" => 3, "b" => 2, "a" => 1], ["c" => 3, "b" => 2, "a" => 1], $defaults); + $this->_ensureAssocKeysOrder(["a" => 1, 2], ["a" => 1, "b" => 2, "c" => false], $defaults); + $this->_ensureAssocKeysOrder([2, "a" => 1], ["a" => 1, "b" => 2, "c" => false], $defaults); + } } From 26817d28266716717cdbc98b681cc2e3d34fff96 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Sun, 23 Mar 2025 08:06:40 +0400 Subject: [PATCH 26/27] modifs.mineures sans commentaires --- .pman.yml => .composer.pman.yml | 0 src/php/access/KeyAccess.php | 54 +++++++++++++++++++---- src/php/access/PropertyAccess.php | 59 +++++++++++++++++++++++--- tests/wip/php/access/KeyAccessTest.php | 46 ++++++++++++++------ 4 files changed, 132 insertions(+), 27 deletions(-) rename .pman.yml => .composer.pman.yml (100%) diff --git a/.pman.yml b/.composer.pman.yml similarity index 100% rename from .pman.yml rename to .composer.pman.yml diff --git a/src/php/access/KeyAccess.php b/src/php/access/KeyAccess.php index 79948b2..356d297 100644 --- a/src/php/access/KeyAccess.php +++ b/src/php/access/KeyAccess.php @@ -118,33 +118,71 @@ class KeyAccess extends AbstractAccess { ]); } - function ensureAssoc(array $keys): void { - $index = 0; + function ensureAssoc(array $keys, ?array $params=null): void { $dest =& $this->dest; + $prefix = $params["key_prefix"] ?? null; + $suffix = $params["key_suffix"] ?? null; + $index = 0; foreach ($keys as $key) { - if ($dest !== null && array_key_exists($key, $dest)) continue; + if ($prefix !== null || $suffix !== null) { + $destKey = "$prefix$key$suffix"; + } else { + # préserver les clés numériques + $destKey = $key; + } + if ($dest !== null && array_key_exists($destKey, $dest)) continue; while (in_array($index, $keys, true)) { $index++; } if ($dest !== null && array_key_exists($index, $dest)) { - $dest[$key] = $dest[$index]; + $dest[$destKey] = $dest[$index]; unset($dest[$index]); $index++; } } } - function ensureKeys(array $defaults): void { + function ensureKeys(array $defaults, ?array $params=null): void { $dest =& $this->dest; $keys = array_keys($defaults); + $prefix = $params["key_prefix"] ?? null; + $suffix = $params["key_suffix"] ?? null; foreach ($keys as $key) { - if ($dest === null || !array_key_exists($key, $dest)) { - $dest[$key] = $defaults[$key]; + $destKey = "$prefix$key$suffix"; + if ($dest === null || !array_key_exists($destKey, $dest)) { + $dest[$destKey] = $defaults[$key]; } } } - function ensureOrder(array $keys): void { + function ensureOrder(array $keys, ?array $params=null): void { $dest =& $this->dest; + if ($dest === null) return; + + $prefix = $params["key_prefix"] ?? null; + $suffix = $params["key_suffix"] ?? null; + if ($prefix !== null || $suffix !== null) { + foreach ($keys as &$key) { + $key = "$prefix$key$suffix"; + }; unset($key); + } + + $destKeys = array_keys($dest); + $keyCount = count($keys); + if (array_slice($destKeys, 0, $keyCount) === $keys) { + # si le tableau a déjà les bonnes clés dans le bon ordre, rien à faire + return; + } + + $ordered = []; + foreach ($keys as $key) { + if (array_key_exists($key, $dest)) { + $ordered[$key] = $dest[$key]; + unset($dest[$key]); + } + } + $preserveKeys = $params["preserve_keys"] ?? false; + if ($preserveKeys) $dest = cl::merge2($ordered, $dest); + else $dest = array_merge($ordered, $dest); } } diff --git a/src/php/access/PropertyAccess.php b/src/php/access/PropertyAccess.php index eadf80d..522c9db 100644 --- a/src/php/access/PropertyAccess.php +++ b/src/php/access/PropertyAccess.php @@ -5,7 +5,9 @@ use nulib\StateException; use nulib\str; use ReflectionClass; use ReflectionException; +use ReflectionNamedType; use ReflectionProperty; +use stdClass; class PropertyAccess extends AbstractAccess { const PROTECT_DEST = true; @@ -32,24 +34,32 @@ class PropertyAccess extends AbstractAccess { protected ?ReflectionProperty $property; + private function _getName(string $key): string { + return $this->mapNames? str::us2camel($key): $key; + } private function _setName(?string $name): void { - if ($this->mapNames) $name = str::us2camel($name); + if ($name !== null) $name = $this->_getName($name); $this->name = $name; } - private function _setDest(?object $dest): void { - $this->dest = $dest; + private function _getProperty(?string $name, ?ReflectionClass $class, ?object $object=null): ?ReflectionProperty { $property = null; - $name = $this->name; - if ($dest !== null && $name !== null) { - $class = new ReflectionClass($dest); + if ($class === null && $object !== null) { + $class = new ReflectionClass($object); + } + if ($class !== null && $name !== null) { try { $property = $class->getProperty($name); $property->setAccessible(true); } catch (ReflectionException $e) { } } - $this->property = $property; + return $property; + } + + private function _setDest(?object $dest): void { + $this->dest = $dest; + $this->property = $this->_getProperty($this->name, null, $dest); } function reset(?object $dest, ?string $name=null): self { @@ -135,4 +145,39 @@ class PropertyAccess extends AbstractAccess { if ($key === null) return $this; return new ChainAccess($this, $key); } + + function ensureAssoc(array $keys, ?array $params=null): void { + # NOP + } + + function ensureKeys(array $defaults, ?array $params=null): void { + $dest = $this->dest; + if ($dest === null) { + # comme ne connait pas la classe de l'objet destination, on n'essaie pas + # de le créer + return; + } + $class = new ReflectionClass($dest); + $keys = array_keys($defaults); + $prefix = $params["key_prefix"] ?? null; + $suffix = $params["key_suffix"] ?? null; + foreach ($keys as $key) { + $name = $this->_getName("$prefix$key$suffix"); + $property = $this->_getProperty($name, $class); + if ($property !== null) { + $type = $property->getType(); + if ($type !== null && !$property->isInitialized($dest) && $type->allowsNull()) { + # initialiser avec null au lieu de $defaults[$key] pour respecter le + # type de la propriété + $property->setValue($dest, null); + } + } elseif (!property_exists($dest, $name)) { + $dest->$name = $defaults[$key]; + } + } + } + + function ensureOrder(array $keys, ?array $params=null): void { + # NOP + } } diff --git a/tests/wip/php/access/KeyAccessTest.php b/tests/wip/php/access/KeyAccessTest.php index 5247d98..8911ccd 100644 --- a/tests/wip/php/access/KeyAccessTest.php +++ b/tests/wip/php/access/KeyAccessTest.php @@ -126,9 +126,9 @@ class KeyAccessTest extends TestCase { self::assertSame("", $a->get($default)); } - private function _ensureAssoc(?array $orig, ?array $expected, array $keys) { + private function _ensureAssoc(?array $orig, ?array $expected, array $keys, ?array $params=null) { $v = $orig; $a = new KeyAccess($v); - $a->ensureAssoc($keys); + $a->ensureAssoc($keys, $params); self::assertSame($expected, $v); } function testEnsureAssoc() { @@ -150,9 +150,9 @@ class KeyAccessTest extends TestCase { $this->_ensureAssoc([1, 2], [1, "a" => 2], $keys); } - private function _ensureKeys(?array $orig, ?array $expected, array $defaults) { + private function _ensureKeys(?array $orig, ?array $expected, array $defaults, ?array $params=null) { $v = $orig; $a = new KeyAccess($v); - $a->ensureKeys($defaults); + $a->ensureKeys($defaults, $params); self::assertSame($expected, $v); } function testEnsureKeys() { @@ -168,12 +168,27 @@ class KeyAccessTest extends TestCase { $this->_ensureKeys(["a" => 1, "b" => 2, "c" => 3, "x"], ["a" => 1, "b" => 2, "c" => 3, "x"], $defaults); } - private function _ensureAssocKeysOrder(?array $orig, ?array $expected, array $defaults) { + private function _ensureOrder(?array $orig, ?array $expected, array $keys, ?array $params=null) { + $v = $orig; $a = new KeyAccess($v); + $a->ensureOrder($keys, $params); + self::assertSame($expected, $v); + } + function testEnsureOrder() { + $keys = ["a", "b", "c"]; + + $this->_ensureOrder(null, null, $keys); + $this->_ensureOrder([], [], $keys); + $this->_ensureOrder([1], [1], $keys); + $this->_ensureOrder(["b" => 2, "a" => 1], ["a" => 1, "b" => 2], $keys); + $this->_ensureOrder(["c" => 3, "a" => 1], ["a" => 1, "c" => 3], $keys); + } + + private function _ensureAssocKeysOrder(?array $orig, ?array $expected, array $defaults, ?array $params=null) { $v = $orig; $a = new KeyAccess($v); $keys = array_keys($defaults); - $a->ensureAssoc($keys); - $a->ensureKeys($defaults); - $a->ensureOrder($keys); + $a->ensureAssoc($keys, $params); + $a->ensureKeys($defaults, $params); + $a->ensureOrder($keys, $params); self::assertSame($expected, $v); } function testEnsureAssocKeysOrder() { @@ -183,11 +198,18 @@ class KeyAccessTest extends TestCase { $this->_ensureAssocKeysOrder([], ["a" => false, "b" => false, "c" => false], $defaults); $this->_ensureAssocKeysOrder([1], ["a" => 1, "b" => false, "c" => false], $defaults); $this->_ensureAssocKeysOrder([1, 2, 3], ["a" => 1, "b" => 2, "c" => 3], $defaults); - $this->_ensureAssocKeysOrder([1, 2, 3, 4], [3 => 4, "a" => 1, "b" => 2, "c" => 3], $defaults); - $this->_ensureAssocKeysOrder(["c" => 3, 1], ["c" => 3, "a" => 1, "b" => false], $defaults); - $this->_ensureAssocKeysOrder(["c" => 3, "b" => 2, 1], ["c" => 3, "b" => 2, "a" => 1], $defaults); - $this->_ensureAssocKeysOrder(["c" => 3, "b" => 2, "a" => 1], ["c" => 3, "b" => 2, "a" => 1], $defaults); + $this->_ensureAssocKeysOrder([1, 2, 3, 4], ["a" => 1, "b" => 2, "c" => 3, 4], $defaults); + $this->_ensureAssocKeysOrder([1, 2, 3, 4], ["a" => 1, "b" => 2, "c" => 3, 3 => 4], $defaults, [ + "preserve_keys" => true, + ]); + $this->_ensureAssocKeysOrder(["c" => 3, 1], ["a" => 1, "b" => false, "c" => 3], $defaults); + $this->_ensureAssocKeysOrder(["c" => 3, "b" => 2, 1], ["a" => 1, "b" => 2, "c" => 3], $defaults); + $this->_ensureAssocKeysOrder(["c" => 3, "b" => 2, "a" => 1], ["a" => 1, "b" => 2, "c" => 3], $defaults); $this->_ensureAssocKeysOrder(["a" => 1, 2], ["a" => 1, "b" => 2, "c" => false], $defaults); $this->_ensureAssocKeysOrder([2, "a" => 1], ["a" => 1, "b" => 2, "c" => false], $defaults); + + $this->_ensureAssocKeysOrder([1], ["x_a" => 1, "x_b" => false, "x_c" => false], $defaults, [ + "key_prefix" => "x_", + ]); } } From fd1ebaf6114f005418de0a46c2d6631678647278 Mon Sep 17 00:00:00 2001 From: Jephte Clain Date: Sun, 23 Mar 2025 08:19:20 +0400 Subject: [PATCH 27/27] modifs.mineures sans commentaires --- src/php/access/AbstractAccess.php | 9 +++++++++ src/php/access/ChainAccess.php | 15 +++++++++++++++ src/php/access/IAccess.php | 21 +++++++++++++++++++++ src/php/access/PropertyAccess.php | 8 -------- src/php/access/ShadowAccess.php | 12 ++++++++++++ 5 files changed, 57 insertions(+), 8 deletions(-) diff --git a/src/php/access/AbstractAccess.php b/src/php/access/AbstractAccess.php index 417d2cb..cffb954 100644 --- a/src/php/access/AbstractAccess.php +++ b/src/php/access/AbstractAccess.php @@ -45,4 +45,13 @@ abstract class AbstractAccess implements IAccess { cl::set($array, $key, $value); $this->set($array); } + + function ensureAssoc(array $keys, ?array $params=null): void { + } + + function ensureKeys(array $defaults, ?array $params=null): void { + } + + function ensureOrder(array $keys, ?array $params=null): void { + } } diff --git a/src/php/access/ChainAccess.php b/src/php/access/ChainAccess.php index 299c01d..00529ce 100644 --- a/src/php/access/ChainAccess.php +++ b/src/php/access/ChainAccess.php @@ -164,4 +164,19 @@ class ChainAccess extends AbstractAccess { return new ChainAccess($this, $key); } } + + function ensureAssoc(array $keys, ?array $params=null): void { + #XXX fonction de $accessType? + #$this->access->ensureAssoc($keys, $params); + } + + function ensureKeys(array $defaults, ?array $params=null): void { + #XXX fonction de $accessType? + #$this->access->ensureKeys($defaults, $params); + } + + function ensureOrder(array $keys, ?array $params=null): void { + #XXX fonction de $accessType? + #$this->access->ensureOrder($keys, $params); + } } diff --git a/src/php/access/IAccess.php b/src/php/access/IAccess.php index 7987c4c..a6f9b84 100644 --- a/src/php/access/IAccess.php +++ b/src/php/access/IAccess.php @@ -1,6 +1,8 @@ dest; if ($dest === null) { @@ -176,8 +172,4 @@ class PropertyAccess extends AbstractAccess { } } } - - function ensureOrder(array $keys, ?array $params=null): void { - # NOP - } } diff --git a/src/php/access/ShadowAccess.php b/src/php/access/ShadowAccess.php index e4f1211..bdd12d6 100644 --- a/src/php/access/ShadowAccess.php +++ b/src/php/access/ShadowAccess.php @@ -57,4 +57,16 @@ class ShadowAccess extends AbstractAccess { function addKey($key): IAccess { return new ChainAccess($this, $key); } + + function ensureAssoc(array $keys, ?array $params=null): void { + $this->writer->ensureAssoc($keys, $params); + } + + function ensureKeys(array $defaults, ?array $params=null): void { + $this->writer->ensureKeys($defaults, $params); + } + + function ensureOrder(array $keys, ?array $params=null): void { + $this->writer->ensureOrder($keys, $params); + } }