<?php
abstract class Action {
  private $error = '';
  public abstract function index();
  protected function getDto() {
    return new Dto();
  }
  protected function checkAccess() {
    session_start();
    if (!isset($_SESSION['LOGIN']) || empty($_SESSION['LOGIN']) || $_SESSION['LOGIN'] != 'OK') {
      exit('400 Bad Request');
    }
  }
  public final function invoke($target) {
    $dto = $this->getDto();
    foreach ($_REQUEST as $key => $val) {
      $dto->$key = $this->escape($val);
    }
    $result = $this->$target();
    $dto = $this->getDto();
    $dto->error = $this->error;
    $response = array();
    foreach (array_keys(get_class_vars(get_class($dto))) as $val) {
      $response[$val] = $dto->$val;
    }
    $result->setResponse($response);
    return $result;
  }
  protected function setError($error) {
    if (empty($this->error)) {
      $this->error = $error;
    } else {
      $this->error .= '<br />' . $error;
    }
  }
  protected function hasError() {
    return !empty($this->error);
  }
  private function escape($request) {
    if (is_array($request)) {
      $ret = array();
      foreach ($request as $key => $val) {
        $ret[$key] = $this->escape($val);
      }
      return $ret;
    } else {
      return htmlspecialchars($request, ENT_QUOTES, 'UTF-8');
    }
  }
}
// EOF.
