<?php
namespace nur\data\types;

class IntType extends AbstractSimpleType {
  const TITLE = "nombre entier";

  private static $instance;
  static final function to_zint($value) {
    $type = self::$instance;
    if ($type === null) self::$instance = $type = new self();
    return $type->with($value);
  }
  static final function to_int($value): int {
    return intval(self::to_zint($value));
  }

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

  function isInstance($value, bool $strict=false): bool {
    return $value === null || is_int($value)
      || (!$strict && (is_float($value) || is_bool($value)));
  }

  function parse(string &$input) {
    if (preg_match('/^-?[0-9]+/', $input, $ms)) {
      $value = $ms[0];
      $input = substr($input, strlen($value));
      return $value;
    }
    return false;
  }

  protected function verifixCheckClass(&$value, $orig, array &$result=null): bool {
    # accepter int, float et true
    if (is_int($value)) $value = self::result_valid($result, $value, $orig);
    elseif (is_float($value)) $value = self::result_valid($result, intval($value), $orig);
    elseif ($value === true) $value = self::result_valid($result, intval($value), $orig);
    else return false;
    return true;
  }

  function verifixConvert(&$value): bool {
    if ($value === null && $this->ppAllowNull) return true;
    $value = intval($value);
    return true;
  }
}
