Add table prefix setup for Doctrine

[MAILPOET-2014]
This commit is contained in:
Jan Jakeš
2019-04-25 17:04:53 +02:00
committed by M. Shull
parent e515f06d02
commit b314afed8c
2 changed files with 49 additions and 0 deletions

View File

@@ -38,6 +38,8 @@ class ConfigurationFactory {
} }
private function configureMetadata(Configuration $configuration) { private function configureMetadata(Configuration $configuration) {
$configuration->setClassMetadataFactoryName(TablePrefixMetadataFactory::class);
// metadata cache (for production cache is pre-generated at build time) // metadata cache (for production cache is pre-generated at build time)
$metadata_storage = new MetadataCache(self::METADATA_DIR); $metadata_storage = new MetadataCache(self::METADATA_DIR);
$configuration->setMetadataCacheImpl($metadata_storage); $configuration->setMetadataCacheImpl($metadata_storage);

View File

@@ -0,0 +1,47 @@
<?php
namespace MailPoet\Doctrine;
use MailPoet\Config\Env;
use MailPoetVendor\Doctrine\ORM\Mapping\ClassMetadata;
use MailPoetVendor\Doctrine\ORM\Mapping\ClassMetadataFactory;
use MailPoetVendor\Doctrine\ORM\Mapping\ClassMetadataInfo;
// Taken from Doctrine docs (see link bellow) but implemented in metadata factory instead of an event
// because we need to add prefix at runtime, not at metadata dump (which is included in builds).
// @see https://www.doctrine-project.org/projects/doctrine-orm/en/2.5/cookbook/sql-table-prefixes.html
class TablePrefixMetadataFactory extends ClassMetadataFactory {
/** @var string */
private $prefix;
function __construct() {
if (Env::$db_prefix === null) {
throw new \RuntimeException('DB table prefix not initialized');
}
$this->prefix = Env::$db_prefix;
}
function getMetadataFor($className) {
$isPrefixed = $this->hasMetadataFor($className);
$classMetadata = parent::getMetadataFor($className);
if (!$isPrefixed && $classMetadata instanceof ClassMetadata) {
$this->addPrefix($classMetadata);
}
return $classMetadata;
}
function addPrefix(ClassMetadata $classMetadata) {
if (!$classMetadata->isInheritanceTypeSingleTable() || $classMetadata->getName() === $classMetadata->rootEntityName) {
$classMetadata->setPrimaryTable([
'name' => $this->prefix . $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->prefix . $mappedTableName;
}
}
}
}