<?php
namespace ModulesAbstract\ImportedOrdersFileManager\Model\Utils; class FilesystemPaginatorAndSorter { protected $iterator = NULL; protected $internalIterator = NULL; protected $currentPage = NULL; protected $itemsPerPage = NULL; protected $totalNumberOfResults = NULL; protected $orderColumn = NULL; protected $orderDirection = NULL; public function setIterator($iterator) { $this->iterator = $iterator; return $this; } public function setResultsPerPage($count) { $this->itemsPerPage = (int)$count; return $this; } public function getItemsPerPage() { return $this->itemsPerPage; } public function setCurrentPage($page) { $this->currentPage = (int)$page; return $this; } public function getCurrentPage() { return $this->currentPage; } public function getTotalNumberOfResults() { return $this->totalNumberOfResults; } public function hasResults() { return $this->totalNumberOfResults>0; } public function setSortStyle($orderColumn, $orderDirection) { if (!in_array($orderColumn, ['originalName', 'fullName', 'size', 'none', ])) { throw new \Exception("Invalid \$orderColumn in `".get_called_class()."` class."); } if (!in_array($orderDirection, ['ASC', 'DESC' ])) { throw new \Exception("The order by direction can only be ASC or DESC in `".get_called_class()."` class."); } $this->orderColumn = $orderColumn; $this->orderDirection = $orderDirection; return $this; } public function execute() { if ($this->orderColumn && $this->orderColumn!='none' && $this->orderDirection) { $elements = iterator_to_array($this->iterator); $this->totalNumberOfResults = count($elements); $elements = $this->sortList($elements, $this->orderColumn, ($this->orderDirection == 'ASC')); return new \ArrayIterator(array_slice($elements, $this->currentPage * $this->itemsPerPage, $this->itemsPerPage)); } $elements = iterator_to_array($this->iterator); $this->totalNumberOfResults = count($elements); return array_slice($elements, $this->currentPage * $this->itemsPerPage, $this->currentPage * $this->itemsPerPage + $this->itemsPerPage); } protected function sortList($elements, $orderColumn, $orderAscending=true) { usort($elements, function($a, $b) use($orderColumn, $orderAscending) { if ($orderColumn == 'none') { return 0; } if ($orderColumn == 'fullName') { if ($orderAscending) { return strnatcmp($a->getFullName(), $b->getFullName()); } else { return strnatcmp($b->getFullName(), $a->getFullName()); } } if ($orderColumn == 'size') { if ($orderAscending) { return $a->getFilesize() - $b->getFilesize(); } else { return $b->getFilesize() - $a->getFilesize(); } } if ($orderColumn == 'originalName') { $aName = preg_replace("/^[0-9]{8} [0-9]{6} [0-9]{2} [0-9]{2}\.FluX\./", '', $a->getFullName()); $bName = preg_replace("/^[0-9]{8} [0-9]{6} [0-9]{2} [0-9]{2}\.FluX\./", '', $b->getFullName()); if ($orderAscending) { return strnatcmp($aName, $bName); } else { return strnatcmp($bName, $aName); } } }); return $elements; } } 