<?php
namespace nulib\schema\types;

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

class tkey extends _tunion {
  const NAME = "key";

  static function ensure_key(&$key): void {
    if ($key === null) $key = "";
    elseif ($key === false) $key = 0;
    elseif (!is_string($key) && !is_int($key)) $key = strval($key);
  }

  static function ensure_nkey(&$key): void {
    if ($key !== null) self::ensure_key($key);
  }

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

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

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

  function parse(string $value) {
    return $value;
  }

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

  function format($value, $format=null): string {
    return strval($value);
  }
}
