AdminHelper::appendFormFieldElement()   D
last analyzed

Complexity

Conditions 16
Paths 63

Size

Total Lines 104

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 104
rs 4.4532
c 0
b 0
f 0
cc 16
nc 63
nop 3

How to fix   Long Method    Complexity   

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
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\AdminBundle\Admin;
15
16
use Doctrine\Common\Collections\Collection;
17
use Doctrine\ODM\MongoDB\PersistentCollection;
18
use Doctrine\ORM\PersistentCollection as DoctrinePersistentCollection;
19
use Sonata\AdminBundle\Exception\NoValueException;
20
use Sonata\AdminBundle\Manipulator\ObjectManipulator;
21
use Sonata\AdminBundle\Util\FormBuilderIterator;
22
use Sonata\AdminBundle\Util\FormViewIterator;
23
use Symfony\Component\Form\FormBuilderInterface;
24
use Symfony\Component\Form\FormView;
25
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
26
27
/**
28
 * @final since sonata-project/admin-bundle 3.52
29
 *
30
 * @author Thomas Rabaix <[email protected]>
31
 */
32
class AdminHelper
33
{
34
    /**
35
     * @var string
36
     */
37
    private const FORM_FIELD_DELETE = '_delete';
38
39
    /**
40
     * @var PropertyAccessorInterface
41
     */
42
    protected $propertyAccessor;
43
44
    public function __construct(PropertyAccessorInterface $propertyAccessor)
45
    {
46
        $this->propertyAccessor = $propertyAccessor;
47
    }
48
49
    /**
50
     * @throws \RuntimeException
51
     */
52
    public function getChildFormBuilder(FormBuilderInterface $formBuilder, string $elementId): ?FormBuilderInterface
53
    {
54
        foreach (new FormBuilderIterator($formBuilder) as $name => $formBuilder) {
55
            if ($name === $elementId) {
56
                return $formBuilder;
57
            }
58
        }
59
60
        return null;
61
    }
62
63
    public function getChildFormView(FormView $formView, string $elementId): ?FormView
64
    {
65
        foreach (new \RecursiveIteratorIterator(new FormViewIterator($formView), \RecursiveIteratorIterator::SELF_FIRST) as $name => $formView) {
66
            if ($name === $elementId) {
67
                return $formView;
68
            }
69
        }
70
71
        return null;
72
    }
73
74
    /**
75
     * Note:
76
     *   This code is ugly, but there is no better way of doing it.
77
     *
78
     * @throws \RuntimeException
79
     * @throws \Exception
80
     */
81
    public function appendFormFieldElement(AdminInterface $admin, object $subject, string $elementId): array
82
    {
83
        // child rows marked as toDelete
84
        $toDelete = [];
85
86
        $formBuilder = $admin->getFormBuilder();
87
88
        // get the field element
89
        $childFormBuilder = $this->getChildFormBuilder($formBuilder, $elementId);
90
91
        if ($childFormBuilder) {
92
            $formData = $admin->getRequest()->get($formBuilder->getName(), []);
93
            if (\array_key_exists($childFormBuilder->getName(), $formData)) {
94
                $formData = $admin->getRequest()->get($formBuilder->getName(), []);
95
                $i = 0;
96
                foreach ($formData[$childFormBuilder->getName()] as $name => &$field) {
97
                    $toDelete[$i] = false;
98
                    if (\array_key_exists(self::FORM_FIELD_DELETE, $field)) {
99
                        $toDelete[$i] = true;
100
                        unset($field[self::FORM_FIELD_DELETE]);
101
                    }
102
                    ++$i;
103
                }
104
            }
105
            $admin->getRequest()->request->set($formBuilder->getName(), $formData);
106
        }
107
108
        $form = $formBuilder->getForm();
109
        $form->setData($subject);
110
        $form->handleRequest($admin->getRequest());
111
112
        //Child form not found (probably nested one)
113
        //if childFormBuilder was not found resulted in fatal error getName() method call on non object
114
        if (!$childFormBuilder) {
115
            $path = $this->getElementAccessPath($elementId, $subject);
116
117
            $collection = $this->propertyAccessor->getValue($subject, $path);
118
119
            if ($collection instanceof DoctrinePersistentCollection || $collection instanceof PersistentCollection) {
0 ignored issues
show
Bug introduced by
The class Doctrine\ORM\PersistentCollection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Bug introduced by
The class Doctrine\ODM\MongoDB\PersistentCollection does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
120
                //since doctrine 2.4
121
                $modelClassName = $collection->getTypeClass()->getName();
122
            } elseif ($collection instanceof Collection) {
123
                $modelClassName = $this->getModelClassName($admin, explode('.', preg_replace('#\[\d*?\]#', '', $path)));
124
            } else {
125
                throw new \Exception('unknown collection class');
126
            }
127
128
            $collection->add(new $modelClassName());
129
            $this->propertyAccessor->setValue($subject, $path, $collection);
130
131
            $fieldDescription = null;
132
        } else {
133
            // retrieve the FieldDescription
134
            $fieldDescription = $admin->getFormFieldDescription($childFormBuilder->getName());
135
136
            try {
137
                $value = $fieldDescription->getValue($form->getData());
138
            } catch (NoValueException $e) {
139
                $value = null;
140
            }
141
142
            // retrieve the posted data
143
            $data = $admin->getRequest()->get($formBuilder->getName());
144
145
            if (!isset($data[$childFormBuilder->getName()])) {
146
                $data[$childFormBuilder->getName()] = [];
147
            }
148
149
            $objectCount = null === $value ? 0 : \count($value);
150
            $postCount = \count($data[$childFormBuilder->getName()]);
151
152
            $associationAdmin = $fieldDescription->getAssociationAdmin();
153
154
            // add new elements to the subject
155
            while ($objectCount < $postCount) {
156
                // append a new instance into the object
157
                ObjectManipulator::addInstance($form->getData(), $associationAdmin->getNewInstance(), $fieldDescription);
158
                ++$objectCount;
159
            }
160
161
            $newInstance = ObjectManipulator::addInstance($form->getData(), $associationAdmin->getNewInstance(), $fieldDescription);
162
163
            $associationAdmin->setSubject($newInstance);
164
        }
165
166
        $finalForm = $admin->getFormBuilder()->getForm();
167
        $finalForm->setData($subject);
168
169
        // bind the data
170
        $finalForm->setData($form->getData());
171
172
        // back up delete field
173
        if (\count($toDelete) > 0) {
174
            $i = 0;
175
            foreach ($finalForm->get($childFormBuilder->getName()) as $childField) {
176
                if ($childField->has(self::FORM_FIELD_DELETE)) {
177
                    $childField->get(self::FORM_FIELD_DELETE)->setData($toDelete[$i] ?? false);
178
                }
179
                ++$i;
180
            }
181
        }
182
183
        return [$fieldDescription, $finalForm];
184
    }
185
186
    /**
187
     * Get access path to element which works with PropertyAccessor.
188
     *
189
     * @param string $elementId expects string in format used in form id field.
190
     *                          (uniqueIdentifier_model_sub_model or uniqueIdentifier_model_1_sub_model etc.)
191
     * @param mixed  $model
192
     *
193
     * @throws \Exception
194
     */
195
    public function getElementAccessPath(string $elementId, $model): string
196
    {
197
        $idWithoutIdentifier = preg_replace('/^[^_]*_/', '', $elementId);
198
        $initialPath = preg_replace('#(_(\d+)_)#', '[$2]_', $idWithoutIdentifier);
199
200
        $parts = explode('_', $initialPath);
201
        $totalPath = '';
202
        $currentPath = '';
203
204
        foreach ($parts as $part) {
205
            $currentPath .= empty($currentPath) ? $part : '_'.$part;
206
            $separator = empty($totalPath) ? '' : '.';
207
208
            if ($this->propertyAccessor->isReadable($model, $totalPath.$separator.$currentPath)) {
209
                $totalPath .= $separator.$currentPath;
210
                $currentPath = '';
211
            }
212
        }
213
214
        if (!empty($currentPath)) {
215
            throw new \Exception(sprintf(
216
                'Could not get element id from %s Failing part: %s',
217
                $elementId,
218
                $currentPath
219
            ));
220
        }
221
222
        return $totalPath;
223
    }
224
225
    /**
226
     * Recursively find the class name of the admin responsible for the element at the end of an association chain.
227
     */
228
    protected function getModelClassName(AdminInterface $admin, array $elements): string
229
    {
230
        $element = array_shift($elements);
231
        $associationAdmin = $admin->getFormFieldDescription($element)->getAssociationAdmin();
232
        if (0 === \count($elements)) {
233
            return $associationAdmin->getClass();
234
        }
235
236
        return $this->getModelClassName($associationAdmin, $elements);
237
    }
238
}
239