<?php
declare(strict_types=1);
namespace App\Base\EventSubscriber;
use App\User\Service\UserService;
use Pimcore\Event\AssetEvents;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Log\ApplicationLogger;
use Pimcore\Model\Asset\Folder;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Класс подписчиков на события assets
*/
class AssetSubscriber implements EventSubscriberInterface
{
public function __construct(
protected ContainerBagInterface $params,
protected TranslatorInterface $translator,
private UserService $userService
) {
}
/**
* @return string[]
*/
public static function getSubscribedEvents()
{
return [
AssetEvents::PRE_ADD => 'onPreAdd'
];
}
/**
* @param \Pimcore\Event\Model\AssetEvent $event
* @throws \Exception
*/
public function onPreAdd(AssetEvent $event)
{
$asset = $event->getAsset();
if ($asset->getType() === 'image') {
$streamMeta = stream_get_meta_data($asset->getStream());
[$imageWidth, $imageHeight] = getimagesize($streamMeta['uri']);
if ($imageWidth > $this->params->get('image.max_upload_width') || $imageHeight > $this->params->get(
'image.max_upload__height'
)) {
throw new \Exception($this->translator->trans('Photo size limits exceeded'));
}
}
if (($parent = $asset->getParent()) && $parent->getFilename() == '__tmp') {
$uuid = Uuid::v6()->toRfc4122();
//todo быстрое решение. Подмена пути хранения файла (нужно заменять __tmp)
$type = 'photo';
if (strpos($asset->getFilename(), '/') !== false) {
[$typeFile, $arFilename] = explode('/', $asset->getFilename());
if ($typeFile && $arFilename) {
$asset->setFilename($arFilename);
if (in_array($typeFile, ['album', 'photo', 'cover', 'audio'], true)) {
$type = $typeFile;
}
}
}
$ext = substr(strrchr($asset->getFilename(), '.'), 1);
$baseAssetName = $asset->getFilename();
$asset->setFilename($uuid . '.' . $ext);
//логика записи asset photo сразу пользователю
$user = $this->userService->getUserByToken();
if ($user instanceof UserInterface) {
/** @var \Pimcore\Model\User $user */
$user = $user->getUser();
$photoFolder = Folder::getByPath('/' . $user->getEmail() . '/' . $type . '/');
$asset->setParent($photoFolder);
if ($asset->getType() === 'image') {
$logger = ApplicationLogger::getInstance();
$logger->notice(
'asset_image:onPreAdd::userEmail:' . $user->getEmail() . '_fileName:' . $baseAssetName
);
}
}
}
}
}