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

use nulib\str;
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 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 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 ScalarResult $result
   * @var ScalarSchema $schema
   */
  function verifix(&$value, Result $result, Schema $schema): bool {
    if (is_string($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);
  }
}
