Completed
Push — 3.x ( a5a386...9dc6d5 )
by Christian
02:59
created

BaseGroupedMapper::getTabs()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
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\Mapper;
15
16
use Sonata\AdminBundle\Admin\AbstractAdmin;
17
18
/**
19
 * This class is used to simulate the Form API.
20
 *
21
 * @author Thomas Rabaix <[email protected]>
22
 */
23
abstract class BaseGroupedMapper extends BaseMapper
24
{
25
    /**
26
     * @var string|null
27
     */
28
    protected $currentGroup;
29
30
    /**
31
     * @var string|null
32
     */
33
    protected $currentTab;
34
35
    /**
36
     * @var bool[]
37
     */
38
    protected $apply = [];
39
40
    /**
41
     * Add new group or tab (if parameter "tab=true" is available in options).
42
     *
43
     * @param string $name
44
     *
45
     * @throws \LogicException
46
     *
47
     * @return $this
48
     */
49
    public function with($name, array $options = [])
50
    {
51
        if (!$this->shouldApply()) {
52
            return $this;
53
        }
54
55
        /*
56
         * The current implementation should work with the following workflow:
57
         *
58
         *     $formMapper
59
         *        ->with('group1')
60
         *            ->add('username')
61
         *            ->add('password')
62
         *        ->end()
63
         *        ->with('tab1', ['tab' => true])
64
         *            ->with('group1')
65
         *                ->add('username')
66
         *                ->add('password')
67
         *            ->end()
68
         *            ->with('group2', ['collapsed' => true])
69
         *                ->add('enabled')
70
         *                ->add('createdAt')
71
         *            ->end()
72
         *        ->end();
73
         *
74
         */
75
        $defaultOptions = [
76
            'collapsed' => false,
77
            'class' => false,
78
            'description' => false,
79
            'label' => $name, // NEXT_MAJOR: Remove this line and uncomment the next one
80
//            'label' => $this->admin->getLabelTranslatorStrategy()->getLabel($name, $this->getName(), 'group'),
81
            'translation_domain' => null,
82
            'name' => $name,
83
            'box_class' => 'box box-primary',
84
        ];
85
86
        // NEXT_MAJOR: remove this code
87
        if ($this->admin instanceof AbstractAdmin && $pool = $this->admin->getConfigurationPool()) {
88
            if ($pool->getContainer()->getParameter('sonata.admin.configuration.translate_group_label')) {
89
                $defaultOptions['label'] = $this->admin->getLabelTranslatorStrategy()->getLabel($name, $this->getName(), 'group');
90
            }
91
        }
92
93
        $code = $name;
94
95
        // Open
96
        if (\array_key_exists('tab', $options) && $options['tab']) {
97
            $tabs = $this->getTabs();
98
99
            if ($this->currentTab) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentTab of type string|null is loosely compared to true; 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...
100
                if (isset($tabs[$this->currentTab]['auto_created']) && true === $tabs[$this->currentTab]['auto_created']) {
101
                    throw new \LogicException('New tab was added automatically when you have added field or group. You should close current tab before adding new one OR add tabs before adding groups and fields.');
102
                }
103
104
                throw new \LogicException(sprintf('You should close previous tab "%s" with end() before adding new tab "%s".', $this->currentTab, $name));
105
            } elseif ($this->currentGroup) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentGroup of type string|null is loosely compared to true; 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...
106
                throw new \LogicException(sprintf('You should open tab before adding new group "%s".', $name));
107
            }
108
109
            if (!isset($tabs[$name])) {
110
                $tabs[$name] = [];
111
            }
112
113
            $tabs[$code] = array_merge($defaultOptions, [
114
                'auto_created' => false,
115
                'groups' => [],
116
            ], $tabs[$code], $options);
117
118
            $this->currentTab = $code;
119
        } else {
120
            if ($this->currentGroup) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentGroup of type string|null is loosely compared to true; 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...
121
                throw new \LogicException(sprintf('You should close previous group "%s" with end() before adding new tab "%s".', $this->currentGroup, $name));
122
            }
123
124
            if (!$this->currentTab) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentTab 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...
125
                // no tab define
126
                $this->with('default', [
127
                    'tab' => true,
128
                    'auto_created' => true,
129
                    'translation_domain' => $options['translation_domain'] ?? null,
130
                ]); // add new tab automatically
131
            }
132
133
            // if no tab is selected, we go the the main one named '_' ..
134
            if ('default' !== $this->currentTab) {
135
                $code = $this->currentTab.'.'.$name; // groups with the same name can be on different tabs, so we prefix them in order to make unique group name
136
            }
137
138
            $groups = $this->getGroups();
139
            if (!isset($groups[$code])) {
140
                $groups[$code] = [];
141
            }
142
143
            $groups[$code] = array_merge($defaultOptions, [
144
                'fields' => [],
145
            ], $groups[$code], $options);
146
147
            $this->currentGroup = $code;
148
            $this->setGroups($groups);
149
            $tabs = $this->getTabs();
150
        }
151
152
        if ($this->currentGroup && isset($tabs[$this->currentTab]) && !\in_array($this->currentGroup, $tabs[$this->currentTab]['groups'], true)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentGroup of type string|null is loosely compared to true; 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...
153
            $tabs[$this->currentTab]['groups'][] = $this->currentGroup;
154
        }
155
156
        $this->setTabs($tabs);
157
158
        return $this;
159
    }
160
161
    /**
162
     * Only nested add if the condition match true.
163
     *
164
     * @param bool $bool
165
     *
166
     * @return $this
167
     */
168
    public function ifTrue($bool)
169
    {
170
        $this->apply[] = true === $bool;
171
172
        return $this;
173
    }
174
175
    /**
176
     * Only nested add if the condition match false.
177
     *
178
     * @param bool $bool
179
     *
180
     * @return $this
181
     */
182
    public function ifFalse($bool)
183
    {
184
        $this->apply[] = false === $bool;
185
186
        return $this;
187
    }
188
189
    /**
190
     * @return $this
191
     */
192
    public function ifEnd()
193
    {
194
        array_pop($this->apply);
195
196
        return $this;
197
    }
198
199
    /**
200
     * Add new tab.
201
     *
202
     * @param string $name
203
     *
204
     * @return $this
205
     */
206
    public function tab($name, array $options = [])
207
    {
208
        return $this->with($name, array_merge($options, ['tab' => true]));
209
    }
210
211
    /**
212
     * Close the current group or tab.
213
     *
214
     * @throws \LogicException
215
     *
216
     * @return $this
217
     */
218
    public function end()
219
    {
220
        if (!$this->shouldApply()) {
221
            return $this;
222
        }
223
224
        if (null !== $this->currentGroup) {
225
            $this->currentGroup = null;
226
        } elseif (null !== $this->currentTab) {
227
            $this->currentTab = null;
228
        } else {
229
            throw new \LogicException('No open tabs or groups, you cannot use end()');
230
        }
231
232
        return $this;
233
    }
234
235
    /**
236
     * Returns a boolean indicating if there is an open tab at the moment.
237
     *
238
     * @return bool
239
     */
240
    public function hasOpenTab()
241
    {
242
        return null !== $this->currentTab;
243
    }
244
245
    /**
246
     * @return array
247
     */
248
    abstract protected function getGroups();
249
250
    /**
251
     * @return array
252
     */
253
    abstract protected function getTabs();
254
255
    abstract protected function setGroups(array $groups);
256
257
    abstract protected function setTabs(array $tabs);
258
259
    /**
260
     * NEXT_MAJOR: make this method abstract.
261
     *
262
     * @return string
263
     */
264
    protected function getName()
265
    {
266
        @trigger_error(__METHOD__.' should be implemented and will be abstract in 4.0.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
267
268
        return 'default';
269
    }
270
271
    /**
272
     * Add the field name to the current group.
273
     *
274
     * @param string $fieldName
275
     */
276
    protected function addFieldToCurrentGroup($fieldName)
277
    {
278
        // Note this line must happen before the next line.
279
        // See https://github.com/sonata-project/SonataAdminBundle/pull/1351
280
        $currentGroup = $this->getCurrentGroupName();
281
        $groups = $this->getGroups();
282
        $groups[$currentGroup]['fields'][$fieldName] = $fieldName;
283
        $this->setGroups($groups);
284
285
        return $groups[$currentGroup];
286
    }
287
288
    /**
289
     * Return the name of the currently selected group. The method also makes
290
     * sure a valid group name is currently selected.
291
     *
292
     * Note that this can have the side effect to change the 'group' value
293
     * returned by the getGroup function
294
     *
295
     * @return string
296
     */
297
    protected function getCurrentGroupName()
298
    {
299
        if (!$this->currentGroup) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->currentGroup 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...
300
            $this->with($this->admin->getLabel(), ['auto_created' => true]);
301
        }
302
303
        return $this->currentGroup;
304
    }
305
306
    /**
307
     * Check if all apply conditions are respected.
308
     */
309
    final protected function shouldApply(): bool
310
    {
311
        return !\in_array(false, $this->apply, true);
312
    }
313
}
314