Exemple #1
0
 /**
  * Encode the given data in the format
  *
  * @param array   $data                resulting data that needs to
  *                                     be encoded in the given format
  * @param boolean $humanReadable       set to TRUE when restler
  *                                     is not running in production mode.
  *                                     Formatter has to make the encoded
  *                                     output more human readable
  *
  * @throws \Exception
  * @return string encoded string
  */
 public function encode($data, $humanReadable = false)
 {
     if (!is_readable(static::$viewPath)) {
         throw new \Exception('The views directory `' . self::$viewPath . '` should exist with read permission.');
     }
     static::$data['basePath'] = dirname($_SERVER['SCRIPT_NAME']);
     static::$data['baseUrl'] = $this->restler->getBaseUrl();
     static::$data['currentPath'] = $this->restler->url;
     try {
         $exception = $this->restler->exception;
         $success = is_null($exception);
         $error = $success ? null : $exception->getMessage();
         $data = array('response' => static::$convertResponseToArray ? Object::toArray($data) : $data, 'stages' => $this->restler->getEvents(), 'success' => $success, 'error' => $error);
         $info = $data['api'] = $this->restler->apiMethodInfo;
         $metadata = Util::nestedValue($this->restler, 'apiMethodInfo', 'metadata');
         $view = $success ? 'view' : 'errorView';
         $value = false;
         if (static::$parseViewMetadata && isset($metadata[$view])) {
             if (is_array($metadata[$view])) {
                 self::$view = $metadata[$view]['description'];
                 $value = Util::nestedValue($metadata[$view], 'properties', 'value');
             } else {
                 self::$view = $metadata[$view];
             }
         } elseif (!self::$view) {
             $file = static::$viewPath . '/' . $this->restler->url . '.' . static::getViewExtension();
             self::$view = static::$useSmartViews && is_readable($file) ? $this->restler->url : static::$errorView;
         }
         if (isset($metadata['param']) && (!$value || 0 === strpos($value, 'request'))) {
             $params = $metadata['param'];
             foreach ($params as $index => &$param) {
                 $index = intval($index);
                 if (is_numeric($index)) {
                     $param['value'] = $this->restler->apiMethodInfo->parameters[$index];
                 }
             }
             $data['request']['parameters'] = $params;
         }
         if ($value) {
             $data = Util::nestedValue($data, explode('.', $value));
         }
         $data += static::$data;
         if (false === ($i = strrpos(self::$view, '.'))) {
             $template = self::$template;
         } else {
             self::$template = $template = substr(self::$view, $i + 1);
             self::$view = substr(self::$view, 0, $i);
         }
         if (!static::$cacheDirectory) {
             static::$cacheDirectory = Defaults::$cacheDirectory . DIRECTORY_SEPARATOR . $template;
             if (!file_exists(static::$cacheDirectory)) {
                 if (!mkdir(static::$cacheDirectory, 0770, true)) {
                     throw new RestException(500, 'Unable to create cache directory `' . static::$cacheDirectory . '`');
                 }
             }
         }
         if (method_exists($class = get_called_class(), $template)) {
             if ($template == 'blade') {
                 $this->checkDependency('Illuminate\\View\\View');
             } elseif ($template == 'twig') {
                 $this->checkDependency('Twig_Environment');
             } elseif ($template == 'mustache' || $template == 'handlebar') {
                 $this->checkDependency('Mustache_Engine');
             }
             return call_user_func("{$class}::{$template}", $data, $humanReadable);
         }
         throw new RestException(500, "Unsupported template system `{$template}`");
     } catch (Exception $e) {
         static::$parseViewMetadata = false;
         $this->reset();
         throw $e;
     }
 }
 /**
  * Encode the given data in the format
  *
  * @param array   $data                resulting data that needs to
  *                                     be encoded in the given format
  * @param boolean $humanReadable       set to TRUE when restler
  *                                     is not running in production mode.
  *                                     Formatter has to make the encoded
  *                                     output more human readable
  *
  * @throws \Exception
  * @return string encoded string
  */
 public function encode($data, $humanReadable = false)
 {
     try {
         $events = $this->restler->getEvents();
         $data = array_merge(array('response' => Object::toArray($data), 'stages' => $events, 'success' => end($events) != 'message'), static::$data);
         $params = array();
         //print_r($this->restler);
         if (isset($this->restler->apiMethodInfo->metadata)) {
             $info = $data['api'] = $this->restler->apiMethodInfo;
             $metadata = $info->metadata;
             $params = $metadata['param'];
         }
         foreach ($params as $index => &$param) {
             $index = intval($index);
             if (is_numeric($index)) {
                 $param['value'] = $this->restler->apiMethodInfo->parameters[$index];
             }
         }
         $data['request']['parameters'] = $params;
         $inner = null;
         if (!$data['success'] && !is_null(static::$errorView)) {
             self::$view = static::$errorView;
         } elseif (static::$parseViewMetadata && isset($metadata['view'])) {
             if (is_array($metadata['view'])) {
                 self::$view = $metadata['view']['description'];
                 if ($value = Util::nestedValue($metadata['view'], 'properties', 'value')) {
                     $inner = explode('.', $value);
                 }
             } else {
                 self::$view = $metadata['view'];
             }
         }
         if (false === ($i = strpos(self::$view, '.'))) {
             $extension = self::$format;
             self::$view .= '.' . $extension;
         } else {
             $extension = substr(self::$view, $i + 1);
         }
         switch ($extension) {
             case 'php':
                 $view = self::$viewPath . DIRECTORY_SEPARATOR . self::$view;
                 if (!is_readable($view)) {
                     throw new RestException(500, "view file `{$view}` is not readable. Check for file presence and file permissions");
                 }
                 $data = $inner ? Util::nestedValue($data, $inner) : $data;
                 $template = function ($view) use($data) {
                     $_ = function () use($data) {
                         extract($data);
                         $args = func_get_args();
                         $task = array_shift($args);
                         switch ($task) {
                             case 'require':
                             case 'include':
                                 $file = HtmlFormat::$viewPath . DIRECTORY_SEPARATOR . $args[0];
                                 if (is_readable($file)) {
                                     if (isset($args[1]) && ($arrays = Util::nestedValue($data, $args[1]))) {
                                         $str = '';
                                         foreach ($arrays as $arr) {
                                             extract($arr);
                                             $str .= (include $file);
                                         }
                                         return $str;
                                     } else {
                                         return include $file;
                                     }
                                 }
                                 break;
                             case 'if':
                                 if (count($args) < 2) {
                                     $args[1] = '';
                                 }
                                 if (count($args) < 3) {
                                     $args[2] = '';
                                 }
                                 return $args[0] ? $args[1] : $args[2];
                                 break;
                             default:
                                 return call_user_func_array($task, $args);
                         }
                     };
                     extract($data);
                     return @(include $view);
                 };
                 $value = $template($view);
                 if (is_string($value)) {
                     echo $value;
                 }
                 break;
             case 'twig':
                 if (!class_exists('\\Twig_Environment', true)) {
                     throw new RestException(500, 'Twig templates require twig classes to be installed using `composer install`');
                 }
                 $loader = new \Twig_Loader_Filesystem(static::$viewPath);
                 $twig = new \Twig_Environment($loader, array('cache' => Defaults::$cacheDirectory, 'debug' => true));
                 $template = $twig->loadTemplate(self::$view);
                 return $template->render($data);
             case 'handlebar':
             case 'mustache':
                 if (!class_exists('\\Mustache_Engine', true)) {
                     throw new RestException(500, 'Mustache/Handlebar templates require mustache classes to be installed using `composer install`');
                 }
                 $view = self::$viewPath . DIRECTORY_SEPARATOR . self::$view;
                 $m = new \Mustache_Engine();
                 return $m->render(file_get_contents($view), $data);
             default:
                 throw new RestException(500, "Unsupported template system `{$extension}`");
         }
     } catch (Exception $e) {
         static::$parseViewMetadata = false;
         $this->reset();
         throw $e;
     }
 }