Example #1
0
 public static function setAllowedMethodsHeaders($allowed_methods_arr)
 {
     Assert::assert(is_array($allowed_methods_arr));
     self::setAccessControlAllowOriginHeader();
     header('Access-Control-Allow-Methods: ' . implode(', ', $allowed_methods_arr));
     header('Allow: ' . implode(', ', $allowed_methods_arr));
 }
Example #2
0
 /**
  * Берет из debug_backtrace путь к вызывающему файлу и подключает шаблон относительно этого пути.
  * Это сделано для сокращения путей к шаблонам в коде.
  * @param $template_file string путь к шаблону относительно папки, в которой лежит вызывающий файл. Например: templates/page.tpl.php
  * @param array $variables ассоциативный массив переменных, которые будут переданы в шаблон
  * @return string
  */
 public static function callLocaltemplate($template_file, $variables = array())
 {
     //
     // находим шаблон
     //
     $cb_arr = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
     $caller_obj = array_shift($cb_arr);
     Assert::assert($caller_obj);
     $caller_path = $caller_obj['file'];
     $caller_path_arr = pathinfo($caller_path);
     $caller_dir = $caller_path_arr['dirname'];
     $full_template_path = $caller_dir . DIRECTORY_SEPARATOR . $template_file;
     //
     // вызываем шаблон
     //
     extract($variables, EXTR_SKIP);
     // Extract the variables to a local namespace
     ob_start();
     // Start output buffering
     require $full_template_path;
     // Include the template file
     $contents = ob_get_contents();
     // Get the contents of the buffer
     ob_end_clean();
     // End buffering and discard
     return $contents;
     // Return the contents
 }
Example #3
0
 /**
  * @param $arr
  * @param $path
  * @return mixed
  * @throws \Exception
  */
 public static function getRequiredSubvalue($arr, $path)
 {
     Assert::assert(!empty($path));
     Assert::assert(is_array($arr));
     $value = $arr;
     $parts = explode(".", $path);
     foreach ($parts as $part) {
         if (isset($value[$part])) {
             $value = $value[$part];
         } else {
             throw new \Exception('missing config key: ' . \OLOG\Sanitize::sanitizeTagContent($path));
         }
     }
     return $value;
 }
Example #4
0
 /**
  * @param $class_name string Имя класса.
  * @param $interface_class_name string Имя интерфейса
  * @throws \Exception
  */
 public static function exceptionIfClassNotImplementsInterface($class_name, $interface_class_name)
 {
     Assert::assert(self::classImplementsInterface($class_name, $interface_class_name), 'Class ' . $class_name . ' does not implement interface ' . $interface_class_name);
 }
Example #5
0
 public static function processAction($action_class_name, $cache_seconds_for_headers = 60, $return_action_result_instead_of_exit = false)
 {
     CheckClassInterfaces::exceptionIfClassNotImplementsInterface($action_class_name, InterfaceAction::class);
     $action_obj = null;
     $current_url = Url::getCurrentUrlNoGetForm();
     if (CheckClassInterfaces::classImplementsInterface($action_class_name, InterfaceGetActionObjForUrl::class)) {
         //
         // экшен умеет сам проверять его ли это урл и получать контекст из урла
         //
         $action_obj = $action_class_name::getActionObjForUrl($current_url);
         if (is_null($action_obj)) {
             // экшен не умеет обрабатывать этот урл
             return null;
         }
     } else {
         //
         // экшен не умеет сам проверять его ли это урл и получать контекст из урла
         // поэтому получаем из экшена маску адреса и матчим с запрошенным урлом
         //
         $url_regexp = '';
         if (method_exists($action_class_name, 'urlMask')) {
             $url_regexp = '@^' . $action_class_name::urlMask() . '$@';
         } else {
             // создаем объект экшена без контекста, чтобы получить из него маску адреса через метод url()
             /** @var InterfaceAction $dummy_action_obj */
             $dummy_action_obj = new $action_class_name();
             // url_perfix позволяет работать в папке
             $url_str = self::$url_prefix . $dummy_action_obj->url();
             $url_regexp = '@^' . $url_str . '$@';
         }
         //
         // проверка соответствия запрошенного адреса маске экшена и извлечение параметров экшена
         //
         $matches_arr = array();
         if (!preg_match($url_regexp, $current_url, $matches_arr)) {
             return false;
         }
         if (count($matches_arr)) {
             array_shift($matches_arr);
             // убираем первый элемент массива - содержит всю сматченую строку
         }
         //
         // декодирование параметров экшена, полученных из урла
         //
         $decoded_matches_arr = array();
         foreach ($matches_arr as $arg_value) {
             $decoded_matches_arr[] = urldecode($arg_value);
         }
         //
         // создание объекта экшена и вызов метода action
         //
         //$action_obj = new $action_class_name($decoded_matches_arr);
         $reflect = new \ReflectionClass($action_class_name);
         $action_obj = $reflect->newInstanceArgs($decoded_matches_arr);
     }
     Assert::assert($action_obj);
     //
     // установка хидеров кэширования
     //
     self::cacheHeaders($cache_seconds_for_headers);
     //
     // вызов экшена
     //
     self::$current_action_obj = $action_obj;
     $action_result = $action_obj->action();
     //
     // сбрасываем текущий экшен - он больше не актуален
     //
     self::$current_action_obj = null;
     //
     // проверка результата экшена - нужно ли завершать работу
     //
     if ($action_result === self::CONTINUE_ROUTING) {
         return $action_result;
     }
     if ($return_action_result_instead_of_exit) {
         return $action_result;
     }
     exit;
 }