<?php declare(strict_types=1);
namespace MoorlProductAccessories\Core\Content\Accessory;
use MoorlProductAccessories\Core\Content\Category\CategoryCollection;
use MoorlProductAccessories\Core\Content\Category\CategoryEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
use Shopware\Core\Framework\Uuid\Uuid;
/**
* @method void add(AccessoryEntity $entity)
* @method void set(string $key, AccessoryEntity $entity)
* @method AccessoryEntity[] getIterator()
* @method AccessoryEntity[] getElements()
* @method AccessoryEntity|null get(string $key)
* @method AccessoryEntity|null first()
* @method AccessoryEntity|null last()
*/
class AccessoryCollection extends EntityCollection
{
protected function getExpectedClass(): string
{
return AccessoryEntity::class;
}
public function filterByCategoryId(?string $id = null): self
{
return $this->filter(function (AccessoryEntity $entity) use ($id) {
return ($entity->getCategoryId() === $id && $entity->getAccessory()->getActive() === true);
});
}
public function hasDuplicate(AccessoryEntity $struct): bool
{
foreach ($this->getElements() as $entity) {
if ($entity->getId() === $struct->getId()) {
continue;
}
if ($entity->getAccessoryId() === $struct->getAccessoryId() && $entity->getCategoryId() === $struct->getCategoryId()) {
return true;
}
}
return false;
}
public function removeDuplicates(): void
{
foreach ($this->getElements() as $entity) {
if ($entity->getSwCategoryId() && $this->hasDuplicate($entity)) {
$this->remove($entity->getId());
}
}
}
public function sortByName(): void
{
$this->sort(function (AccessoryEntity $a, AccessoryEntity $b) {
return strnatcasecmp($a->getAccessory()->getTranslated()['name'], $b->getAccessory()->getTranslated()['name']);
});
}
public function getByAccessoryId(string $id): ?AccessoryEntity
{
return $this->filter(function (AccessoryEntity $entity) use ($id) {
return ($entity->getAccessoryId() === $id);
})->first();
}
public function getIdByAccessoryId(string $id): ?string
{
$entity = $this->getByAccessoryId($id);
if (!$entity) {
return null;
}
return $entity->getId();
}
public function getCategories(): CategoryCollection
{
$this->removeDuplicates();
$this->sortByName();
$categories = new CategoryCollection();
foreach ($this->getElements() as $entity) {
if ($entity->getCategoryId() && !$categories->has($entity->getCategoryId())) {
$categories->add($entity->getCategory());
}
}
foreach ($categories as $category) {
$category->setAccessories($this->filterByCategoryId($category->getId()));
}
if ($this->filterByCategoryId()->count() > 0) {
$category = new CategoryEntity();
$category->setSortOrder(999); // is Last
$category->setAccessories($this->filterByCategoryId());
$category->setType('multi');
$category->setId(Uuid::randomHex());
$categories->add($category);
}
$categories->sortByOrder();
return $categories;
}
}