* @package WB * @subpackage base */ WBClass::load('WBRest_Serializer'); /** * REST Serializer / Unserializer CSV * * @todo current version works only for output * @version 0.1.0 * @package WB * @subpackage base */ class WBRest_Serializer_Csv extends WBRest_Serializer { /** * format string of server error * * @var string */ protected $errorFrame = "\"status\"\t\"error\" \"code\"\t\"message\" \"%d\"\t\"%s\" "; /** * File Handler * @var resource */ private $filePointer; private $delimiter = "\t"; private $enclosure = '"'; /** * Unserialize Request * * Convert Request body to data array * * @param string $body * @param string name of data element, if any * @return array $data */ public function unserialize($body, $dataElement = 'data') { $body = trim($body); $all = array(); return $this->extractUnserializedElement($all, $dataElement); } /** * Serialize data * * Convert array data for response * * @param array $data * @return string $body */ public function serialize($data) { $this->filePointer = fopen('php://temp/', 'r+'); foreach($data as $k => $v) { $this->put($k, $v); } rewind($this->filePointer); return stream_get_contents($this->filePointer); } /** * Recursive Write as CSV * * @param string * @param string|array */ private function put($key, $value) { if (!is_array($value)) { fputcsv($this->filePointer, array($key, $value), $this->delimiter, $this->enclosure); return; } fputcsv($this->filePointer, array($key), $this->delimiter, $this->enclosure); if (!isset($value[0])) { foreach ($value as $k => $v) { $this->put($k, $v); } return; } fputcsv($this->filePointer, array_keys($value[0]), $this->delimiter, $this->enclosure); foreach($value as $data) { fputcsv($this->filePointer, array_values($data), $this->delimiter, $this->enclosure); } fputcsv($this->filePointer, array(), $this->delimiter, $this->enclosure); } }