<?php
namespace nur\ldap\syntaxes;

use nur\b\date\Datetime;
use nur\data\types\SDatetimeType;

class DateSyntax extends AbstractSyntax {
  function __construct() {
    $this->type = new SDatetimeType();
  }

  /** @var SDatetimeType */
  protected $type;


  function php2ldap($value): ?string {
    $value = $this->type->with($value);
    if ($value === null) return null;
    $datetime = new Datetime($value);
    return $datetime->formatRfc4517();
  }

  function ldap2php(string $value) {
    [$y, $m, $d, $H, $M, $S] = [
      substr($value, 0, 4),
      substr($value, 4, 2),
      substr($value, 6, 2),
      substr($value, 8, 2),
      substr($value, 10, 2),
      substr($value, 12, 2),
    ];
    $datetime = new Datetime(gmmktime($H, $M, $S, $m, $d, $y));
    $value = preg_replace('/ 00:00:00$/', "", $datetime->format());
    return $value;
  }
}
