<?php
namespace DM\KategorieBundle\Service;
use DM\KategorieBundle\Entity\Kategorie;
use Doctrine\ORM\PersistentCollection;
class CategorySorter
{
const TYPE_NORMAL = 1;
const TYPE_TEMP = 2;
const TYPE_WIN_BACK = 3;
/**
* sort categories by Type and name
*
* @param array $categories
*
* @return array
*/
public function sortCategoriesByTypeAndName(array $categories): array
{
$items = [];
foreach ($categories as $singleCategory) {
$type = self::TYPE_NORMAL;
$nameWithHighlightedHtml = '<b>' . ($singleCategory['knad_nazwa'] ? $singleCategory['knad_nazwa'] . ' > ' : null) . $singleCategory['nazwa'] . '</b>' . ' [' . $singleCategory['id'] . ']';
if ($singleCategory['temp'] === true && mb_strpos($singleCategory['nazwa'], 'win back', null, 'utf-8') !== false) {
$type = self::TYPE_WIN_BACK;
$nameWithHighlightedHtml = ($singleCategory['knad_nazwa'] ? $singleCategory['knad_nazwa'] . ' > ' : null) . $singleCategory['nazwa'] . ' [' . $singleCategory['id'] . ']' . ' <span class="label label-warning">win back</span> ';
} else if ($singleCategory['temp'] === true) {
$type = self::TYPE_TEMP;
$nameWithHighlightedHtml = ($singleCategory['knad_nazwa'] ? $singleCategory['knad_nazwa'] . ' > ' : null) . $singleCategory['nazwa'] . ' [' . $singleCategory['id'] . ']' . ' <span class="label label-info">tymczasowa</span> ';
}
$name = ($singleCategory['knad_nazwa'] ? $singleCategory['knad_nazwa'] . ' > ' : null) . $singleCategory['nazwa'] . ' [' . $singleCategory['id'] . ']';
$items[$singleCategory['id']] = [
'name' => $name,
'nameWithHighlightedHtml' => $nameWithHighlightedHtml . ($singleCategory['zarchiwizowany'] ? ' <span class="label label-danger">zarchiwizowana</span> ' : ''),
'type' => $type,
'id' => $singleCategory['id'],
'archived' => $singleCategory['zarchiwizowany'],
];
}
usort($items, function ($a, $b) {
if ($a['archived'] > $b['archived']) {
return 1;
} elseif ($a['archived'] < $b['archived']) {
return -1;
} else {
if ($a['type'] > $b['type']) {
return 1;
} elseif ($a['type'] < $b['type']) {
return -1;
} else {
return strcmp(mb_strtolower($a['name'], 'UTF-8'), mb_strtolower($b['name'], 'UTF-8'));
}
}
});
return $items;
}
/**
* sort categories collection by type and name to array
*
* @param array $categories
*
* @return array
*/
public function sortCategoriesCollectionByTypeAndNameToArray(PersistentCollection $categories): array
{
$categoriesArray = [];
/** @var Kategorie $category */
foreach ($categories as $category) {
$categoriesArray[] = [
'id' => $category->getId(),
'nazwa' => $category->getNazwa(),
'temp' => $category->getTemp(),
'zarchiwizowany' => $category->getZarchiwizowany(),
'knad_nazwa' => $category->getKategoriaNadrzedna() ? $category->getKategoriaNadrzedna()->getNazwa() : null
];
}
return $this->sortCategoriesByTypeAndName($categoriesArray);
}
}