/** * Encode the given data in plist format * * @param array $data * resulting data that needs to * be encoded in plist 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 * * @return string encoded string */ public function encode($data, $humanReadable = false) { //require_once 'CFPropertyList.php'; if (!isset(self::$compact)) { self::$compact = !$humanReadable; } /** * * @var CFPropertyList */ $plist = new CFPropertyList(); $td = new CFTypeDetector(); $guessedStructure = $td->toCFType(Object::toArray($data)); $plist->add($guessedStructure); return self::$compact ? $plist->toBinary() : $plist->toXML(true); }
public function encode($data, $humanReadable = false) { $data = Object::toArray($data); $xml = new XMLWriter(); $xml->openMemory(); $xml->startDocument('1.0', $this->charset); if ($humanReadable) { $xml->setIndent(true); $xml->setIndentString(' '); } static::$useNamespaces && isset(static::$namespacedProperties[static::$rootName]) ? $xml->startElementNs(static::$namespacedProperties[static::$rootName], static::$rootName, static::$namepaces[static::$namespacedProperties[static::$rootName]]) : $xml->startElement(static::$rootName); if (static::$useNamespaces) { foreach (static::$namepaces as $prefix => $ns) { if (isset(static::$namespacedProperties[static::$rootName]) && static::$namespacedProperties[static::$rootName] == $prefix) { continue; } $xml->writeAttribute('xmlns:' . $prefix, $ns); } } $this->write($xml, $data, static::$rootName); $xml->endElement(); return $xml->outputMemory(); }
public function decode($data) { $options = 0; if (self::$bigIntAsString) { if (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 4 || PHP_MAJOR_VERSION > 5) { $options |= JSON_BIGINT_AS_STRING; } else { $data = preg_replace('/:\\s*(\\-?\\d+(\\.\\d+)?([e|E][\\-|\\+]\\d+)?)/', ': "$1"', $data); } } $decoded = json_decode($data, $options); if (function_exists('json_last_error')) { switch (json_last_error()) { case JSON_ERROR_NONE: return Object::toArray($decoded); break; case JSON_ERROR_DEPTH: $message = 'maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $message = 'underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $message = 'unexpected control character found'; break; case JSON_ERROR_SYNTAX: $message = 'malformed JSON'; break; case JSON_ERROR_UTF8: $message = 'malformed UTF-8 characters, possibly ' . 'incorrectly encoded'; break; default: $message = 'unknown error'; break; } throw new RestException(400, 'Error parsing JSON, ' . $message); } elseif (strlen($data) && $decoded === null || $decoded === $data) { throw new RestException(400, 'Error parsing JSON'); } return Object::toArray($decoded); }
/** * 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; } }
public function encode($data, $humanReadable = false) { // require_once 'sfyaml.php'; return @Yaml::dump(Object::toArray($data)); }
public function decode($data) { $options = 0; if (self::$bigIntAsString) { if (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 4 || PHP_MAJOR_VERSION > 5) { $options |= JSON_BIGINT_AS_STRING; } else { $data = preg_replace('/:\\s*(\\-?\\d+(\\.\\d+)?([e|E][\\-|\\+]\\d+)?)/', ': "$1"', $data); } } try { $decoded = json_decode($data, $options); $this->handleJsonError(); } catch (\RuntimeException $e) { throw new RestException(400, $e->getMessage()); } if (strlen($data) && $decoded === null || $decoded === $data) { throw new RestException(400, 'Error parsing JSON'); } return Object::toArray($decoded); }
/** * Decode the given data from the csv format * * @param string $data * data sent from client to * the api in the given format. * * @return array associative array of the parsed data */ public function decode($data) { $decoded = array(); if (empty($data)) { return $decoded; } $lines = array_filter(explode(PHP_EOL, $data)); $keys = false; $row = static::getRow(array_shift($lines)); if (is_null(static::$haveHeaders)) { //try to guess with the given data static::$haveHeaders = !count(array_filter($row, 'is_numeric')); } static::$haveHeaders ? $keys = $row : ($decoded[] = $row); while (($row = static::getRow(array_shift($lines), $keys)) !== FALSE) { $decoded[] = $row; } $char = Object::$separatorChar; Object::$separatorChar = false; $decoded = Object::toArray($decoded); Object::$separatorChar = $char; return $decoded; }
/** * Decode the given data stream * * @param string $stream A stream resource with data * sent from client to the api * in the given format. * * @return array associative array of the parsed data */ public function decodeStream($stream) { $decoded = array(); $keys = false; $row = static::getRow(stream_get_line($stream, 0, PHP_EOL)); if (is_null(static::$haveHeaders)) { //try to guess with the given data static::$haveHeaders = !count(array_filter($row, 'is_numeric')); } static::$haveHeaders ? $keys = $row : ($decoded[] = $row); while (($row = static::getRow(stream_get_line($stream, 0, PHP_EOL), $keys)) !== FALSE) { $decoded[] = $row; } $char = Object::$separatorChar; Object::$separatorChar = false; $decoded = Object::toArray($decoded); Object::$separatorChar = $char; return $decoded; }
/** * 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; } }
public function encode($data, $humanReadable = false) { return @Yaml::dump(Object::toArray($data)); }