Completed
Push — master ( 57b7f2...4f95ff )
by Grégoire
28:13 queued 01:46
created

FormMapperTest::setUp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 9.0036
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\NoopLabelTranslatorStrategy;
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
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
80
        $securityHandler
81
            ->method('isGranted')
82
            ->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...
83
                return self::DEFAULT_GRANTED_ROLE === $attributes;
84
            });
85
86
        $this->admin->setSecurityHandler($securityHandler);
87
        $this->admin->setFormContractor($this->contractor);
88
89
        $this->modelManager = $this->getMockForAbstractClass(ModelManagerInterface::class);
90
91
        $this->modelManager
92
            ->method('getNewFieldDescriptionInstance')
93
            ->willReturnCallback(function (string $class, string $name, array $options = []): BaseFieldDescription {
94
                $fieldDescription = $this->getFieldDescriptionMock();
95
                $fieldDescription->setName($name);
96
                $fieldDescription->setOptions($options);
97
98
                return $fieldDescription;
99
            });
100
101
        $this->admin->setModelManager($this->modelManager);
102
103
        $this->admin->setLabelTranslatorStrategy(new NoopLabelTranslatorStrategy());
104
105
        $this->formMapper = new FormMapper(
106
            $this->contractor,
107
            $formBuilder,
108
            $this->admin
109
        );
110
    }
111
112
    public function testWithNoOptions(): void
113
    {
114
        $this->formMapper->with('foobar');
115
116
        $this->assertSame(['default' => [
117
            'collapsed' => false,
118
            'class' => false,
119
            'description' => false,
120
            'label' => 'default',
121
            'translation_domain' => null,
122
            'name' => 'default',
123
            'box_class' => 'box box-primary',
124
            'empty_message' => 'message_form_group_empty',
125
            'empty_message_translation_domain' => 'SonataAdminBundle',
126
            'auto_created' => true,
127
            'groups' => ['foobar'],
128
            'tab' => true,
129
        ]], $this->admin->getFormTabs());
130
131
        $this->assertSame(['foobar' => [
132
            'collapsed' => false,
133
            'class' => false,
134
            'description' => false,
135
            'label' => 'foobar',
136
            'translation_domain' => null,
137
            'name' => 'foobar',
138
            'box_class' => 'box box-primary',
139
            'empty_message' => 'message_form_group_empty',
140
            'empty_message_translation_domain' => 'SonataAdminBundle',
141
            'fields' => [],
142
        ]], $this->admin->getFormGroups());
143
    }
144
145
    public function testWithOptions(): void
146
    {
147
        $this->formMapper->with('foobar', [
148
            'translation_domain' => 'Foobar',
149
            'role' => self::DEFAULT_GRANTED_ROLE,
150
        ]);
151
152
        $this->assertSame(['foobar' => [
153
            'collapsed' => false,
154
            'class' => false,
155
            'description' => false,
156
            'label' => 'foobar',
157
            'translation_domain' => 'Foobar',
158
            'name' => 'foobar',
159
            'box_class' => 'box box-primary',
160
            'empty_message' => 'message_form_group_empty',
161
            'empty_message_translation_domain' => 'SonataAdminBundle',
162
            'fields' => [],
163
            'role' => self::DEFAULT_GRANTED_ROLE,
164
        ]], $this->admin->getFormGroups());
165
166
        $this->assertSame(['default' => [
167
            'collapsed' => false,
168
            'class' => false,
169
            'description' => false,
170
            'label' => 'default',
171
            'translation_domain' => 'Foobar',
172
            'name' => 'default',
173
            'box_class' => 'box box-primary',
174
            'empty_message' => 'message_form_group_empty',
175
            'empty_message_translation_domain' => 'SonataAdminBundle',
176
            'auto_created' => true,
177
            'groups' => ['foobar'],
178
            'tab' => true,
179
        ]], $this->admin->getFormTabs());
180
    }
181
182
    public function testWithFieldsCascadeTranslationDomain(): void
183
    {
184
        $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...
185
            ->method('getDefaultOptions')
186
            ->willReturn([]);
187
188
        $this->formMapper->with('foobar', [
189
                'translation_domain' => 'Foobar',
190
            ])
191
            ->add('foo', 'bar')
192
        ->end();
193
194
        $fieldDescription = $this->admin->getFormFieldDescription('foo');
195
        $this->assertSame('foo', $fieldDescription->getName());
196
        $this->assertSame('bar', $fieldDescription->getType());
197
        $this->assertSame('Foobar', $fieldDescription->getTranslationDomain());
198
199
        $this->assertTrue($this->formMapper->has('foo'));
200
201
        $this->assertSame(['default' => [
202
            'collapsed' => false,
203
            'class' => false,
204
            'description' => false,
205
            'label' => 'default',
206
            'translation_domain' => 'Foobar',
207
            'name' => 'default',
208
            'box_class' => 'box box-primary',
209
            'empty_message' => 'message_form_group_empty',
210
            'empty_message_translation_domain' => 'SonataAdminBundle',
211
            'auto_created' => true,
212
            'groups' => ['foobar'],
213
            'tab' => true,
214
        ]], $this->admin->getFormTabs());
215
216
        $this->assertSame(['foobar' => [
217
            'collapsed' => false,
218
            'class' => false,
219
            'description' => false,
220
            'label' => 'foobar',
221
            'translation_domain' => 'Foobar',
222
            'name' => 'foobar',
223
            'box_class' => 'box box-primary',
224
            'empty_message' => 'message_form_group_empty',
225
            'empty_message_translation_domain' => 'SonataAdminBundle',
226
            'fields' => [
227
                'foo' => 'foo',
228
            ],
229
        ]], $this->admin->getFormGroups());
230
    }
231
232
    /**
233
     * @doesNotPerformAssertions
234
     */
235
    public function testRemoveCascadeRemoveFieldFromFormGroup(): void
236
    {
237
        $this->formMapper->with('foo');
238
        $this->formMapper->remove('foo');
239
    }
240
241
    public function testIfTrueApply(): void
242
    {
243
        $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...
244
            ->method('getDefaultOptions')
245
            ->willReturn([]);
246
247
        $this->formMapper
248
            ->ifTrue(true)
249
            ->add('foo', 'bar')
250
            ->ifEnd()
251
        ;
252
253
        $this->assertTrue($this->formMapper->has('foo'));
254
    }
255
256
    public function testIfTrueNotApply(): void
257
    {
258
        $this->formMapper
259
            ->ifTrue(false)
260
            ->add('foo', 'bar')
261
            ->ifEnd()
262
        ;
263
264
        $this->assertFalse($this->formMapper->has('foo'));
265
    }
266
267
    public function testIfTrueCombination(): void
268
    {
269
        $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...
270
            ->method('getDefaultOptions')
271
            ->willReturn([]);
272
273
        $this->formMapper
274
            ->ifTrue(false)
275
            ->add('foo', 'bar')
276
            ->ifEnd()
277
            ->add('baz', 'foobaz')
278
        ;
279
280
        $this->assertFalse($this->formMapper->has('foo'));
281
        $this->assertTrue($this->formMapper->has('baz'));
282
    }
283
284
    public function testIfFalseApply(): void
285
    {
286
        $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...
287
            ->method('getDefaultOptions')
288
            ->willReturn([]);
289
290
        $this->formMapper
291
            ->ifFalse(false)
292
            ->add('foo', 'bar')
293
            ->ifEnd()
294
        ;
295
296
        $this->assertTrue($this->formMapper->has('foo'));
297
    }
298
299
    public function testIfFalseNotApply(): void
300
    {
301
        $this->formMapper
302
            ->ifFalse(true)
303
            ->add('foo', 'bar')
304
            ->ifEnd()
305
        ;
306
307
        $this->assertFalse($this->formMapper->has('foo'));
308
    }
309
310
    public function testIfFalseCombination(): void
311
    {
312
        $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...
313
            ->method('getDefaultOptions')
314
            ->willReturn([]);
315
316
        $this->formMapper
317
            ->ifFalse(true)
318
            ->add('foo', 'bar')
319
            ->ifEnd()
320
            ->add('baz', 'foobaz')
321
        ;
322
323
        $this->assertFalse($this->formMapper->has('foo'));
324
        $this->assertTrue($this->formMapper->has('baz'));
325
    }
326
327
    public function testIfTrueNested(): void
328
    {
329
        $this->formMapper
330
            ->ifTrue(true)
331
                ->ifTrue(true)
332
                    ->add('fooName')
333
                ->ifEnd()
334
            ->ifEnd()
335
        ;
336
337
        $this->assertTrue($this->formMapper->has('fooName'));
338
    }
339
340
    public function testIfFalseNested(): void
341
    {
342
        $this->formMapper
343
            ->ifFalse(false)
344
                ->ifFalse(false)
345
                    ->add('fooName')
346
                ->ifEnd()
347
            ->ifEnd()
348
        ;
349
350
        $this->assertTrue($this->formMapper->has('fooName'));
351
    }
352
353
    public function testIfCombinationNested(): void
354
    {
355
        $this->formMapper
356
            ->ifTrue(true)
357
                ->ifFalse(false)
358
                    ->add('fooName')
359
                ->ifEnd()
360
            ->ifEnd()
361
        ;
362
363
        $this->assertTrue($this->formMapper->has('fooName'));
364
    }
365
366
    public function testIfFalseCombinationNested2(): void
367
    {
368
        $this->formMapper
369
            ->ifFalse(false)
370
                ->ifTrue(true)
371
                    ->add('fooName')
372
                ->ifEnd()
373
            ->ifEnd()
374
        ;
375
376
        $this->assertTrue($this->formMapper->has('fooName'));
377
    }
378
379
    public function testIfFalseCombinationNested3(): void
380
    {
381
        $this->formMapper
382
            ->ifFalse(true)
383
                ->ifTrue(false)
384
                    ->add('fooName')
385
                ->ifEnd()
386
            ->ifEnd()
387
        ;
388
389
        $this->assertFalse($this->formMapper->has('fooName'));
390
    }
391
392
    public function testIfFalseCombinationNested4(): void
393
    {
394
        $this->formMapper
395
            ->ifTrue(false)
396
                ->ifFalse(true)
397
                    ->add('fooName')
398
                ->ifEnd()
399
            ->ifEnd()
400
        ;
401
402
        $this->assertFalse($this->formMapper->has('fooName'));
403
    }
404
405
    public function testAddAcceptFormBuilder(): void
406
    {
407
        $formBuilder = $this
408
            ->getMockBuilder(FormBuilder::class)
409
            ->disableOriginalConstructor()
410
            ->getMock();
411
412
        $formBuilder
413
            ->method('getName')
414
            ->willReturn('foo');
415
416
        $formType = $this
417
            ->getMockBuilder(ResolvedFormTypeInterface::class)
418
            ->getMock();
419
420
        $innerType = $this
421
            ->getMockBuilder(FormType::class)
422
            ->getMock();
423
424
        $formType->expects($this->once())
425
            ->method('getInnerType')
426
            ->willReturn($innerType);
427
428
        $formBuilder->expects($this->once())
429
            ->method('getType')
430
            ->willReturn($formType);
431
432
        $this->formMapper->add($formBuilder);
433
        $this->assertSame($this->formMapper->get('foo'), $formBuilder);
434
    }
435
436
    public function testAddFormBuilderWithType(): void
437
    {
438
        $formBuilder = $this
439
            ->getMockBuilder(FormBuilder::class)
440
            ->disableOriginalConstructor()
441
            ->getMock();
442
443
        $formBuilder
444
            ->method('getName')
445
            ->willReturn('foo');
446
447
        $formBuilder->expects($this->never())
448
            ->method('getType');
449
450
        $this->formMapper->add($formBuilder, FormType::class);
451
        $this->assertSame($this->formMapper->get('foo'), $formBuilder);
452
    }
453
454
    public function testGroupRemovingWithoutTab(): void
455
    {
456
        $this->formMapper->with('foobar');
457
458
        $this->formMapper->removeGroup('foobar');
459
460
        $this->assertSame([], $this->admin->getFormGroups());
461
    }
462
463
    public function testGroupRemovingWithTab(): void
464
    {
465
        $this->formMapper->tab('mytab')->with('foobar');
466
467
        $this->formMapper->removeGroup('foobar', 'mytab');
468
469
        $this->assertSame([], $this->admin->getFormGroups());
470
    }
471
472
    public function testGroupRemovingWithoutTabAndWithTabRemoving(): void
473
    {
474
        $this->formMapper->with('foobar');
475
476
        $this->formMapper->removeGroup('foobar', 'default', true);
477
478
        $this->assertSame([], $this->admin->getFormGroups());
479
        $this->assertSame([], $this->admin->getFormTabs());
480
    }
481
482
    public function testGroupRemovingWithTabAndWithTabRemoving(): void
483
    {
484
        $this->formMapper->tab('mytab')->with('foobar');
485
486
        $this->formMapper->removeGroup('foobar', 'mytab', true);
487
488
        $this->assertSame([], $this->admin->getFormGroups());
489
        $this->assertSame([], $this->admin->getFormTabs());
490
    }
491
492
    public function testKeys(): void
493
    {
494
        $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...
495
            ->method('getDefaultOptions')
496
            ->willReturn([]);
497
498
        $this->formMapper
499
            ->add('foo', 'bar')
500
            ->add('baz', 'foobaz')
501
        ;
502
503
        $this->assertSame(['foo', 'baz'], $this->formMapper->keys());
504
    }
505
506
    public function testFieldNameIsSanitized(): void
507
    {
508
        $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...
509
            ->method('getDefaultOptions')
510
            ->willReturn([]);
511
512
        $this->formMapper
513
            ->add('fo.o', 'bar')
514
            ->add('ba__z', 'foobaz')
515
        ;
516
517
        $this->assertSame(['fo__o', 'ba____z'], $this->formMapper->keys());
518
    }
519
520
    public function testAddOptionRole(): void
521
    {
522
        $this->formMapper->add('bar', 'bar');
523
524
        $this->assertTrue($this->formMapper->has('bar'));
525
526
        $this->formMapper->add('quux', 'bar', [], ['role' => 'ROLE_QUX']);
527
528
        $this->assertTrue($this->formMapper->has('bar'));
529
        $this->assertFalse($this->formMapper->has('quux'));
530
531
        $this->formMapper->end(); // Close default
532
533
        $this->formMapper
534
            ->with('qux')
535
                ->add('foobar', 'bar', [], ['role' => self::DEFAULT_GRANTED_ROLE])
536
                ->add('foo', 'bar', [], ['role' => 'ROLE_QUX'])
537
                ->add('baz', 'bar')
538
            ->end();
539
540
        $this->assertArrayHasKey('qux', $this->admin->getFormGroups());
541
        $this->assertTrue($this->formMapper->has('foobar'));
542
        $this->assertFalse($this->formMapper->has('foo'));
543
        $this->assertTrue($this->formMapper->has('baz'));
544
    }
545
546
    private function getFieldDescriptionMock(
547
        ?string $name = null,
548
        ?string $label = null,
549
        ?string $translationDomain = null
550
    ): BaseFieldDescription {
551
        $fieldDescription = $this->getMockForAbstractClass(BaseFieldDescription::class);
552
553
        if (null !== $name) {
554
            $fieldDescription->setName($name);
555
        }
556
557
        if (null !== $label) {
558
            $fieldDescription->setOption('label', $label);
559
        }
560
561
        if (null !== $translationDomain) {
562
            $fieldDescription->setOption('translation_domain', $translationDomain);
563
        }
564
565
        return $fieldDescription;
566
    }
567
}
568