<?php

namespace Mautic\CoreBundle\Test\DoctrineExtensions;

use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

class TablePrefix
{
    /**
     * @var string
     */
    protected $prefix = '';

    /**
     * @param string $prefix
     */
    public function __construct($prefix)
    {
        $this->prefix = (string) $prefix;
    }

    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
    {
        /** @var ClassMetadataInfo $classMetadata */
        $classMetadata = $eventArgs->getClassMetadata();

        if (!$classMetadata->isInheritanceTypeSingleTable() || $classMetadata->getName() === $classMetadata->rootEntityName) {
            $table = $classMetadata->table;

            $this->addPrefixToIndexes($this->prefix, $table, 'indexes');
            $this->addPrefixToIndexes($this->prefix, $table, 'uniqueConstraints');

            $classMetadata->setPrimaryTable($table);
        }
    }

    private function addPrefixToIndexes($prefix, array &$table, $key): void
    {
        if (!isset($table[$key])) {
            return;
        }

        $indexes    = &$table[$key];
        $newIndexes = [];

        foreach ($indexes as $name => $index) {
            $newName              = uniqid($prefix.$name);
            $newIndexes[$newName] = $index;
        }

        $table[$key] = $newIndexes;
    }
}
