Files
2026-09-15 10:35:56 +08:00

97 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\ImageManager\Model;
use Esun\ImageManager\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Esun\ImageManager\Model\ResourceModel\Image\CollectionFactory as ImageCollectionFactory;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class ImageProvider
{
public function __construct(
private readonly CategoryCollectionFactory $categoryCollectionFactory,
private readonly ImageCollectionFactory $imageCollectionFactory,
private readonly StoreManagerInterface $storeManager
) {
}
public function getCategory(string $identifier): ?Category
{
$category = $this->categoryCollectionFactory->create()
->addFieldToFilter('identifier', trim($identifier))
->addFieldToFilter('status', 1)
->setPageSize(1)
->getFirstItem();
return $category->getId() ? $category : null;
}
public function getCategoryById(int $categoryId): ?Category
{
if ($categoryId <= 0) {
return null;
}
$category = $this->categoryCollectionFactory->create()
->addFieldToFilter('category_id', $categoryId)
->addFieldToFilter('status', 1)
->setPageSize(1)
->getFirstItem();
return $category->getId() ? $category : null;
}
/**
* @return array<int, array<string, int|string>>
*/
public function getImages(string $categoryIdentifier): array
{
$category = $this->getCategory($categoryIdentifier);
return $category ? $this->getImagesByCategoryId((int) $category->getId()) : [];
}
/**
* @return array<int, array<string, int|string>>
*/
public function getImagesByCategoryId(int $categoryId): array
{
$category = $this->getCategoryById($categoryId);
if (!$category) {
return [];
}
$collection = $this->imageCollectionFactory->create();
$collection->addFieldToFilter('main_table.category_id', (int) $category->getId());
$collection->addFieldToFilter('main_table.status', 1);
$collection->setOrder('main_table.sort_order', 'ASC');
$collection->setOrder('main_table.image_id', 'ASC');
$items = [];
foreach ($collection as $image) {
$items[] = [
'id' => (int) $image->getId(),
'title' => (string) $image->getData('title'),
'description' => (string) $image->getData('description'),
'thumbnail_url' => $this->getMediaUrl((string) $image->getData('thumbnail_path')),
'image_url' => $this->getMediaUrl((string) $image->getData('image_path')),
'icon_url' => $this->getMediaUrl((string) $image->getData('icon_path')),
'link_url' => (string) $image->getData('link_url'),
'sort_order' => (int) $image->getData('sort_order'),
];
}
return $items;
}
private function getMediaUrl(string $path): string
{
if ($path === '') {
return '';
}
return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. ltrim($path, '/');
}
}