From 9bf56c786b91ff613bc0badf779627ed940034a8 Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Thu, 25 Jul 2013 21:48:11 +0300 Subject: [PATCH] add prepend option and index to orderable template. --- ipf/orm/template/listener/orderable.php | 27 ++++++++++++++++--------- ipf/orm/template/orderable.php | 6 +++++- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/ipf/orm/template/listener/orderable.php b/ipf/orm/template/listener/orderable.php index 2ff3372..157f492 100644 --- a/ipf/orm/template/listener/orderable.php +++ b/ipf/orm/template/listener/orderable.php @@ -2,11 +2,12 @@ class IPF_ORM_Template_Listener_Orderable { - private $columnName = 'ord'; + private $columnName, $prepend; - public function __construct($columnName) + public function __construct($columnName, $prepend) { $this->columnName = $columnName; + $this->prepend = $prepend; } public function preInsert(IPF_ORM_Event $event) @@ -22,17 +23,23 @@ class IPF_ORM_Template_Listener_Orderable private function setOrderValue($obj) { $columnName = $this->columnName; - if ($obj->$columnName) + if ($obj->$columnName !== null) return; + if ($this->prepend) { + $f = 'min'; + $d = '-'; + } else { + $f = 'max'; + $d = '+'; + } + $res = IPF_ORM_Query::create() - ->select('max('.$this->columnName.') as x_ord') - ->from(get_class($obj)) - ->execute(); - if (isset($res[0]->x_ord)) - $obj->$columnName = (int)$res[0]->x_ord + 1; - else - $obj->$columnName = 1; + ->select('coalesce('.$f.'('.$this->columnName.') '.$d.' 1, 1) as x_ord') + ->from(get_class($obj)) + ->execute(); + + $obj->$columnName = (int)$res[0]->x_ord; } } diff --git a/ipf/orm/template/orderable.php b/ipf/orm/template/orderable.php index 3270828..3d82df9 100644 --- a/ipf/orm/template/orderable.php +++ b/ipf/orm/template/orderable.php @@ -4,6 +4,7 @@ class IPF_ORM_Template_Orderable extends IPF_ORM_Template { private $columnName = 'ord'; private $exclude = true; + private $prepend = false; public function __construct(array $options=array()) { @@ -12,6 +13,8 @@ class IPF_ORM_Template_Orderable extends IPF_ORM_Template $this->columnName = $options['name']; if (array_key_exists('exclude', $options)) $this->exclude = $options['exclude']; + if (array_key_exists('prepend', $options)) + $this->prepend = $options['prepend']; } } @@ -23,7 +26,8 @@ class IPF_ORM_Template_Orderable extends IPF_ORM_Template public function setTableDefinition() { $this->hasColumn($this->columnName, 'integer', null, array('exclude' => $this->exclude)); - $this->getTable()->listeners['Orderable_'.$this->columnName] = new IPF_ORM_Template_Listener_Orderable($this->columnName); + $this->index($this->getTable()->getOption('tableName') . '_orderable_' . $this->columnName, array('fields' => array($this->columnName))); + $this->getTable()->listeners['Orderable_'.$this->columnName] = new IPF_ORM_Template_Listener_Orderable($this->columnName, $this->prepend); } } -- 2.49.0