Completed
Push — 3.x ( 86c9c1...af1625 )
by Grégoire
02:11
created

DatagridBuilder::fixFieldDescription()   C

Complexity

Conditions 9
Paths 22

Size

Total Lines 63
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 63
rs 6.6149
c 0
b 0
f 0
cc 9
eloc 36
nc 22
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\DoctrineORMAdminBundle\Builder;
13
14
use Doctrine\ORM\Mapping\ClassMetadata;
15
use Sonata\AdminBundle\Admin\AdminInterface;
16
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
17
use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
18
use Sonata\AdminBundle\Datagrid\Datagrid;
19
use Sonata\AdminBundle\Datagrid\DatagridInterface;
20
use Sonata\AdminBundle\Datagrid\PagerInterface;
21
use Sonata\AdminBundle\Datagrid\SimplePager;
22
use Sonata\AdminBundle\Filter\FilterFactoryInterface;
23
use Sonata\AdminBundle\Guesser\TypeGuesserInterface;
24
use Sonata\DoctrineORMAdminBundle\Datagrid\Pager;
25
use Sonata\DoctrineORMAdminBundle\Filter\ModelAutocompleteFilter;
26
use Symfony\Component\Form\Extension\Core\Type\FormType;
27
use Symfony\Component\Form\FormFactoryInterface;
28
29
class DatagridBuilder implements DatagridBuilderInterface
30
{
31
    /**
32
     * @var FilterFactoryInterface
33
     */
34
    protected $filterFactory;
35
36
    /**
37
     * @var FormFactoryInterface
38
     */
39
    protected $formFactory;
40
41
    /**
42
     * @var TypeGuesserInterface
43
     */
44
    protected $guesser;
45
46
    /**
47
     * @var bool
48
     */
49
    protected $csrfTokenEnabled;
50
51
    /**
52
     * @param bool $csrfTokenEnabled
53
     */
54
    public function __construct(
55
        FormFactoryInterface $formFactory,
56
        FilterFactoryInterface $filterFactory,
57
        TypeGuesserInterface $guesser,
58
        $csrfTokenEnabled = true
59
    ) {
60
        $this->formFactory = $formFactory;
61
        $this->filterFactory = $filterFactory;
62
        $this->guesser = $guesser;
63
        $this->csrfTokenEnabled = $csrfTokenEnabled;
64
    }
65
66
    public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription)
67
    {
68
        // set default values
69
        $fieldDescription->setAdmin($admin);
70
71
        if ($admin->getModelManager()->hasMetadata($admin->getClass())) {
72
            list($metadata, $lastPropertyName, $parentAssociationMappings) = $admin->getModelManager()
73
                ->getParentMetadataForProperty($admin->getClass(), $fieldDescription->getName());
74
75
            // set the default field mapping
76
            if (isset($metadata->fieldMappings[$lastPropertyName])) {
77
                $fieldDescription->setOption(
78
                    'field_mapping',
79
                    $fieldDescription->getOption(
80
                        'field_mapping',
81
                        $fieldMapping = $metadata->fieldMappings[$lastPropertyName]
82
                    )
83
                );
84
85
                if ('string' == $fieldMapping['type']) {
86
                    $fieldDescription->setOption('global_search', $fieldDescription->getOption('global_search', true)); // always search on string field only
87
                }
88
89
                if (!empty($embeddedClasses = $metadata->embeddedClasses)
90
                    && isset($fieldMapping['declaredField'])
91
                    && array_key_exists($fieldMapping['declaredField'], $embeddedClasses)
92
                ) {
93
                    $fieldDescription->setOption(
94
                        'field_name',
95
                        $fieldMapping['fieldName']
96
                    );
97
                }
98
            }
99
100
            // set the default association mapping
101
            if (isset($metadata->associationMappings[$lastPropertyName])) {
102
                $fieldDescription->setOption(
103
                    'association_mapping',
104
                    $fieldDescription->getOption(
105
                        'association_mapping',
106
                        $metadata->associationMappings[$lastPropertyName]
107
                    )
108
                );
109
            }
110
111
            $fieldDescription->setOption(
112
                'parent_association_mappings',
113
                $fieldDescription->getOption('parent_association_mappings', $parentAssociationMappings)
114
            );
115
        }
116
117
        $fieldDescription->setOption('code', $fieldDescription->getOption('code', $fieldDescription->getName()));
118
        $fieldDescription->setOption('name', $fieldDescription->getOption('name', $fieldDescription->getName()));
119
120
        if (in_array($fieldDescription->getMappingType(), [
121
            ClassMetadata::ONE_TO_MANY,
122
            ClassMetadata::MANY_TO_MANY,
123
            ClassMetadata::MANY_TO_ONE,
124
            ClassMetadata::ONE_TO_ONE,
125
        ])) {
126
            $admin->attachAdminClass($fieldDescription);
127
        }
128
    }
129
130
    public function addFilter(DatagridInterface $datagrid, $type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
131
    {
132
        if (null == $type) {
133
            $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager());
134
135
            $type = $guessType->getType();
136
137
            $fieldDescription->setType($type);
138
139
            $options = $guessType->getOptions();
140
141
            foreach ($options as $name => $value) {
142
                if (is_array($value)) {
143
                    $fieldDescription->setOption($name, array_merge($value, $fieldDescription->getOption($name, [])));
144
                } else {
145
                    $fieldDescription->setOption($name, $fieldDescription->getOption($name, $value));
146
                }
147
            }
148
        } else {
149
            $fieldDescription->setType($type);
150
        }
151
152
        $this->fixFieldDescription($admin, $fieldDescription);
153
        $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
154
155
        $fieldDescription->mergeOption('field_options', ['required' => false]);
156
157
        // NEXT_MAJOR: Check only against FQCNs when dropping support for Symfony 2.8
158
        if ('doctrine_orm_model_autocomplete' === $type || ModelAutocompleteFilter::class === $type) {
159
            $fieldDescription->mergeOption('field_options', [
160
                'class' => $fieldDescription->getTargetEntity(),
161
                'model_manager' => $fieldDescription->getAdmin()->getModelManager(),
162
                'admin_code' => $admin->getCode(),
163
                'context' => 'filter',
164
            ]);
165
        }
166
167
        $filter = $this->filterFactory->create($fieldDescription->getName(), $type, $fieldDescription->getOptions());
168
169
        if (false !== $filter->getLabel() && !$filter->getLabel()) {
170
            $filter->setLabel($admin->getLabelTranslatorStrategy()->getLabel($fieldDescription->getName(), 'filter', 'label'));
171
        }
172
173
        $datagrid->addFilter($filter);
174
    }
175
176
    public function getBaseDatagrid(AdminInterface $admin, array $values = [])
177
    {
178
        $pager = $this->getPager($admin->getPagerType());
179
180
        $pager->setCountColumn($admin->getModelManager()->getIdentifierFieldNames($admin->getClass()));
181
182
        $defaultOptions = [];
183
        if ($this->csrfTokenEnabled) {
184
            $defaultOptions['csrf_protection'] = false;
185
        }
186
187
        $formBuilder = $this->formFactory->createNamedBuilder('filter', FormType::class, [], $defaultOptions);
188
189
        return new Datagrid($admin->createQuery(), $admin->getList(), $pager, $formBuilder, $values);
190
    }
191
192
    /**
193
     * Get pager by pagerType.
194
     *
195
     * @param string $pagerType
196
     *
197
     * @throws \RuntimeException If invalid pager type is set
198
     *
199
     * @return PagerInterface
200
     */
201
    protected function getPager($pagerType)
202
    {
203
        switch ($pagerType) {
204
            case Pager::TYPE_DEFAULT:
205
                return new Pager();
206
207
            case Pager::TYPE_SIMPLE:
208
                return new SimplePager();
209
210
            default:
211
                throw new \RuntimeException(sprintf('Unknown pager type "%s".', $pagerType));
212
        }
213
    }
214
}
215