Completed
Push — 3.x ( 2751ce...1c411a )
by Vincent
03:57
created

FormMapperTest::setUp()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 59
rs 8.8945
c 0
b 0
f 0
cc 1
nc 1
nop 0

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
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\Tests\Form;
15
16
use PHPUnit\Framework\TestCase;
17
use Sonata\AdminBundle\Admin\AdminInterface;
18
use Sonata\AdminBundle\Admin\BaseFieldDescription;
19
use Sonata\AdminBundle\Builder\FormContractorInterface;
20
use Sonata\AdminBundle\Form\FormMapper;
21
use Sonata\AdminBundle\Model\ModelManagerInterface;
22
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
23
use Sonata\AdminBundle\Tests\Fixtures\Admin\CleanAdmin;
24
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
25
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
26
use Symfony\Component\Form\Extension\Core\Type\FormType;
27
use Symfony\Component\Form\FormBuilder;
28
use Symfony\Component\Form\FormFactoryInterface;
29
use Symfony\Component\Form\ResolvedFormTypeInterface;
30
use Symfony\Component\Validator\Mapping\MemberMetadata;
31
use Symfony\Component\Validator\Validator\ValidatorInterface;
32
33
class FormMapperTest extends TestCase
34
{
35
    private const DEFAULT_GRANTED_ROLE = 'ROLE_ADMIN_BAZ';
36
37
    /**
38
     * @var FormContractorInterface
39
     */
40
    protected $contractor;
41
42
    /**
43
     * @var AdminInterface
44
     */
45
    protected $admin;
46
47
    /**
48
     * @var ModelManagerInterface
49
     */
50
    protected $modelManager;
51
52
    /**
53
     * @var FormMapper
54
     */
55
    protected $formMapper;
56
57
    protected function setUp(): void
58
    {
59
        $this->contractor = $this->createMock(FormContractorInterface::class);
60
61
        $formFactory = $this->createMock(FormFactoryInterface::class);
62
        $eventDispatcher = $this->createMock(EventDispatcherInterface::class);
63
64
        $formBuilder = new FormBuilder('test', \stdClass::class, $eventDispatcher, $formFactory);
65
        $formBuilder2 = new FormBuilder('test', \stdClass::class, $eventDispatcher, $formFactory);
66
67
        $formFactory->method('createNamedBuilder')->willReturn($formBuilder);
68
        $this->contractor->method('getFormBuilder')->willReturn($formBuilder2);
69
70
        $this->admin = new CleanAdmin('code', \stdClass::class, 'controller');
71
        $this->admin->setSubject(new \stdClass());
72
73
        $validator = $this->createMock(ValidatorInterface::class);
74
        $validator
75
            ->method('getMetadataFor')
76
            ->willReturn($this->createMock(MemberMetadata::class));
77
        $this->admin->setValidator($validator);
78
79
        // NEXT_MAJOR: Remove the calls to `setFormGroups()` and `setFormTabs()`
80
        $this->admin->setFormGroups([]);
81
        $this->admin->setFormTabs([]);
82
83
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
84
        $securityHandler
85
            ->method('isGranted')
86
            ->willReturnCallback(static function (AdminInterface $admin, string $attributes, $object = null): bool {
0 ignored issues
show
Unused Code introduced by
The parameter $object is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
87
                return self::DEFAULT_GRANTED_ROLE === $attributes;
88
            });
89
90
        $this->admin->setSecurityHandler($securityHandler);
91
        $this->admin->setFormContractor($this->contractor);
92
93
        $this->modelManager = $this->getMockForAbstractClass(ModelManagerInterface::class);
94
95
        $this->modelManager
96
            ->method('getNewFieldDescriptionInstance')
97
            ->willReturnCallback(function (string $class, string $name, array $options = []): BaseFieldDescription {
98
                $fieldDescription = $this->getFieldDescriptionMock();
99
                $fieldDescription->setName($name);
100
                $fieldDescription->setOptions($options);
101
102
                return $fieldDescription;
103
            });
104
105
        $this->admin->setModelManager($this->modelManager);
106
107
        $labelTranslatorStrategy = $this->getMockForAbstractClass(LabelTranslatorStrategyInterface::class);
108
        $this->admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
109
110
        $this->formMapper = new FormMapper(
111
            $this->contractor,
112
            $formBuilder,
113
            $this->admin
114
        );
115
    }
116
117
    public function testWithNoOptions(): void
118
    {
119
        $this->formMapper->with('foobar');
120
121
        $this->assertSame(['default' => [
122
            'collapsed' => false,
123
            'class' => false,
124
            'description' => false,
125
            'label' => 'default',
126
            'translation_domain' => null,
127
            'name' => 'default',
128
            'box_class' => 'box box-primary',
129
            'empty_message' => 'message_form_group_empty',
130
            'empty_message_translation_domain' => 'SonataAdminBundle',
131
            'auto_created' => true,
132
            'groups' => ['foobar'],
133
            'tab' => true,
134
        ]], $this->admin->getFormTabs());
135
136
        $this->assertSame(['foobar' => [
137
            'collapsed' => false,
138
            'class' => false,
139
            'description' => false,
140
            'label' => 'foobar',
141
            'translation_domain' => null,
142
            'name' => 'foobar',
143
            'box_class' => 'box box-primary',
144
            'empty_message' => 'message_form_group_empty',
145
            'empty_message_translation_domain' => 'SonataAdminBundle',
146
            'fields' => [],
147
        ]], $this->admin->getFormGroups());
148
    }
149
150
    public function testWithOptions(): void
151
    {
152
        $this->formMapper->with('foobar', [
153
            'translation_domain' => 'Foobar',
154
            'role' => self::DEFAULT_GRANTED_ROLE,
155
        ]);
156
157
        $this->assertSame(['foobar' => [
158
            'collapsed' => false,
159
            'class' => false,
160
            'description' => false,
161
            'label' => 'foobar',
162
            'translation_domain' => 'Foobar',
163
            'name' => 'foobar',
164
            'box_class' => 'box box-primary',
165
            'empty_message' => 'message_form_group_empty',
166
            'empty_message_translation_domain' => 'SonataAdminBundle',
167
            'fields' => [],
168
            'role' => self::DEFAULT_GRANTED_ROLE,
169
        ]], $this->admin->getFormGroups());
170
171
        $this->assertSame(['default' => [
172
            'collapsed' => false,
173
            'class' => false,
174
            'description' => false,
175
            'label' => 'default',
176
            'translation_domain' => 'Foobar',
177
            'name' => 'default',
178
            'box_class' => 'box box-primary',
179
            'empty_message' => 'message_form_group_empty',
180
            'empty_message_translation_domain' => 'SonataAdminBundle',
181
            'auto_created' => true,
182
            'groups' => ['foobar'],
183
            'tab' => true,
184
        ]], $this->admin->getFormTabs());
185
    }
186
187
    public function testWithFieldsCascadeTranslationDomain(): void
188
    {
189
        $this->contractor->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
190
            ->method('getDefaultOptions')
191
            ->willReturn([]);
192
193
        $this->formMapper->with('foobar', [
194
                'translation_domain' => 'Foobar',
195
            ])
196
            ->add('foo', 'bar')
197
        ->end();
198
199
        $fieldDescription = $this->admin->getFormFieldDescription('foo');
200
        $this->assertSame('foo', $fieldDescription->getName());
201
        $this->assertSame('bar', $fieldDescription->getType());
202
        $this->assertSame('Foobar', $fieldDescription->getTranslationDomain());
203
204
        $this->assertTrue($this->formMapper->has('foo'));
205
206
        $this->assertSame(['default' => [
207
            'collapsed' => false,
208
            'class' => false,
209
            'description' => false,
210
            'label' => 'default',
211
            'translation_domain' => 'Foobar',
212
            'name' => 'default',
213
            'box_class' => 'box box-primary',
214
            'empty_message' => 'message_form_group_empty',
215
            'empty_message_translation_domain' => 'SonataAdminBundle',
216
            'auto_created' => true,
217
            'groups' => ['foobar'],
218
            'tab' => true,
219
        ]], $this->admin->getFormTabs());
220
221
        $this->assertSame(['foobar' => [
222
            'collapsed' => false,
223
            'class' => false,
224
            'description' => false,
225
            'label' => 'foobar',
226
            'translation_domain' => 'Foobar',
227
            'name' => 'foobar',
228
            'box_class' => 'box box-primary',
229
            'empty_message' => 'message_form_group_empty',
230
            'empty_message_translation_domain' => 'SonataAdminBundle',
231
            'fields' => [
232
                'foo' => 'foo',
233
            ],
234
        ]], $this->admin->getFormGroups());
235
    }
236
237
    /**
238
     * @doesNotPerformAssertions
239
     */
240
    public function testRemoveCascadeRemoveFieldFromFormGroup(): void
241
    {
242
        $this->formMapper->with('foo');
243
        $this->formMapper->remove('foo');
244
    }
245
246
    public function testIfTrueApply(): void
247
    {
248
        $this->contractor->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
249
            ->method('getDefaultOptions')
250
            ->willReturn([]);
251
252
        $this->formMapper
253
            ->ifTrue(true)
254
            ->add('foo', 'bar')
255
            ->ifEnd()
256
        ;
257
258
        $this->assertTrue($this->formMapper->has('foo'));
259
    }
260
261
    public function testIfTrueNotApply(): void
262
    {
263
        $this->formMapper
264
            ->ifTrue(false)
265
            ->add('foo', 'bar')
266
            ->ifEnd()
267
        ;
268
269
        $this->assertFalse($this->formMapper->has('foo'));
270
    }
271
272
    public function testIfTrueCombination(): void
273
    {
274
        $this->contractor->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
275
            ->method('getDefaultOptions')
276
            ->willReturn([]);
277
278
        $this->formMapper
279
            ->ifTrue(false)
280
            ->add('foo', 'bar')
281
            ->ifEnd()
282
            ->add('baz', 'foobaz')
283
        ;
284
285
        $this->assertFalse($this->formMapper->has('foo'));
286
        $this->assertTrue($this->formMapper->has('baz'));
287
    }
288
289
    public function testIfFalseApply(): void
290
    {
291
        $this->contractor->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
292
            ->method('getDefaultOptions')
293
            ->willReturn([]);
294
295
        $this->formMapper
296
            ->ifFalse(false)
297
            ->add('foo', 'bar')
298
            ->ifEnd()
299
        ;
300
301
        $this->assertTrue($this->formMapper->has('foo'));
302
    }
303
304
    public function testIfFalseNotApply(): void
305
    {
306
        $this->formMapper
307
            ->ifFalse(true)
308
            ->add('foo', 'bar')
309
            ->ifEnd()
310
        ;
311
312
        $this->assertFalse($this->formMapper->has('foo'));
313
    }
314
315
    public function testIfFalseCombination(): void
316
    {
317
        $this->contractor->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
318
            ->method('getDefaultOptions')
319
            ->willReturn([]);
320
321
        $this->formMapper
322
            ->ifFalse(true)
323
            ->add('foo', 'bar')
324
            ->ifEnd()
325
            ->add('baz', 'foobaz')
326
        ;
327
328
        $this->assertFalse($this->formMapper->has('foo'));
329
        $this->assertTrue($this->formMapper->has('baz'));
330
    }
331
332
    public function testIfTrueNested(): void
333
    {
334
        $this->formMapper
335
            ->ifTrue(true)
336
                ->ifTrue(true)
337
                    ->add('fooName')
338
                ->ifEnd()
339
            ->ifEnd()
340
        ;
341
342
        $this->assertTrue($this->formMapper->has('fooName'));
343
    }
344
345
    public function testIfFalseNested(): void
346
    {
347
        $this->formMapper
348
            ->ifFalse(false)
349
                ->ifFalse(false)
350
                    ->add('fooName')
351
                ->ifEnd()
352
            ->ifEnd()
353
        ;
354
355
        $this->assertTrue($this->formMapper->has('fooName'));
356
    }
357
358
    public function testIfCombinationNested(): void
359
    {
360
        $this->formMapper
361
            ->ifTrue(true)
362
                ->ifFalse(false)
363
                    ->add('fooName')
364
                ->ifEnd()
365
            ->ifEnd()
366
        ;
367
368
        $this->assertTrue($this->formMapper->has('fooName'));
369
    }
370
371
    public function testIfFalseCombinationNested2(): void
372
    {
373
        $this->formMapper
374
            ->ifFalse(false)
375
                ->ifTrue(true)
376
                    ->add('fooName')
377
                ->ifEnd()
378
            ->ifEnd()
379
        ;
380
381
        $this->assertTrue($this->formMapper->has('fooName'));
382
    }
383
384
    public function testIfFalseCombinationNested3(): void
385
    {
386
        $this->formMapper
387
            ->ifFalse(true)
388
                ->ifTrue(false)
389
                    ->add('fooName')
390
                ->ifEnd()
391
            ->ifEnd()
392
        ;
393
394
        $this->assertFalse($this->formMapper->has('fooName'));
395
    }
396
397
    public function testIfFalseCombinationNested4(): void
398
    {
399
        $this->formMapper
400
            ->ifTrue(false)
401
                ->ifFalse(true)
402
                    ->add('fooName')
403
                ->ifEnd()
404
            ->ifEnd()
405
        ;
406
407
        $this->assertFalse($this->formMapper->has('fooName'));
408
    }
409
410
    public function testAddAcceptFormBuilder(): void
411
    {
412
        $formBuilder = $this
413
            ->getMockBuilder(FormBuilder::class)
414
            ->disableOriginalConstructor()
415
            ->getMock();
416
417
        $formBuilder
418
            ->method('getName')
419
            ->willReturn('foo');
420
421
        $formType = $this
422
            ->getMockBuilder(ResolvedFormTypeInterface::class)
423
            ->getMock();
424
425
        $innerType = $this
426
            ->getMockBuilder(FormType::class)
427
            ->getMock();
428
429
        $formType->expects($this->once())
430
            ->method('getInnerType')
431
            ->willReturn($innerType);
432
433
        $formBuilder->expects($this->once())
434
            ->method('getType')
435
            ->willReturn($formType);
436
437
        $this->formMapper->add($formBuilder);
438
        $this->assertSame($this->formMapper->get('foo'), $formBuilder);
439
    }
440
441
    public function testAddFormBuilderWithType(): void
442
    {
443
        $formBuilder = $this
444
            ->getMockBuilder(FormBuilder::class)
445
            ->disableOriginalConstructor()
446
            ->getMock();
447
448
        $formBuilder
449
            ->method('getName')
450
            ->willReturn('foo');
451
452
        $formBuilder->expects($this->never())
453
            ->method('getType');
454
455
        $this->formMapper->add($formBuilder, FormType::class);
456
        $this->assertSame($this->formMapper->get('foo'), $formBuilder);
457
    }
458
459
    public function testGroupRemovingWithoutTab(): void
460
    {
461
        $this->formMapper->with('foobar');
462
463
        $this->formMapper->removeGroup('foobar');
464
465
        $this->assertSame([], $this->admin->getFormGroups());
466
    }
467
468
    public function testGroupRemovingWithTab(): void
469
    {
470
        $this->formMapper->tab('mytab')->with('foobar');
471
472
        $this->formMapper->removeGroup('foobar', 'mytab');
473
474
        $this->assertSame([], $this->admin->getFormGroups());
475
    }
476
477
    public function testGroupRemovingWithoutTabAndWithTabRemoving(): void
478
    {
479
        $this->formMapper->with('foobar');
480
481
        $this->formMapper->removeGroup('foobar', 'default', true);
482
483
        $this->assertSame([], $this->admin->getFormGroups());
484
        $this->assertSame([], $this->admin->getFormTabs());
485
    }
486
487
    public function testGroupRemovingWithTabAndWithTabRemoving(): void
488
    {
489
        $this->formMapper->tab('mytab')->with('foobar');
490
491
        $this->formMapper->removeGroup('foobar', 'mytab', true);
492
493
        $this->assertSame([], $this->admin->getFormGroups());
494
        $this->assertSame([], $this->admin->getFormTabs());
495
    }
496
497
    public function testKeys(): void
498
    {
499
        $this->contractor
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
500
            ->method('getDefaultOptions')
501
            ->willReturn([]);
502
503
        $this->formMapper
504
            ->add('foo', 'bar')
505
            ->add('baz', 'foobaz')
506
        ;
507
508
        $this->assertSame(['foo', 'baz'], $this->formMapper->keys());
509
    }
510
511
    public function testFieldNameIsSanitized(): void
512
    {
513
        $this->contractor
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<Sonata\AdminBundl...ormContractorInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
514
            ->method('getDefaultOptions')
515
            ->willReturn([]);
516
517
        $this->formMapper
518
            ->add('fo.o', 'bar')
519
            ->add('ba__z', 'foobaz')
520
        ;
521
522
        $this->assertSame(['fo__o', 'ba____z'], $this->formMapper->keys());
523
    }
524
525
    public function testAddOptionRole(): void
526
    {
527
        $this->formMapper->add('bar', 'bar');
528
529
        $this->assertTrue($this->formMapper->has('bar'));
530
531
        $this->formMapper->add('quux', 'bar', [], ['role' => 'ROLE_QUX']);
532
533
        $this->assertTrue($this->formMapper->has('bar'));
534
        $this->assertFalse($this->formMapper->has('quux'));
535
536
        $this->formMapper
537
            ->with('qux')
538
                ->add('foobar', 'bar', [], ['role' => self::DEFAULT_GRANTED_ROLE])
539
                ->add('foo', 'bar', [], ['role' => 'ROLE_QUX'])
540
                ->add('baz', 'bar')
541
            ->end();
542
543
        $this->assertArrayHasKey('qux', $this->admin->getFormGroups());
544
        $this->assertTrue($this->formMapper->has('foobar'));
545
        $this->assertFalse($this->formMapper->has('foo'));
546
        $this->assertTrue($this->formMapper->has('baz'));
547
    }
548
549
    private function getFieldDescriptionMock(
550
        ?string $name = null,
551
        ?string $label = null,
552
        ?string $translationDomain = null
553
    ): BaseFieldDescription {
554
        $fieldDescription = $this->getMockForAbstractClass(BaseFieldDescription::class);
555
556
        if (null !== $name) {
557
            $fieldDescription->setName($name);
558
        }
559
560
        if (null !== $label) {
561
            $fieldDescription->setOption('label', $label);
562
        }
563
564
        if (null !== $translationDomain) {
565
            $fieldDescription->setOption('translation_domain', $translationDomain);
566
        }
567
568
        return $fieldDescription;
569
    }
570
}
571