prePersist - The prePersist event occurs for a given entity before the respective EntityManager persist operation for that entity is executed. It should be noted that this event is only triggered on initial persist of an entity (i.e. it does not trigger on future updates).
app.listeners.category.save_image_in_listener:
class: App\Listeners\Category\SaveImageInListener
tags:
- name: 'doctrine.orm.entity_listener'
event: 'prePersist'
method: 'save'
entity: App\Entity\CategoryProduct
lazy: true
- name: 'doctrine.orm.entity_listener'
event: 'preUpdate' # не работает
method: 'save'
entity: App\Entity\CategoryProduct
lazy: true
prePersist срабатывает перед инсертом новой сущности в базу.
Задумка в том, что в preUpdate я изменяю старое изображение на новое.
$uow->recomputeSingleEntityChangeSet()
$uow->entityChangeSets
будут лежать данные к изменению = к апдейту /**
* @param CategoryProduct $entity
* @param PreFlushEventArgs $eventArgs
* @return string
*/
public function save(CategoryProduct $entity, PreFlushEventArgs $eventArgs)
{
if ($this->support()) {
foreach ($this->white_mime_list as $mmt => $ext) {
if ($mmt == $this->getMimeType()) {
$file_name = sprintf("%s-%s.%s", md5($this->getImageContentBase64()), uniqid(), $ext);
$relative_path = sprintf("/sale_point_%s/categories/%s", $entity->getSalePoint()->getId(), $file_name);
$absolute_path = sprintf("%s%s", $this->images_directory, $relative_path);
if (!is_dir(dirname($absolute_path))) {
mkdir(dirname($absolute_path), 0777, true);
}
$entity->setImage($relative_path);
$eventArgs->getEntityManager()->getUnitOfWork()->recomputeSingleEntityChangeSet($eventArgs->getEntityManager()->getClassMetadata(CategoryProduct::class), $entity);
@file_put_contents($absolute_path, base64_decode($this->getImageContentBase64()));
}
}
}
}
{
"category_id": "1",
"name": "Бургеры",
"description": "Описание",
"image": {
"mime_type": "image/png",
"content": "iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAYAAAB91L6VAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO3dd5weVb348c8mgYQklFCkRQkI0psNRBRFkCsoRcSOFdsV2733p17Ua0WxUr0KdizXXlCQJqCCgKIoAgIWQgdpCUkgjd3fH2f3xSbu7uyZ58ycmWc+79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bYR1YwfJn+jaUq4BPoDvjpWH+aWADaSmmknoeGTSTVOuBN6Kq9CoPuaXAjaQmmYH4DjCeNncSasfy1JCJ7X9yD8JkPqb+aWADaQmWBN4JfA78ieoLpW/AG/Bvh2qhvmlgA2knNYhvNu9mfzJqMtlIXAi9qJWWuaXAjaQctiCMKb8AfInH8sjZSnwZcJrAKlXrcgvOd/DxO6074zUi82BY4CjCI+dm2YBYTrIGwmLWtwzqozM4fwgIVE9NPw3iwjDoQaA9Yb/bU3C/LgzWHUe6Y2Gy6N5ZArMjarcoZIGgW8ThjPdkDkWtVcr8osJWP1uY+DdwBsJSSm3WwjzLV81XP5CSLwLJvibqswiJOLteWSO6l2BLcn/fVtJmJ/3Q4QfJVIM80uBVjwiUGutDXyUMKdxrseqC4Gzgf8h9PxtyzCctYG9CZOO/IQwBWWuNlwO/C/NvFtXc5lfCthAqsIUwhje26k/WSwhrMZyNGHhkH6aK3lb4LXA9whLt9XdtvcD/wGsUfWOqi+YXwrYQErtqdQ/nOgG=="
}
}
/**
* @param CategoryProduct $entity
* @param PreFlushEventArgs $eventArgs
* @return string
*/
public function save(CategoryProduct $entity, $eventArgs)
{
if ($this->computed === false) {
if ($this->support()) {
foreach ($this->white_mime_list as $mmt => $ext) {
if ($mmt == $this->getMimeType()) {
$file_name = sprintf("%s-%s.%s", md5($this->getImageContentBase64()), uniqid(), $ext);
$relative_path = sprintf("/sale_point_%s/categories/%s", $entity->getSalePoint()->getId(), $file_name);
$absolute_path = sprintf("%s%s", $this->images_directory, $relative_path);
if (!is_dir(dirname($absolute_path))) {
mkdir(dirname($absolute_path), 0777, true);
}
$entity->setImage($relative_path);
$this->computed = true;
$eventArgs->getEntityManager()->getUnitOfWork()->computeChangeSets();
@file_put_contents($absolute_path, base64_decode($this->getImageContentBase64()));
}
}
}
}
}
$eventArgs->getEntityManager()->getUnitOfWork()->computeChangeSets();
Пришлось переработать Так как Это приводит к зацикливанию.
$this->computed = true;
shared by default
. Это значит, что если вам понадобится, чтобы на preFlush() сработал ваш листенер у нескольких сущностей ( вцикле например) или вообще у разных сущностей, то ваш листенер не сработает после первого раза из-за значения $copmuted<?php
namespace App\Listeners\Category;
use App\Entity\CategoryProduct;
use Doctrine\ORM\Event\PreFlushEventArgs;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class SaveImageInListener
* @package App\Listeners\Category
*/
class SaveImageInListener
{
private array $white_mime_list = [
"image/jpeg" => "jpeg",
"image/jpg" => "jpg",
"image/png" => "png",
];
private $images_directory;
/** @var Request|null */
private ?Request $request;
/** @var bool */
private bool $computed;
/**
* SaveImageInListener constructor.
* @param RequestStack $requestStack
* @param $images_directory
*/
public function __construct(RequestStack $requestStack, $images_directory)
{
$this->images_directory = $images_directory;
$this->request = $requestStack->getCurrentRequest();
$this->computed = false;
}
/**
* @param CategoryProduct $entity
* @param PreFlushEventArgs $eventArgs
* @return string
*/
public function save(CategoryProduct $entity, $eventArgs)
{
if ($this->computed === false) {
if ($this->support()) {
foreach ($this->white_mime_list as $mmt => $ext) {
if ($mmt == $this->getMimeType()) {
$file_name = sprintf("%s-%s.%s", md5($this->getImageContentBase64()), uniqid(), $ext);
$relative_path = sprintf("/sale_point_%s/categories/%s", $entity->getSalePoint()->getId(), $file_name);
$absolute_path = sprintf("%s%s", $this->images_directory, $relative_path);
if (!is_dir(dirname($absolute_path))) {
mkdir(dirname($absolute_path), 0777, true);
}
// Удаление предыдущей версии файла, если это обновление
if (is_file($this->images_directory . $entity->getImage()))
@unlink($this->images_directory . $entity->getImage());
$entity->setImage($relative_path);
$this->computed = true;
$eventArgs->getEntityManager()->getUnitOfWork()->computeChangeSets();
@file_put_contents($absolute_path, base64_decode($this->getImageContentBase64()));
}
}
}
}
}
/**
* @return bool
*/
private function support()
{
if ($this->request->get("image", false)) {
return true;
}
return false;
}
/**
* @return mixed
*/
private function getImageContentBase64()
{
$request_image = $this->request->get("image", false);
return $request_image["content"];
}
/**
* @return mixed
*/
private function getMimeType()
{
$request_image = $this->request->get("image", false);
return $request_image["mime_type"];
}
}
...
if ($this->support())
...