Last active
April 12, 2017 20:40
-
-
Save bigin/5ef95d33522eac25183d7b1e7acc0172 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$counter = new Counter(1); | |
class Counter | |
{ | |
private $imanager; | |
private $slug; | |
private $catId; | |
private $itemMapper; | |
private $min = 0; | |
public function __construct($catId) | |
{ | |
$this->imanager = imanager(); | |
$this->itemMapper = $this->imanager->getItemMapper(); | |
$this->slug = $this->imanager->sanitizer->pageName(get_page_slug(false)); | |
$this->catId = $catId; | |
} | |
public function getCount($slug = null) | |
{ | |
$slug = (is_null($slug) ? $this->slug : $this->imanager->sanitizer->pageName($slug)); | |
$this->itemMapper->alloc($this->catId); | |
$sItems = $this->itemMapper->getSimpleItems('name='.$slug); | |
if($sItems) $sItem = current($sItems); | |
return (!empty($sItem->total) ? (int)$sItem->total : 0); | |
} | |
public function increment($slug = null) | |
{ | |
$slug = (is_null($slug) ? $this->slug : $this->imanager->sanitizer->pageName($slug)); | |
$this->itemMapper->alloc($this->catId); | |
$this->itemMapper->init($this->catId); | |
$item = $this->itemMapper->getItem('name='.$slug); | |
if(empty($item)) { $item = $this->createItem($slug); } | |
$item->setFieldValue('total', (int)$item->fields->total->value + 1); | |
$item->save(); | |
$this->itemMapper->simplify($item); | |
$this->itemMapper->save(); | |
} | |
public function decrement($slug = null) | |
{ | |
$slug = (is_null($slug) ? $this->slug : $this->imanager->sanitizer->pageName($slug)); | |
$this->itemMapper->alloc($this->catId); | |
$this->itemMapper->init($this->catId); | |
$item = $this->itemMapper->getItem('name='.$slug); | |
if(!empty($item)) | |
{ | |
if((int)$item->fields->total->value <= $this->min) return; | |
$item->setFieldValue('total', (int)$item->fields->total->value - 1); | |
$item->save(); | |
$this->itemMapper->simplify($item); | |
$this->itemMapper->save(); | |
} | |
} | |
public function remove($slug = null) | |
{ | |
$slug = (is_null($slug) ? $this->slug : $this->imanager->sanitizer->pageName($slug)); | |
$this->itemMapper->init($this->catId); | |
$item = $this->itemMapper->getItem('name='.$slug); | |
if(!empty($item)) { return $this->imanager->deleteItem($item->id, $item->categoryid); } | |
} | |
private function createItem($slug) | |
{ | |
$item = new Item($this->catId); | |
$item->name = $slug; | |
$item->setFieldValue('total', 0); | |
$item->active = 1; | |
$item->save(); | |
return $item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment