<?php
namespace nulib\schema\types;

use nulib\schema\_scalar\ScalarSchema;
use nulib\schema\Result;
use nulib\schema\Schema;
use nulib\ValueException;

class tfloat extends _tformatable {
  const NAME = "float";

  const ALIASES = ["flt", "double", "dbl"];

  function getClass(): string {
    return "float";
  }

  function getNullValue() {
    return $this->nullable? null: 0.0;
  }

  function isValid($value, ?bool &$normalized=null): bool {
    $normalized = is_float($value);
    return is_scalar($value);
  }

  function extract(string $value): string {
    return trim($value);
  }

  function parse(string $value) {
    $value = str_replace(",", ".", trim($value));
    if (is_numeric($value)) return floatval($value);
    throw new ValueException("une valeur numérique flottante est attendue");
  }

  /**
   * @var ScalarSchema $schema
   */
  function normalize(&$value, Result $result, Schema $schema): bool {
    if ($result->normalized) {
    } elseif (is_float($value)) {
      $result->setNormalized();
    } elseif (is_scalar($value)) {
      $value = floatval($value);
      return true;
    }
    return false;
  }
}
