* @license PHP License * @package WB * @subpackage base */ WBClass::load('WBEvent_Handler'); /** * WBEvent_Handler_TableOrderPos * * Add order pos for table record * * @version 0.1.0 * @package Wombat * @subpackage base */ class WBEvent_Handler_TableOrderPos extends WBEvent_Handler { /** * handler config * * - table name of table to update * - column name of column to update * - value new value * - valueindex data index where to load the value from * - key primary key of row to update * - keyindex data index where to achieve the primary key from * * @var array */ protected $config = array( 'table' => '', 'column' => 'orderpos', ); /** * Table access * @var WBDatasource_Table */ private $table; /** * Table access via SQL * @var WBDatasource_SimpleQuery */ private $query; /** * Init order position * * In case * * @param WBEvent $e * @return bool true to continue, false to stop processing * @throws Exception in case of error */ public function process(WBEvent $e) { $table = $this->config['table']; if (empty($this->config['table'])) { $table = $e->get('table'); } if (empty($this->config['column'])) { WBClass::load('WBException_Config'); throw new WBException_Config('Column must not be empty!', 2, __CLASS__); } // if someone just update the order position column, nothing $save = $e->get('save'); if (isset($save[$this->config['column']]) && 0 < $save[$this->config['column']]) { return true; } $this->table = WBClass::create('WBDatasource_Table'); $this->table->switchTranslation(false); $id = $e->get('id'); if (empty($id) || $id == '__new') { WBClass::load('WBException_Argument'); throw new WBException_Argument('Id may not be empty or "__new"', 1, __CLASS__); } // find out, whether orderpos is set $old = $this->table->get($table, $id); if (1 != count($old)) { WBClass::load('WBException_Datasource'); throw new WBException_Datasource('Select by id expected a single row.', 1, __CLASS__); } $old = $old[0]; if (!isset($old[$this->config['column']])) { WBClass::load('WBException_Config'); throw new WBException_Config('Order position column does not exist', 2, __CLASS__); } // order position was already set. if (0 < $old[$this->config['column']]) { return true; } $info = $this->table->getTableInfo($table); $sql = 'SELECT max(%1$s.%2$s) + 1 AS m FROM %1$s'; $sql = sprintf($sql, $info['table'], $this->config['column']); $this->query = WBClass::create('WBDatasource_SimpleQuery'); $value = $this->query->query($sql); if (1 != count($value)) { $value = array(array('m' => $id)); } // update $save = array( $this->config['column'] => $value[0]['m'] ); $this->table->save($table, $id, $save); return true; } } ?>