<?php
/*
 * Copyright (c) 2023. RTM Business
 */

namespace WordpressModels\ORM;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\MappingException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use WordpressModels\ORM\Entity\AbstractMeta;
use 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');
    }
}
