1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
<?php
namespace Commercetools\Core\Model\Category;
use Commercetools\Core\Model\Common\Collection;
class CategoryCollection extends Collection
{
const SLUG = 'slug';
const PARENT = 'parent';
const ROOTS = 'roots';
const KEY = 'key';
protected $type = Category::class;
protected function indexRow($offset, $row)
{
if ($row instanceof Category) {
$slugs = $row->getSlug()->toArray();
$parentId = !is_null($row->getParent()) ? $row->getParent()->getId() : null;
$id = $row->getId();
$key = $row->getKey();
} else {
$slugs = isset($row[static::SLUG]) ? $row[static::SLUG] : [];
$id = isset($row[static::ID]) ? $row[static::ID] : null;
$key = isset($row[static::KEY]) ? $row[static::KEY] : null;
$parentId = isset($row[static::PARENT][static::ID]) ? $row[static::PARENT][static::ID] : null;
}
$this->addToIndex(static::ID, $offset, $id);
$this->addToIndex(static::KEY, $offset, $key);
foreach ($slugs as $locale => $slug) {
$locale = \Locale::canonicalize($locale);
$this->addToIndex(static::SLUG, $offset, $locale . '-' . $slug);
if (is_null($parentId)) {
$this->addToIndex(static::ROOTS, $offset, $id);
} else {
$this->addToIndex(static::PARENT . '-' . $parentId, $offset, $id);
}
}
}
public function getById($id)
{
return $this->getBy(static::ID, $id);
}
public function getByKey($key)
{
return $this->getBy(static::KEY, $key);
}
public function getRoots()
{
$elements = [];
foreach ($this->index[static::ROOTS] as $key => $offset) {
$elements[$key] = $this->getAt($offset);
}
return $elements;
}
public function getByParent($parentId)
{
$elements = [];
if (!isset($this->index[static::PARENT . '-' . $parentId])) {
return $elements;
}
foreach ($this->index[static::PARENT . '-' . $parentId] as $key => $offset) {
$elements[$key] = $this->getAt($offset);
}
return $elements;
}
public function getBySlug($slug, $locale)
{
$locale = \Locale::canonicalize($locale);
$category = $this->getBy(static::SLUG, $locale . '-' . $slug);
if ($category instanceof Category) {
return $category;
}
$language = \Locale::getPrimaryLanguage($locale);
return $this->getBy(static::SLUG, $language . '-' . $slug);
}
}