Completed
Push — 3.x-dev-kit ( 4fe8f1 )
by
unknown
11:30 queued 08:33
created

DatagridBuilder::getBaseDatagrid()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 18
rs 9.4285
cc 3
eloc 10
nc 4
nop 2
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\ClassMetadataInfo;
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 Symfony\Component\Form\FormFactoryInterface;
26
27
class DatagridBuilder implements DatagridBuilderInterface
28
{
29
    /**
30
     * @var FilterFactoryInterface
31
     */
32
    protected $filterFactory;
33
34
    /**
35
     * @var FormFactoryInterface
36
     */
37
    protected $formFactory;
38
39
    /**
40
     * @var TypeGuesserInterface
41
     */
42
    protected $guesser;
43
44
    /**
45
     * @var bool
46
     */
47
    protected $csrfTokenEnabled;
48
49
    /**
50
     * @param FormFactoryInterface   $formFactory
51
     * @param FilterFactoryInterface $filterFactory
52
     * @param TypeGuesserInterface   $guesser
53
     * @param bool                   $csrfTokenEnabled
54
     */
55
    public function __construct(FormFactoryInterface $formFactory, FilterFactoryInterface $filterFactory, TypeGuesserInterface $guesser, $csrfTokenEnabled = true)
56
    {
57
        $this->formFactory = $formFactory;
58
        $this->filterFactory = $filterFactory;
59
        $this->guesser = $guesser;
60
        $this->csrfTokenEnabled = $csrfTokenEnabled;
61
    }
62
63
    /**
64
     * {@inheritdoc}
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()->getParentMetadataForProperty($admin->getClass(), $fieldDescription->getName());
73
74
            // set the default field mapping
75
            if (isset($metadata->fieldMappings[$lastPropertyName])) {
76
                $fieldDescription->setOption('field_mapping', $fieldDescription->getOption('field_mapping', $metadata->fieldMappings[$lastPropertyName]));
77
78
                if ($metadata->fieldMappings[$lastPropertyName]['type'] == 'string') {
79
                    $fieldDescription->setOption('global_search', $fieldDescription->getOption('global_search', true)); // always search on string field only
80
                }
81
            }
82
83
            // set the default association mapping
84
            if (isset($metadata->associationMappings[$lastPropertyName])) {
85
                $fieldDescription->setOption('association_mapping', $fieldDescription->getOption('association_mapping', $metadata->associationMappings[$lastPropertyName]));
86
            }
87
88
            $fieldDescription->setOption('parent_association_mappings', $fieldDescription->getOption('parent_association_mappings', $parentAssociationMappings));
89
        }
90
91
        $fieldDescription->setOption('code', $fieldDescription->getOption('code', $fieldDescription->getName()));
92
        $fieldDescription->setOption('name', $fieldDescription->getOption('name', $fieldDescription->getName()));
93
94
        if (in_array($fieldDescription->getMappingType(), array(ClassMetadataInfo::ONE_TO_MANY, ClassMetadataInfo::MANY_TO_MANY, ClassMetadataInfo::MANY_TO_ONE, ClassMetadataInfo::ONE_TO_ONE))) {
95
            $admin->attachAdminClass($fieldDescription);
96
        }
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function addFilter(DatagridInterface $datagrid, $type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
103
    {
104
        if ($type == null) {
105
            $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager());
106
107
            $type = $guessType->getType();
108
109
            $fieldDescription->setType($type);
110
111
            $options = $guessType->getOptions();
112
113
            foreach ($options as $name => $value) {
114
                if (is_array($value)) {
115
                    $fieldDescription->setOption($name, array_merge($value, $fieldDescription->getOption($name, array())));
116
                } else {
117
                    $fieldDescription->setOption($name, $fieldDescription->getOption($name, $value));
118
                }
119
            }
120
        } else {
121
            $fieldDescription->setType($type);
122
        }
123
124
        $this->fixFieldDescription($admin, $fieldDescription);
125
        $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
126
127
        $fieldDescription->mergeOption('field_options', array('required' => false));
128
129
        if ($type === 'doctrine_orm_model_autocomplete') {
130
            $fieldDescription->mergeOption('field_options', array(
131
                'class' => $fieldDescription->getTargetEntity(),
132
                'model_manager' => $fieldDescription->getAdmin()->getModelManager(),
133
                'admin_code' => $admin->getCode(),
134
                'context' => 'filter',
135
            ));
136
        }
137
138
        $filter = $this->filterFactory->create($fieldDescription->getName(), $type, $fieldDescription->getOptions());
139
140
        if (false !== $filter->getLabel() && !$filter->getLabel()) {
141
            $filter->setLabel($admin->getLabelTranslatorStrategy()->getLabel($fieldDescription->getName(), 'filter', 'label'));
142
        }
143
144
        $datagrid->addFilter($filter);
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150
    public function getBaseDatagrid(AdminInterface $admin, array $values = array())
151
    {
152
        $pager = $this->getPager($admin->getPagerType());
153
154
        $pager->setCountColumn($admin->getModelManager()->getIdentifierFieldNames($admin->getClass()));
155
156
        $defaultOptions = array();
157
        if ($this->csrfTokenEnabled) {
158
            $defaultOptions['csrf_protection'] = false;
159
        }
160
161
        // NEXT_MAJOR: Remove this line when drop Symfony <2.8 support
162
        $formType = method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')
163
            ? 'Symfony\Component\Form\Extension\Core\Type\FormType' : 'form';
164
        $formBuilder = $this->formFactory->createNamedBuilder('filter', $formType, array(), $defaultOptions);
165
166
        return new Datagrid($admin->createQuery(), $admin->getList(), $pager, $formBuilder, $values);
167
    }
168
169
    /**
170
     * Get pager by pagerType.
171
     *
172
     * @param string $pagerType
173
     *
174
     * @return PagerInterface
175
     *
176
     * @throws \RuntimeException If invalid pager type is set.
177
     */
178
    protected function getPager($pagerType)
179
    {
180
        switch ($pagerType) {
181
            case Pager::TYPE_DEFAULT:
182
                return new Pager();
183
184
            case Pager::TYPE_SIMPLE:
185
                return new SimplePager();
186
187
            default:
188
                throw new \RuntimeException(sprintf('Unknown pager type "%s".', $pagerType));
189
        }
190
    }
191
}
192