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

use nulib\php\content\c;
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;

abstract class tcontent extends _tunion {
  const NAME = "content";

  static function ensure_content(&$content): void {
    if ($content === null || $content === false) $content = [];
    elseif (!is_string($content) && !is_array($content)) $content = strval($content);
  }

  static function ensure_ncontent(&$content): void {
    if ($content !== null) self::ensure_content($content);
  }

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

  function isValid($value, ?bool &$normalized=null): bool {
    $normalized = is_string($value) || is_array($value);
    return is_scalar($value) || is_array($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_array($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 c::to_string($value);
  }
}
