Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.12% covered (success)
94.12%
80 / 85
71.43% covered (warning)
71.43%
5 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
LimitFieldLength
94.12% covered (success)
94.12%
80 / 85
71.43% covered (warning)
71.43%
5 / 7
38.29
0.00% covered (danger)
0.00%
0 / 1
 postRun
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 patch
90.62% covered (success)
90.62%
29 / 32
0.00% covered (danger)
0.00%
0 / 1
10.08
 limitJoinTable
93.94% covered (success)
93.94%
31 / 33
0.00% covered (danger)
0.00%
0 / 1
14.04
 modifyAttributes
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 fillInMissingStringLength
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 setNameArgument
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 iterateProperties
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2namespace Apie\DoctrineEntityConverter\CodeGenerators;
3
4use Apie\StorageMetadataBuilder\Interfaces\PostRunGeneratedCodeContextInterface;
5use Apie\StorageMetadataBuilder\Mediators\GeneratedCodeContext;
6use Doctrine\ORM\Mapping\Column;
7use Doctrine\ORM\Mapping\JoinColumn;
8use Doctrine\ORM\Mapping\JoinTable;
9use Doctrine\ORM\Mapping\ManyToMany;
10use Doctrine\ORM\Mapping\Table;
11use Generator;
12use Nette\PhpGenerator\Attribute;
13use Nette\PhpGenerator\ClassType;
14use Nette\PhpGenerator\Literal;
15use Nette\PhpGenerator\PromotedParameter;
16use Nette\PhpGenerator\Property;
17
18/**
19 * Find all doctrine column attributes set by AddDoctrineFields and checks if the generated column name
20 * is not too long.
21 *
22 * Most database vendors have a 64 character limit, Postgres has a 63 character limit.
23 * Foreign keys get a '_id' suffix, so any property name with more than 57 characters requires a different
24 * column name.
25 *
26 * We want to rename the column to only 57 characters and add 3 digits after it if this column name is already defined.
27 *
28 * @see AddDoctrineFields
29 */
30class LimitFieldLength implements PostRunGeneratedCodeContextInterface
31{
32    public function postRun(GeneratedCodeContext $generatedCodeContext): void
33    {
34        foreach ($generatedCodeContext->generatedCode->generatedCodeHashmap as $code) {
35            $this->patch($generatedCodeContext, $code);
36        }
37    }
38
39    private function patch(GeneratedCodeContext $generatedCodeContext, ClassType $classType): void
40    {
41        if (strlen($classType->getName()) > 60) {
42            $found = false;
43            $suggestedTableName = substr($classType->getName(), 0, 30) . '_' . md5($classType->getName());
44            $this->modifyAttributes(function (Attribute $attribute) use ($suggestedTableName, &$found) {
45                if ($attribute->getName() === Table::class) {
46                    $found = true;
47                    return $this->setNameArgument($attribute, $suggestedTableName);
48                }
49                return $attribute;
50            }, $classType);
51            if (!$found) {
52                $classType->addAttribute(Table::class, ['name' => $suggestedTableName]);
53            }
54        }
55        $alreadyDefined = [];
56        foreach ($this->iterateProperties($classType) as $property) {
57            $this->limitJoinTable($classType, $property);
58            $this->modifyAttributes(function (Attribute $attribute) {
59                if (in_array($attribute->getName(), [Column::class])) {
60                    return $this->fillInMissingStringLength($attribute);
61                }
62                return $attribute;
63            }, $property);
64            $propertyName = $property->getName();
65            if (strlen($property->getName()) < 57 && !isset($alreadyDefined[$propertyName])) {
66                $alreadyDefined[$propertyName] = true;
67                continue;
68            }
69            $suggestedName = substr($propertyName, 0, 57);
70            for ($i = 0; !empty($alreadyDefined[$suggestedName]); $i++) {
71                $suggestedName = sprintf("%s%03u", substr($property->getName(), 0, 57), $i);
72            }
73            $this->modifyAttributes(function (Attribute $attribute) use ($suggestedName) {
74                if (in_array($attribute->getName(), [Column::class, JoinColumn::class])) {
75                    return $this->setNameArgument($attribute, $suggestedName);
76                }
77                return $attribute;
78            }, $property);
79            $alreadyDefined[$suggestedName] = true;
80        }
81    }
82
83    /**
84     * Doctrine generates the name of a join table of a ManyToMany as "<source table>_<target table>" and the
85     * join columns as "<table>_id", so these can exceed the database limit while the tables themselves do not.
86     */
87    private function limitJoinTable(ClassType $classType, PromotedParameter|Property $property): void
88    {
89        $manyToMany = null;
90        $joinTable = null;
91        foreach ($property->getAttributes() as $attribute) {
92            if ($attribute->getName() === ManyToMany::class) {
93                $manyToMany = $attribute;
94            }
95            if ($attribute->getName() === JoinTable::class) {
96                $joinTable = $attribute;
97            }
98        }
99        $targetEntity = $manyToMany?->getArguments()['targetEntity'] ?? null;
100        if (!is_string($targetEntity) || isset($joinTable?->getArguments()['name'])) {
101            return;
102        }
103        $source = $classType->getName();
104        $target = ltrim(strrchr('\\' . $targetEntity, '\\'), '\\');
105
106        $arguments = $joinTable?->getArguments() ?? [];
107        $tableName = strtolower($source . '_' . $target);
108        if (strlen($tableName) > 60) {
109            $arguments['name'] = substr($tableName, 0, 30) . '_' . md5($tableName);
110        }
111        // Doctrine uses source_id and target_id for self referencing relations, so we leave those alone.
112        if ($source !== $target) {
113            foreach (['joinColumns' => $source, 'inverseJoinColumns' => $target] as $key => $entityName) {
114                $columnName = strtolower($entityName . '_id');
115                if (!isset($arguments[$key]) && strlen($columnName) > 57) {
116                    $shortName = substr($columnName, 0, 30) . '_' . md5($columnName);
117                    $arguments[$key] = [new Literal(
118                        'new \\' . JoinColumn::class . '(name: ?, referencedColumnName: \'id\', onDelete: \'CASCADE\')',
119                        [$shortName]
120                    )];
121                }
122            }
123        }
124        if (!$arguments) {
125            return;
126        }
127        $attributes = [];
128        foreach ($property->getAttributes() as $attribute) {
129            if ($attribute !== $joinTable) {
130                $attributes[] = $attribute;
131            }
132        }
133        $attributes[] = new Attribute(JoinTable::class, $arguments);
134        $property->setAttributes($attributes);
135    }
136
137    private function modifyAttributes(callable $callback, ClassType|PromotedParameter|Property $property): void
138    {
139        $attributes = [];
140        foreach ($property->getAttributes() as $attribute) {
141            $attributes[] = $callback($attribute);
142        }
143        $property->setAttributes($attributes);
144    }
145
146    private function fillInMissingStringLength(Attribute $attribute): Attribute
147    {
148        $arguments = $attribute->getArguments();
149        if (($arguments['type'] ?? 'string')=== 'string' || !isset($arguments['type'])) {
150            if (!isset($arguments['length'])) {
151                $arguments['length'] = 255;
152            }
153        }
154        return new Attribute($attribute->getName(), $arguments);
155    }
156
157    private function setNameArgument(Attribute $attribute, string $suggestedName): Attribute
158    {
159        $arguments = $attribute->getArguments();
160        $arguments['name'] = $suggestedName;
161        return new Attribute($attribute->getName(), $arguments);
162    }
163
164    /**
165     * @return Generator<int, PromotedParameter|Property>
166     */
167    private function iterateProperties(ClassType $classType): Generator
168    {
169        foreach ($classType->getProperties() as $property) {
170            yield $property;
171        }
172        if ($classType->hasMethod('__construct')) {
173            foreach ($classType->getMethod('__construct')->getParameters() as $parameter) {
174                if ($parameter instanceof PromotedParameter) {
175                    yield $parameter;
176                }
177            }
178        }
179    }
180}