init
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
use Magento\Framework\DataObject\IdentityInterface;
|
||||
|
||||
class Category extends AbstractModel implements IdentityInterface
|
||||
{
|
||||
public const CACHE_TAG = 'esun_image_category';
|
||||
|
||||
protected $_cacheTag = self::CACHE_TAG;
|
||||
protected $_eventPrefix = self::CACHE_TAG;
|
||||
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(\Esun\ImageManager\Model\ResourceModel\Category::class);
|
||||
}
|
||||
|
||||
public function getIdentities(): array
|
||||
{
|
||||
return [self::CACHE_TAG . '_' . (int) $this->getId()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
use Magento\Framework\DataObject\IdentityInterface;
|
||||
|
||||
class Image extends AbstractModel implements IdentityInterface
|
||||
{
|
||||
public const CACHE_TAG = 'esun_image';
|
||||
|
||||
protected $_cacheTag = self::CACHE_TAG;
|
||||
protected $_eventPrefix = self::CACHE_TAG;
|
||||
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(\Esun\ImageManager\Model\ResourceModel\Image::class);
|
||||
}
|
||||
|
||||
public function getIdentities(): array
|
||||
{
|
||||
return [self::CACHE_TAG . '_' . (int) $this->getId()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?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, '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model;
|
||||
|
||||
use Magento\Framework\App\Filesystem\DirectoryList;
|
||||
use Magento\Framework\App\Request\Http;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Filesystem;
|
||||
use Magento\MediaStorage\Model\File\UploaderFactory;
|
||||
|
||||
class MediaUploader
|
||||
{
|
||||
private const MEDIA_DIRECTORY = 'esun/image-manager';
|
||||
private const PNG_SIGNATURE = "\x89PNG\r\n\x1a\n";
|
||||
private const PNG_TEXT_CHUNKS = ['iTXt', 'tEXt', 'zTXt'];
|
||||
|
||||
public function __construct(
|
||||
private readonly UploaderFactory $uploaderFactory,
|
||||
private readonly Filesystem $filesystem,
|
||||
private readonly Http $request
|
||||
) {
|
||||
}
|
||||
|
||||
public function save(string $field): ?string
|
||||
{
|
||||
$file = $this->request->getFiles($field);
|
||||
if (!is_array($file)
|
||||
|| empty($file['tmp_name'])
|
||||
|| (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if ((int) ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
|
||||
throw new LocalizedException(__('The %1 image could not be uploaded.', $field));
|
||||
}
|
||||
|
||||
$this->sanitizePngUpload((string) $file['tmp_name']);
|
||||
|
||||
$relativeDirectory = self::MEDIA_DIRECTORY . '/' . $field . '/' . date('Y/m');
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
$media->create($relativeDirectory);
|
||||
$uploader = $this->uploaderFactory->create(['fileId' => $field]);
|
||||
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif', 'webp']);
|
||||
$uploader->setAllowRenameFiles(true);
|
||||
$uploader->setFilesDispersion(true);
|
||||
$saved = $uploader->save($media->getAbsolutePath($relativeDirectory));
|
||||
if (!is_array($saved) || empty($saved['file'])) {
|
||||
throw new LocalizedException(__('Unable to save the %1 image.', $field));
|
||||
}
|
||||
|
||||
return trim($relativeDirectory . '/' . ltrim((string) $saved['file'], '/'), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip optional PNG text chunks before Magento asks GD to validate the image.
|
||||
*
|
||||
* Some image exporters embed multi-megabyte iTXt payloads in tiny icons.
|
||||
* libpng versions with stricter chunk limits reject those files before GD can
|
||||
* inspect the actual pixels. Text chunks do not affect image rendering, so
|
||||
* rebuilding the PNG without them keeps the original image and CRC-protected
|
||||
* critical chunks intact while avoiding environment-dependent validation.
|
||||
*/
|
||||
public function sanitizePngUpload(string $path): void
|
||||
{
|
||||
if ($path === '' || !is_file($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$source = @fopen($path, 'rb');
|
||||
if ($source === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
$signature = fread($source, 8);
|
||||
if ($signature !== self::PNG_SIGNATURE) {
|
||||
fclose($source);
|
||||
return;
|
||||
}
|
||||
|
||||
$temporary = tempnam(dirname($path), 'esun-png-');
|
||||
if ($temporary === false) {
|
||||
fclose($source);
|
||||
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
|
||||
}
|
||||
|
||||
$target = @fopen($temporary, 'wb');
|
||||
if ($target === false) {
|
||||
fclose($source);
|
||||
@unlink($temporary);
|
||||
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
|
||||
}
|
||||
|
||||
$removedText = false;
|
||||
$hasHeader = false;
|
||||
$hasImageData = false;
|
||||
$hasEnd = false;
|
||||
|
||||
try {
|
||||
$this->writeAll($target, self::PNG_SIGNATURE);
|
||||
while (!feof($source)) {
|
||||
$header = fread($source, 8);
|
||||
if ($header === '') {
|
||||
break;
|
||||
}
|
||||
if (strlen($header) !== 8) {
|
||||
throw new LocalizedException(__('The uploaded PNG image is incomplete.'));
|
||||
}
|
||||
|
||||
$chunk = unpack('Nlength/a4type', $header);
|
||||
$length = (int) ($chunk['length'] ?? -1);
|
||||
$type = (string) ($chunk['type'] ?? '');
|
||||
if ($length < 0 || !preg_match('/^[A-Za-z]{4}$/', $type)) {
|
||||
throw new LocalizedException(__('The uploaded PNG image has an invalid chunk.'));
|
||||
}
|
||||
|
||||
$skip = in_array($type, self::PNG_TEXT_CHUNKS, true);
|
||||
if ($skip) {
|
||||
$this->copyBytes($source, null, $length + 4);
|
||||
$removedText = true;
|
||||
} else {
|
||||
$this->writeAll($target, $header);
|
||||
$this->copyBytes($source, $target, $length + 4);
|
||||
}
|
||||
|
||||
$hasHeader = $hasHeader || $type === 'IHDR';
|
||||
$hasImageData = $hasImageData || $type === 'IDAT';
|
||||
if ($type === 'IEND') {
|
||||
$hasEnd = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$hasHeader || !$hasImageData || !$hasEnd) {
|
||||
throw new LocalizedException(__('The uploaded PNG image is incomplete.'));
|
||||
}
|
||||
|
||||
fclose($source);
|
||||
$source = null;
|
||||
fflush($target);
|
||||
fclose($target);
|
||||
$target = null;
|
||||
|
||||
if ($removedText && !@copy($temporary, $path)) {
|
||||
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
|
||||
}
|
||||
} finally {
|
||||
if (is_resource($source)) {
|
||||
fclose($source);
|
||||
}
|
||||
if (is_resource($target)) {
|
||||
fclose($target);
|
||||
}
|
||||
@unlink($temporary);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param resource $source @param resource|null $target */
|
||||
private function copyBytes($source, $target, int $remaining): void
|
||||
{
|
||||
while ($remaining > 0) {
|
||||
$data = fread($source, min(8192, $remaining));
|
||||
if ($data === false || $data === '') {
|
||||
throw new LocalizedException(__('The uploaded PNG image is incomplete.'));
|
||||
}
|
||||
if ($target !== null) {
|
||||
$this->writeAll($target, $data);
|
||||
}
|
||||
$remaining -= strlen($data);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param resource $target */
|
||||
private function writeAll($target, string $data): void
|
||||
{
|
||||
$offset = 0;
|
||||
$length = strlen($data);
|
||||
while ($offset < $length) {
|
||||
$written = fwrite($target, substr($data, $offset));
|
||||
if ($written === false || $written === 0) {
|
||||
throw new LocalizedException(__('Unable to prepare the PNG image for validation.'));
|
||||
}
|
||||
$offset += $written;
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(string $path): void
|
||||
{
|
||||
$path = ltrim($path, '/');
|
||||
if ($path === '' || !str_starts_with($path, self::MEDIA_DIRECTORY . '/')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$media = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
|
||||
if ($media->isExist($path)) {
|
||||
$media->delete($path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class Category extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_image_category', 'category_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model\ResourceModel\Category;
|
||||
|
||||
use Esun\ImageManager\Model\Category;
|
||||
use Esun\ImageManager\Model\ResourceModel\Category as CategoryResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(Category::class, CategoryResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class Image extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_image', 'image_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model\ResourceModel\Image;
|
||||
|
||||
use Esun\ImageManager\Model\Image;
|
||||
use Esun\ImageManager\Model\ResourceModel\Image as ImageResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(Image::class, ImageResource::class);
|
||||
}
|
||||
|
||||
protected function _initSelect()
|
||||
{
|
||||
parent::_initSelect();
|
||||
$this->getSelect()->joinLeft(
|
||||
['category' => $this->getTable('esun_image_category')],
|
||||
'main_table.category_id = category.category_id',
|
||||
['category_name' => 'name']
|
||||
);
|
||||
$this->addFilterToMap('image_id', 'main_table.image_id');
|
||||
$this->addFilterToMap('title', 'main_table.title');
|
||||
$this->addFilterToMap('category_id', 'main_table.category_id');
|
||||
$this->addFilterToMap('category_name', 'category.name');
|
||||
$this->addFilterToMap('status', 'main_table.status');
|
||||
$this->addFilterToMap('sort_order', 'main_table.sort_order');
|
||||
$this->addFilterToMap('created_at', 'main_table.created_at');
|
||||
$this->addFilterToMap('updated_at', 'main_table.updated_at');
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model\Source;
|
||||
|
||||
use Esun\ImageManager\Model\ResourceModel\Category\CollectionFactory;
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class CategoryOptions implements OptionSourceInterface
|
||||
{
|
||||
public function __construct(private readonly CollectionFactory $collectionFactory)
|
||||
{
|
||||
}
|
||||
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
$options = [];
|
||||
$collection = $this->collectionFactory->create()
|
||||
->setOrder('sort_order', 'ASC')
|
||||
->setOrder('name', 'ASC');
|
||||
foreach ($collection as $category) {
|
||||
$options[] = [
|
||||
'value' => (int) $category->getId(),
|
||||
'label' => (string) $category->getData('name'),
|
||||
];
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\ImageManager\Model\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class StatusOptions implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 1, 'label' => __('Enabled')],
|
||||
['value' => 0, 'label' => __('Disabled')],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user