TableSchemaSubscriber::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Fi\CoreBundle\Subscriber;
4
5
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
6
use Doctrine\ORM\Mapping\ClassMetadataInfo;
7
use Doctrine\ORM\Id\SequenceGenerator;
8
9
class TableSchemaSubscriber implements \Doctrine\Common\EventSubscriber
10
{
11
    protected $prefix = '';
12
13 67
    public function __construct($prefix)
14
    {
15 67
        $this->prefix = (string) $prefix;
16 67
    }
17
18 67
    public function getSubscribedEvents()
19
    {
20 67
        return array('loadClassMetadata');
21
    }
22
23 59
    public function loadClassMetadata(LoadClassMetadataEventArgs $args)
24
    {
25 59
        if ($this->prefix != '') {
26
            $classMetadata = $args->getClassMetadata();
27
28
            $classMetadata->setPrimaryTable(array('name' => $this->prefix.'.'.$classMetadata->getTableName()));
29
30
            foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
31
                $jointablename = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
32
                if ($mapping['type'] == ClassMetadataInfo::MANY_TO_MANY && isset($jointablename)) {
33
                    $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
34
                    $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix.'.'.$mappedTableName;
35
                }
36
            }
37
            if ($classMetadata->isIdGeneratorSequence()) {
38
                $newDefinition = $classMetadata->sequenceGeneratorDefinition;
39
                $newDefinition['sequenceName'] = $this->prefix.'.'.$newDefinition['sequenceName'];
40
41
                $classMetadata->setSequenceGeneratorDefinition($newDefinition);
42
                $em = $args->getEntityManager();
43
                if (isset($classMetadata->idGenerator)) {
44
                    $sequncename = $em->getConfiguration()->getQuoteStrategy()
45
                            ->getSequenceName($newDefinition, $classMetadata, $em->getConnection()->getDatabasePlatform());
46
                    $allocationSize = $newDefinition['allocationSize'];
47
                    $sequenceGenerator = new SequenceGenerator($sequncename, $allocationSize);
48
                    $classMetadata->setIdGenerator($sequenceGenerator);
49
                }
50
            }
51
        }
52 59
    }
53
}
54