ListBuilder   A
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 221
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 6
dl 0
loc 221
rs 9.52
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getBaseList() 0 4 1
A buildField() 0 11 3
A addField() 0 7 1
F fixFieldDescription() 0 114 20
B buildActionFieldDescription() 0 31 8
A getTemplate() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\DoctrinePHPCRAdminBundle\Builder;
15
16
use Doctrine\ODM\PHPCR\Mapping\ClassMetadata;
17
use Sonata\AdminBundle\Admin\AdminInterface;
18
use Sonata\AdminBundle\Admin\FieldDescriptionCollection;
19
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
20
use Sonata\AdminBundle\Builder\ListBuilderInterface;
21
use Sonata\AdminBundle\Guesser\TypeGuesserInterface;
22
use Symfony\Component\Form\Guess\TypeGuess;
23
24
class ListBuilder implements ListBuilderInterface
25
{
26
    /**
27
     * @var TypeGuesserInterface
28
     */
29
    protected $guesser;
30
31
    /**
32
     * @var array
33
     */
34
    protected $templates;
35
36
    public function __construct(TypeGuesserInterface $guesser, array $templates = [])
37
    {
38
        $this->guesser = $guesser;
39
        $this->templates = $templates;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getBaseList(array $options = [])
46
    {
47
        return new FieldDescriptionCollection();
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function buildField($type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin): void
54
    {
55
        if (null === $type) {
56
            $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager());
57
            $fieldDescription->setType($guessType instanceof TypeGuess ? $guessType->getType() : null);
58
        } else {
59
            $fieldDescription->setType($type);
60
        }
61
62
        $this->fixFieldDescription($admin, $fieldDescription);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function addField(FieldDescriptionCollection $list, $type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin): void
69
    {
70
        $this->buildField($type, $fieldDescription, $admin);
71
        $admin->addListFieldDescription($fieldDescription->getName(), $fieldDescription);
72
73
        $list->add($fieldDescription);
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     *
79
     * @throws \RuntimeException if the $fieldDescription does not have a type
80
     */
81
    public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription): void
82
    {
83
        if ('_action' === $fieldDescription->getName() || 'actions' === $fieldDescription->getType()) {
84
            $this->buildActionFieldDescription($fieldDescription);
85
        }
86
87
        $fieldDescription->setAdmin($admin);
88
        $metadata = null;
89
90
        if ($admin->getModelManager()->hasMetadata($admin->getClass())) {
91
            /** @var ClassMetadata $metadata */
92
            $metadata = $admin->getModelManager()->getMetadata($admin->getClass());
93
94
            // TODO sort on parent associations or node name
95
            $defaultSortable = true;
96
            if ($metadata->hasAssociation($fieldDescription->getName())
97
                || $metadata->nodename === $fieldDescription->getName()
98
            ) {
99
                $defaultSortable = false;
100
            }
101
102
            // TODO get and set parent association mappings, see
103
            // https://github.com/sonata-project/SonataDoctrinePhpcrAdminBundle/issues/106
104
            //$fieldDescription->setParentAssociationMappings($parentAssociationMappings);
105
106
            // set the default field mapping
107
            if (isset($metadata->mappings[$fieldDescription->getName()])) {
108
                $fieldDescription->setFieldMapping($metadata->mappings[$fieldDescription->getName()]);
109
                if (false !== $fieldDescription->getOption('sortable')) {
110
                    $fieldDescription->setOption(
111
                        'sortable',
112
                        $fieldDescription->getOption('sortable', $defaultSortable)
113
                    );
114
                    $fieldDescription->setOption(
115
                        'sort_parent_association_mappings',
116
                        $fieldDescription->getOption(
117
                            'sort_parent_association_mappings',
118
                            $fieldDescription->getParentAssociationMappings()
119
                        )
120
                    );
121
                    $fieldDescription->setOption(
122
                        'sort_field_mapping',
123
                        $fieldDescription->getOption(
124
                            'sort_field_mapping',
125
                            $fieldDescription->getFieldMapping()
126
                        )
127
                    );
128
                }
129
            }
130
131
            // set the default association mapping
132
            if (isset($metadata->associationMappings[$fieldDescription->getName()])) {
0 ignored issues
show
Bug introduced by
The property associationMappings does not seem to exist. Did you mean mappings?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
133
                $fieldDescription->setAssociationMapping($metadata->associationMappings[$fieldDescription->getName()]);
0 ignored issues
show
Bug introduced by
The property associationMappings does not seem to exist. Did you mean mappings?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
134
            }
135
136
            $fieldDescription->setOption(
137
                '_sort_order',
138
                $fieldDescription->getOption('_sort_order', 'ASC')
139
            );
140
        }
141
142
        if (!$fieldDescription->getType()) {
143
            throw new \RuntimeException(sprintf(
144
                'Please define a type for field `%s` in `%s`',
145
                $fieldDescription->getName(),
146
                \get_class($admin)
147
            ));
148
        }
149
150
        $fieldDescription->setOption(
151
            'code',
152
            $fieldDescription->getOption('code', $fieldDescription->getName())
153
        );
154
        $fieldDescription->setOption(
155
            'label',
156
            $fieldDescription->getOption('label', $fieldDescription->getName())
157
        );
158
159
        if (!$fieldDescription->getTemplate()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fieldDescription->getTemplate() of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
160
            $fieldDescription->setTemplate($this->getTemplate($fieldDescription->getType()));
161
162
            if (ClassMetadata::MANY_TO_ONE === $fieldDescription->getMappingType()) {
163
                $fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_many_to_one.html.twig');
164
            }
165
166
            if (ClassMetadata::MANY_TO_MANY === $fieldDescription->getMappingType()) {
167
                $fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_many_to_many.html.twig');
168
            }
169
170
            if ('child' === $fieldDescription->getMappingType() || 'parent' === $fieldDescription->getMappingType()) {
171
                $fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_one_to_one.html.twig');
172
            }
173
174
            if ('children' === $fieldDescription->getMappingType() || 'referrers' === $fieldDescription->getMappingType()) {
175
                $fieldDescription->setTemplate('@SonataAdmin/CRUD/Association/list_one_to_many.html.twig');
176
            }
177
        }
178
179
        $mappingTypes = [
180
            ClassMetadata::MANY_TO_ONE,
181
            ClassMetadata::MANY_TO_MANY,
182
            'children',
183
            'child',
184
            'parent',
185
            'referrers',
186
        ];
187
188
        if ($metadata
189
            && $metadata->hasAssociation($fieldDescription->getName())
190
            && \in_array($fieldDescription->getMappingType(), $mappingTypes, true)
191
        ) {
192
            $admin->attachAdminClass($fieldDescription);
193
        }
194
    }
195
196
    /**
197
     * @return FieldDescriptionInterface
198
     */
199
    public function buildActionFieldDescription(FieldDescriptionInterface $fieldDescription)
200
    {
201
        if (null === $fieldDescription->getTemplate()) {
202
            $fieldDescription->setTemplate('@SonataAdmin/CRUD/list__action.html.twig');
203
        }
204
205
        if (null === $fieldDescription->getType()) {
206
            $fieldDescription->setType('actions');
207
        }
208
209
        if (null === $fieldDescription->getOption('name')) {
210
            $fieldDescription->setOption('name', 'Action');
211
        }
212
213
        if (null === $fieldDescription->getOption('code')) {
214
            $fieldDescription->setOption('code', 'Action');
215
        }
216
217
        if (null !== $fieldDescription->getOption('actions')) {
218
            $actions = $fieldDescription->getOption('actions');
219
            foreach ($actions as $k => $action) {
220
                if (!isset($action['template'])) {
221
                    $actions[$k]['template'] = sprintf('@SonataAdmin/CRUD/list__action_%s.html.twig', $k);
222
                }
223
            }
224
225
            $fieldDescription->setOption('actions', $actions);
226
        }
227
228
        return $fieldDescription;
229
    }
230
231
    /**
232
     * @param string $type
233
     *
234
     * @return string
235
     */
236
    private function getTemplate($type)
237
    {
238
        if (!isset($this->templates[$type])) {
239
            return;
240
        }
241
242
        return $this->templates[$type];
243
    }
244
}
245