<?php
/*
 * Copyright (c) 2023. RTM Business
 *
 * @license proprietary
 * Modified by RTM Business on 16-December-2024 using {@see https://github.com/BrianHenryIE/strauss}.
 */

namespace RtmMailVendor\Dependencies\WordpressModels\ORM;

use RtmMailVendor\Dependencies\Doctrine\Common\EventSubscriber;
use RtmMailVendor\Dependencies\Doctrine\ORM\EntityManagerInterface;
use RtmMailVendor\Dependencies\Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use RtmMailVendor\Dependencies\Doctrine\ORM\Events;
use RtmMailVendor\Dependencies\Doctrine\ORM\Mapping\ClassMetadataInfo;
use RtmMailVendor\Dependencies\Doctrine\ORM\Mapping\MappingException;
use RtmMailVendor\Dependencies\Symfony\Component\DependencyInjection\ContainerInterface;
use RtmMailVendor\Dependencies\WordpressModels\ORM\Entity\AbstractMeta;
use RtmMailVendor\Dependencies\WordpressModels\ORM\EntityListener\MetaListener;

/**
 * Doctrine EventSubscriber for injecting table prefixes for global database and plugin-specific entity-mappings.
 *
 * Entity- and plugin-specific prefixes can be registered using the `doctrine_plugin_entity_table_prefixes` hook.
 */
class MetaListenerSubscriber implements EventSubscriber
{

    public function __construct(private ContainerInterface $container)
    {
    }

    public function getSubscribedEvents()
    {
        return [Events::loadClassMetadata];
    }

    /**
     * Event handler for LoadClassMetadata event.
     *
     * Prefix any table with the self::$mainPrefix property. If the class in the event is a registered plugin entity,
     * prefix the table additionally with the given value from self::$pluginPrefix.
     *
     * @param LoadClassMetadataEventArgs $eventArgs
     * @return void
     * @throws MappingException
     */
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $classMetadata = $eventArgs->getClassMetadata();
        if (!$classMetadata->reflClass->isSubclassOf(AbstractMeta::class)) {
            return;
        }

        // register the entity listener
        $classMetadata->addEntityListener(Events::preFlush, MetaListener::class, 'preFlush');
    }
}
