* @license PHP License * @package WB * @subpackage db */ WBClass::load('WBDatasource_Renderer'); /** * Datasource renderer JSON * * @version 1.0.0 * @package WB * @subpackage db */ class WBDatasource_Renderer_JSON extends WBDatasource_Renderer { /** * Configuration parameters */ protected $config = array( 'addbom' => 0 ); /** * temporary file * @var WBFile */ protected $file; /** * current file stream * @var resource */ protected $stream; /** * cleanup * * remove temporary file */ public function __destruct() { if ($this->file) { $this->file->unlink(); } } /** * start rendering * * Open stream to render view */ public function start($view) { $this->config['addbom'] = intval($this->config['addbom']); if ($this->file) { $this->file->unlink(); } $this->file = WBClass::create('WBFile'); $this->file->mkdir('var/tmp'); $this->file->tempnam('json'); } /** * render single item * * The consumer for data source iteratrion * @param array $item */ public function renderItem($item) { $json = json_encode($item); // Append if ($this->stream) { fputs($this->stream, ",\n"); fputs($this->stream, $json); return; } // Init file $this->stream = fopen($this->file->realpath(), 'w'); fputs($this->stream, "[\n"); if ($this->config['addbom']) { fputs($this->stream, "\xEF\xBB\xBF"); } fputs($this->stream, $json); } /** * finish rendering * * Things to do after iterating through datasource */ public function end() { if (!$this->stream) { return; } fputs($this->stream, "\n]\n"); fclose($this->stream); $this->stream = null; } /** * get actual file * * @return WBFile */ public function getFile() { return $this->file; } }