<?php
 namespace ModulesAbstract\PluginReports\Report\Model\Builder\ArrayEmulator; class Database implements GeneralInterface { private $dbTableName; private $orderFieldType; private $keyFieldType = 'VARCHAR(50) NOT NULL'; public function __construct($orderFieldType) { if (!$orderFieldType) { throw new \Exception('The database order column type was not set.'); } $this->dbTableName = 'arrayEmulator_'.uniqid(); $this->orderFieldType = $orderFieldType; } public function initialize() { $CFG = \Engine\Loader_Cfg::getInstance()->getGlobal(); $db = \DB::getInstance(); $createTableSQL = "CREATE TEMPORARY TABLE `{$this->dbTableName}` (
			`key` {$this->keyFieldType},
			`data` TEXT NOT NULL ,
			`ordering` {$this->orderFieldType},
			PRIMARY KEY (`key`),
			KEY (`ordering`)
		) ENGINE=InnoDB DEFAULT CHARSET={$CFG['encodings']['dbCharacterSet']} COLLATE={$CFG['encodings']['dbCollation']} ROW_FORMAT=DYNAMIC
		"; if (!$db->Execute($createTableSQL)) { throw new \DBException('Invalid SQL for creating a temporary table.'); } } public function set($key, Array $data, $orderValue) { $db = \DB::getInstance(); $insertDataSQL = "REPLACE INTO `{$this->dbTableName}` (`key`, `data`, `ordering`) VALUES (?, ?, ?)"; $insertDataEx = $db->Execute($insertDataSQL, [$key, serialize($data), $orderValue]); if (!$insertDataEx) { throw new \DBException('Could not insert data into temporary table.'); } } public function get($key) { $db = \DB::getInstance(); $getDataSQL = "SELECT data FROM `{$this->dbTableName}` WHERE `key`=?"; $getData = $db->GetRow($getDataSQL, [$key]); if (!is_array($getData)) { throw new \DBException('Could not insert data into temporary table.'); } return unserialize((string)$getData['data']); } public function getAllOrdered($direction = 'ASC') { if ($direction!='ASC' and $direction!='DESC') { throw new \Exception("Invalid direction - you can only set ASC/DESC. `{$direction}` was set."); } $db = \DB::getInstance(); $getDataSQL = "SELECT data FROM `{$this->dbTableName}` ORDER BY `ordering` {$direction}"; foreach($db->Execute($getDataSQL) as $row) { yield unserialize($row['data']); } } public function destroy() { $db = \DB::getInstance(); $dropTblSQL = "DROP TEMPORARY TABLE `{$this->dbTableName}`"; $dropTblEx = $db->Execute($dropTblSQL); if (!$dropTblEx) { throw new \DBException('Could not drop temporary table.'); } } }