nur-sery/src/schema/values/ScalarValue.php

75 lines
2.1 KiB
PHP
Raw Normal View History

2023-11-09 10:03:35 +04:00
<?php
namespace nur\sery\schema\values;
use nur\sery\schema\types\IType;
class ScalarValue implements IValue {
use TValue;
function __construct(&$value, array $schema, $key=null, bool $verifix=true) {
$this->schema = $schema;
$this->reset($value, $key, $verifix);
}
function isScalar(?ScalarValue &$scalar=null): bool { $scalar = $this; return true; }
function isSeq(?SeqValue &$seq=null): bool { return false; }
function isAssoc(?AssocValue &$assoc=null): bool { return false; }
function get($default=null) {
$key = $this->key;
if ($key === null) return $this->value;
elseif (array_key_exists($key, $this->value)) return $this->value[$key];
else return $default;
}
function set($value): self {
$key = $this->key;
if ($key === null) $this->value = $value;
else $this->value[$key] = $value;
return $this;
}
/** @var IType */
protected $type;
function type(): IType {
if ($this->type === null) $this->type = $this->md()->getType($this->key);
return $this->type;
}
/** @var ?Result résultat de l'analyse de la valeur */
protected $result;
function exists(): bool {
return $this->type()->exists($this->value, $this->key);
}
/**
* analyser, corriger éventuellement et normaliser la valeur
*
* si la valeur était déjà normalisée, retourner false.
*/
function verifix(bool $throw=true, ?Result &$result=null): bool {
$type = $this->type();
$key = $this->key;
if ($key === null) $modified = $type->verifix($this->value, $throw, $result);
else $modified = $type->verifix($this->value[$key], $throw, $result);
$this->result = $result;
return $modified;
}
function parse($value, bool $throw=true, ?Result &$result=null) {
$this->type()->verifix($value, $throw, $result);
$this->set($value);
$this->result = $result;
return $value;
}
function format(?string $format=null): string {
$type = $this->type();
$key = $this->key;
if ($key === null) return $type->format($this->value, $format);
else return $type->format($this->value[$key], $format);
}
}