<?php
namespace nur\sery\ext;

use nur\sery\cl;
use nur\sery\file;
use nur\sery\os\IOException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml as SymfonyYaml;

/**
 * Class yaml: lecture de données yaml
 */
class yaml {
  /**
   * @throws IOException si une erreur de lecture s'est produite
   */
  static final function load($input): array {
    $contents = file::reader($input)->getContents();
    try {
      return cl::with(SymfonyYaml::parse($contents));
    } catch (ParseException $e) {
      $message = "parse error";
      if (is_string($input)) $message .= " while loading $input";
      throw new IOException($message, 0, $e);
    }
  }

  static final function with($data, int $indent=2, int $flags=0): string {
    return SymfonyYaml::dump($data, PHP_INT_MAX, $indent, $flags);
  }

  static final function dump($data, $output=null, int $indent=2, int $flags=0): void {
    file::writer($output)->putContents(self::with($data, $indent, $flags));
  }
}
