<?php
namespace nulib\schema\types;

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

class trawstring extends _tstring {
  const NAME = "rawstring";

  static function ensure_string(&$string): void {
    if (!is_string($string)) $string = strval($string);
    if (static::TRIM) $string = trim($string);
    if (static::NORM_NL) $string = str::norm_nl($string);
  }

  static function ensure_nstring(&$string): void {
    if ($string !== null) self::ensure_string($string);
  }

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

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

  function isNull($value): bool {
    return $value === null;
  }

  function isValid($value, ?bool &$normalized=null): bool {
    if (is_string($value)) {
      $normalized = true;
      return true;
    }
    return 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)) {
      $result->setNormalized();
    } elseif (is_scalar($value)) {
      $value = strval($value);
      return true;
    }
    return false;
  }

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