|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LAG\AdminBundle\Bridge\Doctrine\ORM\Metadata; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
6
|
|
|
use Doctrine\ORM\Mapping\ClassMetadataInfo; |
|
7
|
|
|
use LAG\AdminBundle\Field\Definition\FieldDefinition; |
|
8
|
|
|
|
|
9
|
|
|
class MetadataHelper implements MetadataHelperInterface |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var EntityManagerInterface |
|
13
|
|
|
*/ |
|
14
|
|
|
private $entityManager; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct(EntityManagerInterface $entityManager) |
|
17
|
|
|
{ |
|
18
|
|
|
$this->entityManager = $entityManager; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function getFields(string $entityClass): array |
|
22
|
|
|
{ |
|
23
|
|
|
$metadata = $this->entityManager->getClassMetadata($entityClass); |
|
24
|
|
|
$fieldNames = (array) $metadata->fieldNames; |
|
|
|
|
|
|
25
|
|
|
$fields = []; |
|
26
|
|
|
|
|
27
|
|
|
foreach ($fieldNames as $fieldName) { |
|
28
|
|
|
// Remove the primary key field if it's not managed manually |
|
29
|
|
|
if (!$metadata->isIdentifierNatural() && in_array($fieldName, $metadata->identifier)) { |
|
|
|
|
|
|
30
|
|
|
continue; |
|
31
|
|
|
} |
|
32
|
|
|
$mapping = $metadata->getFieldMapping($fieldName); |
|
33
|
|
|
$formOptions = []; |
|
34
|
|
|
|
|
35
|
|
|
// When a field is defined as nullable in the Doctrine entity configuration, the associated form field |
|
36
|
|
|
// should not be required neither |
|
37
|
|
|
if (key_exists('nullable', $mapping) && true === $mapping['nullable']) { |
|
38
|
|
|
$formOptions['required'] = false; |
|
39
|
|
|
} |
|
40
|
|
|
$fields[$fieldName] = new FieldDefinition($metadata->getTypeOfField($fieldName), [], $formOptions); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
foreach ($metadata->associationMappings as $fieldName => $relation) { |
|
|
|
|
|
|
44
|
|
|
$formOptions = []; |
|
45
|
|
|
$formType = 'choice'; |
|
46
|
|
|
|
|
47
|
|
|
if (ClassMetadataInfo::MANY_TO_MANY === $relation['type']) { |
|
48
|
|
|
$formOptions['expanded'] = true; |
|
49
|
|
|
$formOptions['multiple'] = true; |
|
50
|
|
|
} |
|
51
|
|
|
if ($this->isJoinColumnNullable($relation)) { |
|
52
|
|
|
$formOptions['required'] = false; |
|
53
|
|
|
} |
|
54
|
|
|
$fields[$fieldName] = new FieldDefinition($formType, [], $formOptions); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $fields; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
private function isJoinColumnNullable(array $relation) |
|
61
|
|
|
{ |
|
62
|
|
|
if (!key_exists('joinColumns', $relation)) { |
|
63
|
|
|
return false; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if (!key_exists('nullable', $relation['joinColumns'])) { |
|
67
|
|
|
return false; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return false === $relation['joinColumns']['nullable']; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|