Skip to content
This repository was archived by the owner on Oct 24, 2023. It is now read-only.

Commit ece9d87

Browse files
author
Jens Schulze
committed
feat(CategoryCollection): add getByParent and getRoots to CategoryCollection
1 parent f0caaa1 commit ece9d87

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/Model/Category/CategoryCollection.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,56 @@
1616
class CategoryCollection extends Collection
1717
{
1818
const SLUG = 'slug';
19+
const PARENT = 'parent';
20+
const ID = 'id';
21+
const ROOTS = 'roots';
1922

2023
protected $type = '\Commercetools\Core\Model\Category\Category';
2124

2225
protected function indexRow($offset, $row)
2326
{
2427
if ($row instanceof Category) {
2528
$slugs = $row->getSlug()->toArray();
29+
$parentId = !is_null($row->getParent()) ? $row->getParent()->getId() : null;
30+
$id = $row->getId();
2631
} else {
2732
$slugs = isset($row[static::SLUG]) ? $row[static::SLUG] : [];
33+
$id = isset($row[static::ID]) ? $row[static::ID] : null;
34+
$parentId = isset($row[static::PARENT][static::ID]) ? $row[static::PARENT][static::ID] : null;
2835
}
2936
foreach ($slugs as $locale => $slug) {
3037
$locale = \Locale::canonicalize($locale);
3138
$this->addToIndex(static::SLUG, $offset, $locale . '-' . $slug);
39+
if (is_null($parentId)) {
40+
$this->addToIndex(static::ROOTS, $offset, $id);
41+
} else {
42+
$this->addToIndex(static::PARENT . '-' . $parentId, $offset, $id);
43+
}
3244
}
3345
}
3446

47+
public function getRoots()
48+
{
49+
$elements = [];
50+
foreach ($this->index[static::ROOTS] as $key => $offset) {
51+
$elements[$key] = $this->getAt($offset);
52+
}
53+
return $elements;
54+
}
55+
56+
public function getByParent($parentId)
57+
{
58+
$elements = [];
59+
if (!isset($this->index[static::PARENT . '-' . $parentId])) {
60+
return $elements;
61+
}
62+
63+
foreach ($this->index[static::PARENT . '-' . $parentId] as $key => $offset) {
64+
$elements[$key] = $this->getAt($offset);
65+
}
66+
return $elements;
67+
}
68+
3569
/**
3670
* @param $locale
3771
* @param $slug

0 commit comments

Comments
 (0)