Backend service and controller for converting piece categories to component categories (and vice-versa). Uses raw SQL in a transaction to preserve IDs and transfer all related data (documents, custom fields, constructeurs). Includes php-cs-fixer formatting pass on existing controllers/entities. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
78 lines
1.9 KiB
PHP
78 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\EventSubscriber;
|
|
|
|
use App\Entity\Piece;
|
|
use App\Repository\ProductRepository;
|
|
use Doctrine\Common\EventSubscriber;
|
|
use Doctrine\ORM\Event\LifecycleEventArgs;
|
|
use Doctrine\ORM\Event\PreUpdateEventArgs;
|
|
use Doctrine\ORM\Events;
|
|
|
|
/**
|
|
* Keep the legacy single product relation in sync with the new productIds array.
|
|
*/
|
|
final class PieceProductSyncSubscriber implements EventSubscriber
|
|
{
|
|
public function __construct(private readonly ProductRepository $productRepository) {}
|
|
|
|
public function getSubscribedEvents(): array
|
|
{
|
|
return [
|
|
Events::prePersist,
|
|
Events::preUpdate,
|
|
];
|
|
}
|
|
|
|
public function prePersist(LifecycleEventArgs $args): void
|
|
{
|
|
$entity = $args->getObject();
|
|
if (!$entity instanceof Piece) {
|
|
return;
|
|
}
|
|
|
|
$this->syncPrimaryProduct($entity);
|
|
}
|
|
|
|
public function preUpdate(PreUpdateEventArgs $args): void
|
|
{
|
|
$entity = $args->getObject();
|
|
if (!$entity instanceof Piece) {
|
|
return;
|
|
}
|
|
|
|
$this->syncPrimaryProduct($entity);
|
|
|
|
$em = $args->getObjectManager();
|
|
$meta = $em->getClassMetadata(Piece::class);
|
|
$em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $entity);
|
|
}
|
|
|
|
private function syncPrimaryProduct(Piece $piece): void
|
|
{
|
|
$productIds = $piece->getProductIds();
|
|
|
|
if ([] === $productIds) {
|
|
// If no explicit list is provided, keep the legacy relation as-is.
|
|
return;
|
|
}
|
|
|
|
$primaryId = $productIds[0] ?? null;
|
|
if (!$primaryId) {
|
|
$piece->setProduct(null);
|
|
|
|
return;
|
|
}
|
|
|
|
$currentProductId = $piece->getProduct()?->getId();
|
|
if ($currentProductId === $primaryId) {
|
|
return;
|
|
}
|
|
|
|
$primaryProduct = $this->productRepository->find($primaryId);
|
|
$piece->setProduct($primaryProduct);
|
|
}
|
|
}
|