modifs.mineures sans commentaires

This commit is contained in:
Jephté Clain 2025-03-18 17:37:55 +04:00
parent 189c7aba68
commit d148850c12
12 changed files with 223 additions and 220 deletions

View File

@ -80,7 +80,7 @@ abstract class Schema implements ArrayAccess {
# schéma d'un scalaire quelconque), on ne l'autorise pas ici # schéma d'un scalaire quelconque), on ne l'autorise pas ici
throw SchemaException::invalid_schema("definition is required"); 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 { protected static function have_nature(array $definition, ?string &$nature=null): bool {
@ -98,7 +98,7 @@ abstract class Schema implements ArrayAccess {
return false; 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]; if (!is_array($definition)) $definition = [$definition];
# s'assurer que toutes les clés existent avec leur valeur par défaut # s'assurer que toutes les clés existent avec leur valeur par défaut
$index = 0; $index = 0;
@ -192,11 +192,11 @@ abstract class Schema implements ArrayAccess {
switch ($nature[0] ?? null) { switch ($nature[0] ?? null) {
case "assoc": case "assoc":
foreach ($definition["schema"] as $key => &$keydef) { foreach ($definition["schema"] as $key => &$keydef) {
self::_normalize($keydef, $key); self::_normalize_definition($keydef, $key);
}; unset($keydef); }; unset($keydef);
break; break;
case "list": case "list":
self::_normalize($definition["schema"]); self::_normalize_definition($definition["schema"]);
break; break;
} }
} }
@ -285,7 +285,7 @@ abstract class Schema implements ArrayAccess {
abstract protected function newWrapper(): Wrapper; 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 # key & properties

View File

@ -1,5 +1,10 @@
# nulib\schema # 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 * valeurs composite/computed
* analyse / vérification de la valeur complète après calcul du résultat, si * analyse / vérification de la valeur complète après calcul du résultat, si
tous les résultats sont bons tous les résultats sont bons

View File

@ -6,7 +6,9 @@ use IteratorAggregate;
use nulib\php\func; use nulib\php\func;
use nur\sery\wip\schema\_assoc\AssocWrapper; use nur\sery\wip\schema\_assoc\AssocWrapper;
use nur\sery\wip\schema\_list\ListWrapper; 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\_scalar\ScalarWrapper;
use nur\sery\wip\schema\input\Input;
use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\types\IType;
abstract class Wrapper implements ArrayAccess, IteratorAggregate { 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 isList(?ListWrapper &$wrapper=null): bool { return false; }
function isScalar(?ScalarWrapper &$wrapper=null): bool { return false; } function isScalar(?ScalarWrapper &$wrapper=null): bool { return false; }
/** spécifier la valeur destination gérée par cet objet */ protected WrapperContext $context;
abstract function reset(&$value, $valueKey=null, ?bool $verifix=null): self;
/** 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 * 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 * obtenir le résultat de l'analyse de la valeur du wrapper sélectionné
* {@link unset()} *
* 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 */ /** retourner true si la valeur existe */
abstract function isPresent(): bool; function isPresent(): bool {
return $this->context->result->present;
}
/** retourner le type associé à la valeur */ /** retourner le type associé à la valeur */
abstract function getType(): IType; function getType(): IType {
return $this->context->type;
}
/** retourner true si la valeur est disponible */ /** 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 */ /** 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 */ /** 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 */ function get($default=null) {
abstract function set($value): self; $context = $this->context;
if ($context->result->available) return $context->input->get($context->valueKey);
else return $default;
}
/** supprimer la valeur */ function set($value, ?array $params=null): self {
abstract function unset(): 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 { protected function _format(WrapperContext $context, $format=null): string {
$value = $context->input->get($context->valueKey); $value = $context->input->get($context->valueKey);
@ -85,7 +186,9 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate {
} }
/** formatter la valeur pour affichage */ /** formatter la valeur pour affichage */
abstract function format($format=null): string; function format($format=null): string {
return $this->_format($this->context, $format);
}
############################################################################# #############################################################################
# key & properties # key & properties
@ -95,7 +198,7 @@ abstract class Wrapper implements ArrayAccess, IteratorAggregate {
} }
function offsetGet($offset) { function offsetGet($offset) {
return $this->select($offset); return $this->select($offset)->get();
} }
function offsetSet($offset, $value): void { function offsetSet($offset, $value): void {

View File

@ -5,39 +5,44 @@ use nur\sery\wip\schema\input\Input;
use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\types\IType;
class WrapperContext { class WrapperContext {
function __construct(Schema $schema, ?Input $input, $valueKey, ?Result $result, ?array $params) { function __construct(Schema $schema, ?Input $input, $valueKey, ?array $params) {
$this->params = $params; $this->resetParams($params);
$this->verifix = $params["verifix"] ?? true;
$this->throw = $params["throw"] ?? null;
$this->schema = $schema; $this->schema = $schema;
//$this->wrapper = $wrapper;
if ($input !== null) $this->input = $input; if ($input !== null) $this->input = $input;
$this->valueKey = $valueKey; $this->valueKey = $valueKey;
$this->type = null;
if ($result !== null) $this->result = $result;
$this->origValue = null; $this->origValue = null;
$this->value = null; $this->value = null;
$this->type = null;
$this->result = null;
} }
public ?array $params; public ?array $params;
public bool $verifix; public bool $analyze, $analyzed;
public bool $normalize, $normalized;
public ?bool $throw; 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 */ /** schéma de la valeur */
public Schema $schema; public Schema $schema;
/** instance de Wrapper associé à ce contexte */
//public Wrapper $wrapper;
/** source et destination de la valeur */ /** source et destination de la valeur */
public Input $input; public Input $input;
/** @var string|int|null clé de la valeur dans le tableau destination */ /** @var string|int|null clé de la valeur dans le tableau destination */
public $valueKey; 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 */ /** @var mixed */
public $origValue; public $origValue;
/** @var mixed */ /** @var mixed */
public $value; 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;
} }

View File

@ -4,7 +4,6 @@ namespace nur\sery\wip\schema\_assoc;
use nulib\cl; use nulib\cl;
use nulib\ref\schema\ref_schema; use nulib\ref\schema\ref_schema;
use nulib\ValueException; use nulib\ValueException;
use nur\sery\wip\schema\_scalar\ScalarWrapper;
use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\Schema;
use nur\sery\wip\schema\Wrapper; 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 * 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 { static function isa_definition($definition): bool {
if (!is_array($definition)) return false; if (!is_array($definition)) return false;
@ -29,7 +28,7 @@ class AssocSchema extends Schema {
return !cl::have_num_keys($definition); 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 (!is_array($definition)) $definition = [$definition];
if (!self::have_nature($definition)) { if (!self::have_nature($definition)) {
$definition = [ $definition = [
@ -38,7 +37,7 @@ class AssocSchema extends Schema {
"schema" => $definition, "schema" => $definition,
]; ];
} }
self::_normalize($definition, $definitionKey); self::_normalize_definition($definition, $definitionKey);
self::_ensure_nature($definition, "assoc", "array"); self::_ensure_nature($definition, "assoc", "array");
return $definition; return $definition;
} }
@ -46,7 +45,7 @@ class AssocSchema extends Schema {
function __construct($definition=null, $definitionKey=null, bool $normalize=true) { function __construct($definition=null, $definitionKey=null, bool $normalize=true) {
if ($definition === null) $definition = static::SCHEMA; if ($definition === null) $definition = static::SCHEMA;
if ($normalize) { if ($normalize) {
$definition = self::normalize($definition, $definitionKey); $definition = self::normalize_definition($definition, $definitionKey);
$this->_definition = $definition; $this->_definition = $definition;
self::_ensure_type($definition); self::_ensure_type($definition);
self::_ensure_schema_instances($definition); self::_ensure_schema_instances($definition);
@ -81,11 +80,12 @@ class AssocSchema extends Schema {
return new AssocWrapper($this); 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 # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception
# cf le code similaire dans ScalarWrapper::__construct() # cf le code similaire dans ScalarWrapper::__construct()
$verifix = $array !== null || $wrapper !== null; $verifix = $value !== null || $wrapper !== null;
if (!($wrapper instanceof AssocWrapper)) $wrapper = $this->newWrapper(); 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);
} }
} }

View File

@ -10,7 +10,6 @@ use nur\sery\wip\schema\WrapperContext;
class AssocWrapper extends Wrapper { class AssocWrapper extends Wrapper {
function __construct(AssocSchema $schema, &$array=null, $arrayKey=null, ?array $params=null) { function __construct(AssocSchema $schema, &$array=null, $arrayKey=null, ?array $params=null) {
$definitionSchema = $schema->getDefinition()["schema"];
$keys = $schema->getKeys(); $keys = $schema->getKeys();
$keyTypes = []; $keyTypes = [];
$keyWrappers = []; $keyWrappers = [];
@ -18,7 +17,7 @@ class AssocWrapper extends Wrapper {
$keyTypes[$key] = null; $keyTypes[$key] = null;
$keyWrappers[$key] = $schema->getSchema($key)->getWrapper(); $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->arrayResult = new ScalarResult();
$context->keys = $keys; $context->keys = $keys;
$context->keyTypes = $keyTypes; $context->keyTypes = $keyTypes;
@ -41,18 +40,13 @@ class AssocWrapper extends Wrapper {
/** @var AssocWrapperContext */ /** @var AssocWrapperContext */
protected WrapperContext $context; protected WrapperContext $context;
protected function newInput(&$value): Input { function reset(&$array, $arrayKey=null, ?array $params=null): Wrapper {
return new Input($value);
}
function reset(&$array, $arrayKey=null, ?bool $verifix=null): Wrapper {
if ($array instanceof Input) $input = $array; if ($array instanceof Input) $input = $array;
else $input = $this->newInput($array); else $input = $this->newInput($array);
$context = $this->context; $context = $this->context;
$context->input = $input; $context->input = $input;
$context->valueKey = $arrayKey; $context->valueKey = $arrayKey;
$this->analyze(); $this->afterModify($params);
if ($verifix ?? $context->verifix) $this->verifix();
return $this; return $this;
} }
@ -62,72 +56,17 @@ class AssocWrapper extends Wrapper {
/** @param string|int|null $key */ /** @param string|int|null $key */
function select($key=null): Wrapper { function select($key=null): Wrapper {
#XXX il faut que context contiennent les informations pour la clé sélectionnée
if ($key === null) return $this; if ($key === null) return $this;
$wrapper = $this->context->keyWrappers[$key] ?? null; $wrapper = $this->context->keyWrappers[$key] ?? null;
if ($wrapper === null) throw ValueException::invalid_key($key); if ($wrapper === null) throw ValueException::invalid_key($key);
return $wrapper; 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 { function isNormalized(): bool {
return $this->context->result->normalized; 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 ensureKeys(): bool {
} }
function orderKeys(): bool { function orderKeys(): bool {

View File

@ -35,7 +35,7 @@ class ListSchema extends Schema {
"schema" => $definition[0], "schema" => $definition[0],
]; ];
} }
self::_normalize($definition, $definitionKey); self::_normalize_definition($definition, $definitionKey);
self::_ensure_nature($definition, "list", "array"); self::_ensure_nature($definition, "list", "array");
return $definition; return $definition;
} }
@ -71,7 +71,7 @@ class ListSchema extends Schema {
return new ListWrapper($this); 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 # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception
# cf le code similaire dans ScalarWrapper::__construct() # cf le code similaire dans ScalarWrapper::__construct()
$verifix = $value !== null || $wrapper !== null; $verifix = $value !== null || $wrapper !== null;

View File

@ -4,7 +4,6 @@ namespace nur\sery\wip\schema\_scalar;
use nulib\ref\schema\ref_schema; use nulib\ref\schema\ref_schema;
use nulib\ValueException; use nulib\ValueException;
use nur\sery\wip\schema\Schema; use nur\sery\wip\schema\Schema;
use nur\sery\wip\schema\types\IType;
use nur\sery\wip\schema\Wrapper; 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 * 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 { static function isa_definition($definition): bool {
# chaine ou null # chaine ou null
@ -45,8 +44,8 @@ class ScalarSchema extends Schema {
return $haveIndex0 && $count > 1; return $haveIndex0 && $count > 1;
} }
static function normalize($definition, $definitionKey=null): array { static function normalize_definition($definition, $definitionKey=null): array {
self::_normalize($definition, $definitionKey); self::_normalize_definition($definition, $definitionKey);
self::_ensure_nature($definition, "scalar"); self::_ensure_nature($definition, "scalar");
return $definition; return $definition;
} }
@ -54,7 +53,7 @@ class ScalarSchema extends Schema {
function __construct($definition=null, $definitionKey=null, bool $normalize=true) { function __construct($definition=null, $definitionKey=null, bool $normalize=true) {
if ($definition === null) $definition = static::SCHEMA; if ($definition === null) $definition = static::SCHEMA;
if ($normalize) { if ($normalize) {
$definition = self::normalize($definition, $definitionKey); $definition = self::normalize_definition($definition, $definitionKey);
$this->_definition = $definition; $this->_definition = $definition;
self::_ensure_type($definition); self::_ensure_type($definition);
self::_ensure_schema_instances($definition); self::_ensure_schema_instances($definition);
@ -82,11 +81,12 @@ class ScalarSchema extends Schema {
return new ScalarWrapper($this); 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 # si pas de valeur ni de wrapper, pas de vérification et donc pas d'exception
# cf le code similaire dans ScalarWrapper::__construct() # cf le code similaire dans ScalarWrapper::__construct()
$verifix = $value !== null || $wrapper !== null; $dontNormalize = $value === null && $wrapper === null;
if (!($wrapper instanceof ScalarWrapper)) $wrapper = $this->newWrapper(); 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);
} }
} }

View File

@ -4,22 +4,31 @@ namespace nur\sery\wip\schema\_scalar;
use nulib\php\func; use nulib\php\func;
use nulib\ref\schema\ref_analyze; use nulib\ref\schema\ref_analyze;
use nulib\ValueException; use nulib\ValueException;
use nur\sery\wip\schema\WrapperContext;
use nur\sery\wip\schema\input\Input; use nur\sery\wip\schema\input\Input;
use nur\sery\wip\schema\types; use nur\sery\wip\schema\types;
use nur\sery\wip\schema\types\IType; use nur\sery\wip\schema\types\IType;
use nur\sery\wip\schema\Wrapper; 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 { class ScalarWrapper extends Wrapper {
function __construct(ScalarSchema $schema, &$value=null, $valueKey=null, ?array $params=null) { 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; # calculer manuellemet throw ici parce que WrapperContext le met à true par
if ($value !== null && $throw === null) { # défaut. on veut pouvoir mettre temporairement throw à false si jamais il
# Si $value est null, ne pas lancer d'exception, parce qu'on considère que # n'est pas spécifié par l'utilisateur
# c'est une initialisation sans conséquences $throw = $params["throw"] ?? null;
$throw = true; # 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; $context->throw = $throw ?? false;
$this->reset($value, $valueKey); $this->reset($value, $valueKey);
$context->throw = $throw ?? true; $context->throw = $throw ?? true;
@ -29,19 +38,13 @@ class ScalarWrapper extends Wrapper {
protected WrapperContext $context; protected WrapperContext $context;
protected function newInput(&$value): Input { function reset(&$value, $valueKey=null, ?array $params=null): Wrapper {
return new Input($value); $context = $this->context;
}
function reset(&$value, $valueKey=null, ?bool $verifix=null): Wrapper {
if ($value instanceof Input) $input = $value; if ($value instanceof Input) $input = $value;
else $input = $this->newInput($value); else $input = $this->newInput($value);
$context = $this->context;
$context->input = $input; $context->input = $input;
$context->valueKey = $valueKey; $context->valueKey = $valueKey;
$context->type = null; $this->afterModify($params);
$this->analyze();
if ($verifix ?? $context->verifix) $this->verifix();
return $this; return $this;
} }
@ -56,7 +59,7 @@ class ScalarWrapper extends Wrapper {
} }
/** analyser la valeur et résoudre son type */ /** analyser la valeur et résoudre son type */
protected function analyze0(): int { protected function _analyze0(): int {
$context = $this->context; $context = $this->context;
/** @var ScalarSchema $schema */ /** @var ScalarSchema $schema */
$schema = $context->schema; $schema = $context->schema;
@ -123,7 +126,7 @@ class ScalarWrapper extends Wrapper {
$type = $firstType; $type = $firstType;
} }
} }
$context->type = $this->type = $type; $context->type = $type;
if (!$type->isAvailable($input, $valueKey)) { if (!$type->isAvailable($input, $valueKey)) {
if ($default !== null) { if ($default !== null) {
@ -148,7 +151,7 @@ class ScalarWrapper extends Wrapper {
} }
} }
protected function analyze(): int { protected function _analyze(?array $params): int {
$context = $this->context; $context = $this->context;
/** @var ScalarSchema $schema */ /** @var ScalarSchema $schema */
$schema = $context->schema; $schema = $context->schema;
@ -156,12 +159,11 @@ class ScalarWrapper extends Wrapper {
$valueKey = $context->valueKey; $valueKey = $context->valueKey;
/** @var ScalarResult $result */ /** @var ScalarResult $result */
$result = $context->result; $result = $context->result;
$result->reset();
/** @var func $analyzerFunc */ /** @var func $analyzerFunc */
$analyzerFunc = $schema->analyzerFunc; $analyzerFunc = $schema->analyzerFunc;
if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context, $this]); if ($analyzerFunc !== null) $what = $analyzerFunc->invoke([$context, $this]);
else $what = $this->analyze0(); else $what = $this->_analyze0();
if ($what !== ref_analyze::STRING) return $what; if ($what !== ref_analyze::STRING) return $what;
$value = $context->value; $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; $context = $this->context;
/** @var ScalarSchema $schema */ /** @var ScalarSchema $schema */
$schema = $context->schema; $schema = $context->schema;
@ -241,59 +243,6 @@ class ScalarWrapper extends Wrapper {
} }
if ($result->valid) $input->set($value, $valueKey); if ($result->valid) $input->set($value, $valueKey);
} }
if (!$result->valid) $result->throw($throw ?? $context->throw);
return $modified; 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);
}
} }

View File

@ -44,7 +44,7 @@ class AssocSchemaTest extends TestCase {
"type" => ["string"], "nullable" => false, "type" => ["string"], "nullable" => false,
"name" => "a", "pkey" => "a", "header" => "a", "name" => "a", "pkey" => "a", "header" => "a",
], ],
]), AssocSchema::normalize(["a" => "string"])); ]), AssocSchema::normalize_definition(["a" => "string"]));
self::assertSame(self::schema([ self::assertSame(self::schema([
"type" => ["array"], "nullable" => true, "type" => ["array"], "nullable" => true,
@ -61,7 +61,7 @@ class AssocSchemaTest extends TestCase {
"type" => ["bool"], "nullable" => false, "type" => ["bool"], "nullable" => false,
"name" => "c", "pkey" => "c", "header" => "c", "name" => "c", "pkey" => "c", "header" => "c",
], ],
]), AssocSchema::normalize([ ]), AssocSchema::normalize_definition([
"a" => "string", "a" => "string",
"b" => "int", "b" => "int",
"c" => "bool", "c" => "bool",

View File

@ -32,33 +32,33 @@ class ScalarSchemaTest extends TestCase {
} }
function testNormalize() { function testNormalize() {
self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize(null)); self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize_definition(null));
self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize([])); self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize_definition([]));
self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize([null])); self::assertSame(self::NULL_SCHEMA, ScalarSchema::normalize_definition([null]));
self::assertException(SchemaException::class, function () { self::assertException(SchemaException::class, function () {
ScalarSchema::normalize([[]]); ScalarSchema::normalize_definition([[]]);
}); });
self::assertException(SchemaException::class, function () { self::assertException(SchemaException::class, function () {
ScalarSchema::normalize([[null]]); ScalarSchema::normalize_definition([[null]]);
}); });
$string = self::schema(["type" => ["string"], "nullable" => false]); $string = self::schema(["type" => ["string"], "nullable" => false]);
self::assertSame($string, ScalarSchema::normalize("string")); self::assertSame($string, ScalarSchema::normalize_definition("string"));
self::assertSame($string, ScalarSchema::normalize(["string"])); self::assertSame($string, ScalarSchema::normalize_definition(["string"]));
$nstring = self::schema(["type" => ["string"]]); $nstring = self::schema(["type" => ["string"]]);
self::assertSame($nstring, ScalarSchema::normalize(["?string"])); self::assertSame($nstring, ScalarSchema::normalize_definition(["?string"]));
self::assertSame($nstring, ScalarSchema::normalize(["?string|null"])); self::assertSame($nstring, ScalarSchema::normalize_definition(["?string|null"]));
self::assertSame($nstring, ScalarSchema::normalize(["string|null"])); self::assertSame($nstring, ScalarSchema::normalize_definition(["string|null"]));
self::assertSame($nstring, ScalarSchema::normalize([["?string", "null"]])); self::assertSame($nstring, ScalarSchema::normalize_definition([["?string", "null"]]));
self::assertSame($nstring, ScalarSchema::normalize([["string", "null"]])); self::assertSame($nstring, ScalarSchema::normalize_definition([["string", "null"]]));
self::assertSame($nstring, ScalarSchema::normalize([["string", null]])); self::assertSame($nstring, ScalarSchema::normalize_definition([["string", null]]));
$key = self::schema(["type" => ["string", "int"], "nullable" => false]); $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]); $nkey = self::schema(["type" => ["string", "int"], "nullable" => true]);
self::assertSame($nkey, ScalarSchema::normalize("?string|int")); self::assertSame($nkey, ScalarSchema::normalize_definition("?string|int"));
self::assertSame($nkey, ScalarSchema::normalize("string|?int")); self::assertSame($nkey, ScalarSchema::normalize_definition("string|?int"));
} }
} }

View File

@ -15,19 +15,21 @@ class ScalarWrapperTest extends TestCase {
self::assertSame($normalized, $wrapper->isNormalized(), "normalized"); 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 = $schema->getWrapper();
$wrapper->resetParams(["normalize" => $normalize]);
if ($inputParams !== null) $input = new Input($orig, $inputParams); if ($inputParams !== null) $input = new Input($orig, $inputParams);
else $input = $orig; else $input = $orig;
$wrapper->reset($input, null, $verifix); $wrapper->reset($input);
$this->checkValue($wrapper, $value, $present, $available, $valid, $normalized); $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(); $wrapper = $schema->getWrapper();
if ($inputParams !== null) $orig = new Input($orig, $inputParams); if ($inputParams !== null) $orig = new Input($orig, $inputParams);
self::assertException($exceptionClass, function() use ($wrapper, &$orig, $verifix) { self::assertException($exceptionClass, function() use ($wrapper, &$orig, $normalize) {
$wrapper->reset($orig, null, $verifix); $wrapper->resetParams(["normalize" => $normalize]);
$wrapper->reset($orig);
}); });
} }