<?php
namespace nur\sery\wip\schema\types;

use nur\sery\wip\schema\_scalar\ScalarResult;
use nur\sery\wip\schema\_scalar\ScalarSchema;
use nur\sery\wip\schema\Result;
use nur\sery\wip\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 isValid($value, ?bool &$normalized=null): bool {
    $normalized = is_string($value) || is_int($value);
    return is_scalar($value);
  }

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

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

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