<?php
namespace nulib\schema\types;

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

class tint extends _tformatable {
  const NAME = "int";

  const ALIASES = ["integer"];

  //const INT_PATTERN = '/^[-+]?[0-9]+(?:\.[0-9]*)?$/';

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

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

  function isValid($value, ?bool &$normalized=null): bool {
    $normalized = is_int($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 intval($value);
    throw new ValueException("une valeur numérique entière est attendue");
  }

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