<?php
namespace nur\ldap\syntaxes;

use nur\A;
use nur\ldap\LdapAttr;
use nur\ldap\LdapConn;

abstract class AbstractSyntax {
  /** @var LdapConn */
  protected $conn;

  function initConn(LdapConn $conn) {
    $this->conn = $conn;
  }

  function newAttr(string $name, ?array &$values, ?int $flags): LdapAttr {
    return new LdapAttr($name, $values, $this, $flags);
  }

  function getPhpType(): ?string {
    return "string";
  }

  /** @throws SyntaxException si $value est invalide */
  abstract function php2ldap($value): ?string;

  abstract function ldap2php(string $value);

  /** transformer les valeurs d'un attribut LDAP en PHP */
  function fromMultivaluedLdap($values): ?array {
    A::ensure_narray($values);
    if ($values !== null) {
      foreach ($values as &$value) {
        $value = $this->ldap2php($value);
      }; unset($value);
    }
    return A::filter_n($values)?: null;
  }

  /** transformer la valeur d'un attribut LDAP en PHP */
  function fromMonovaluedLdap($value) {
    if (is_array($value)) $value = A::first($value);
    if ($value === null) return null;
    else return $this->ldap2php($value);
  }

  /** transformer une(des) valeur(s) PHP en attribut LDAP */
  function fromPhp($values): ?array {
    A::ensure_narray($values);
    if ($values !== null) {
      foreach ($values as &$value) {
        $value = $this->php2ldap($value);
      }; unset($value);
    }
    return A::filter_n($values)?: null;
  }
}
