1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| <?php
namespace App\Event;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
class TablePrefixEventListener implements EventSubscriber
{
/**
* @var array
*/
protected $config;
/**
* @param array $config
*/
public function setConfig(array $config)
{
$this->config = $config;
}
/**
* @param LoadClassMetadataEventArgs $eventArgs
*
* @return void
*/
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
{
$classMetadata = $eventArgs->getClassMetadata();
if (!$classMetadata->isInheritanceTypeSingleTable() || $classMetadata->getName() === $classMetadata->rootEntityName) {
$classMetadata->setPrimaryTable([
'name' => $this->getPrefix($classMetadata->getName(), $classMetadata->getTableName()) . $classMetadata->getTableName()
]);
}
foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
if ($mapping['type'] == ClassMetadataInfo::MANY_TO_MANY && $mapping['isOwningSide']) {
$mappedTableName = $mapping['joinTable']['name'];
$classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->getPrefix($mapping['targetEntity'], $mappedTableName) . $mappedTableName;
}
}
}
/**
* @param string $className
* @param string $tableName
*
* @return string
*/
protected function getPrefix(string $className, string $tableName): string
{
// get the namespaces from the class name
// $className might be "App\Calendar\Entity\CalendarEntity"
$nameSpaces = explode('\\', $className);
$bundleName = isset($nameSpaces[1]) ? strtolower($nameSpaces[1]) : null;
if (!$bundleName || !isset($this->config[$bundleName])) {
return '';
}
$prefix = $this->config[$bundleName];
// table is already prefixed with bundle name
if (strpos($tableName, $prefix) === 0) {
return '';
}
return $prefix;
}
/**
* Returns an array of events this subscriber wants to listen to.
*
* @return string[]
*/
public function getSubscribedEvents()
{
// TODO: Implement getSubscribedEvents() method.
}
} |
Partager