-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTablePrefixEventListener.php
More file actions
55 lines (45 loc) · 1.48 KB
/
TablePrefixEventListener.php
File metadata and controls
55 lines (45 loc) · 1.48 KB
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
<?php
namespace SyncEngine\EventListener;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
#[AsDoctrineListener( event: 'loadClassMetadata' )]
class TablePrefixEventListener
{
public function __construct(
private readonly string $prefix
) {}
public function loadClassMetadata( LoadClassMetadataEventArgs $eventArgs ): void
{
$classMetadata = $eventArgs->getClassMetadata();
if (
! $classMetadata->isInheritanceTypeSingleTable()
|| $classMetadata->getName() === $classMetadata->rootEntityName
) {
$this->prefixTable( $classMetadata );
}
foreach ( $classMetadata->getAssociationMappings() as $fieldName => $mapping ) {
if (
$mapping['type'] === ClassMetadataInfo::MANY_TO_MANY
&& $mapping['isOwningSide']
) {
$this->prefixJoinTable( $classMetadata, $fieldName, $mapping );
}
}
}
private function prefixTable( $classMetadata ): void
{
$tableName = $classMetadata->getTableName();
if ( ! str_starts_with( $tableName, $this->prefix ) ) {
$classMetadata->setPrimaryTable( [ 'name' => $this->prefix . $tableName ] );
}
}
private function prefixJoinTable( $classMetadata, string $fieldName, array $mapping ): void
{
$tableName = $mapping['joinTable']['name'];
if ( ! str_starts_with( $tableName, $this->prefix ) ) {
$classMetadata->associationMappings[ $fieldName ]['joinTable']['name'] =
$this->prefix . $tableName;
}
}
}