Completed
Pull Request — master (#6210)
by Jordi Sala
02:41
created

AdminTest::testDefaultFilters()   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\Admin;
15
16
use Doctrine\Common\Collections\Collection;
17
use Knp\Menu\FactoryInterface;
18
use Knp\Menu\ItemInterface;
19
use PHPUnit\Framework\TestCase;
20
use Sonata\AdminBundle\Admin\AbstractAdmin;
21
use Sonata\AdminBundle\Admin\AbstractAdminExtension;
22
use Sonata\AdminBundle\Admin\AdminExtensionInterface;
23
use Sonata\AdminBundle\Admin\AdminInterface;
24
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
25
use Sonata\AdminBundle\Admin\Pool;
26
use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
27
use Sonata\AdminBundle\Builder\FormContractorInterface;
28
use Sonata\AdminBundle\Builder\ListBuilderInterface;
29
use Sonata\AdminBundle\Builder\RouteBuilderInterface;
30
use Sonata\AdminBundle\Builder\ShowBuilderInterface;
31
use Sonata\AdminBundle\Datagrid\DatagridInterface;
32
use Sonata\AdminBundle\Datagrid\PagerInterface;
33
use Sonata\AdminBundle\Filter\Persister\FilterPersisterInterface;
34
use Sonata\AdminBundle\Model\AuditManagerInterface;
35
use Sonata\AdminBundle\Model\ModelManagerInterface;
36
use Sonata\AdminBundle\Route\DefaultRouteGenerator;
37
use Sonata\AdminBundle\Route\PathInfoBuilder;
38
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
39
use Sonata\AdminBundle\Route\RoutesCache;
40
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
41
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
42
use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface;
43
use Sonata\AdminBundle\Tests\App\Builder\DatagridBuilder;
44
use Sonata\AdminBundle\Tests\App\Builder\FormContractor;
45
use Sonata\AdminBundle\Tests\App\Builder\ListBuilder;
46
use Sonata\AdminBundle\Tests\App\Builder\ShowBuilder;
47
use Sonata\AdminBundle\Tests\Fixtures\Admin\AvoidInfiniteLoopAdmin;
48
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentAdmin;
49
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentVoteAdmin;
50
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentWithCustomRouteAdmin;
51
use Sonata\AdminBundle\Tests\Fixtures\Admin\FieldDescription;
52
use Sonata\AdminBundle\Tests\Fixtures\Admin\FilteredAdmin;
53
use Sonata\AdminBundle\Tests\Fixtures\Admin\ModelAdmin;
54
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostAdmin;
55
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostCategoryAdmin;
56
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostWithCustomRouteAdmin;
57
use Sonata\AdminBundle\Tests\Fixtures\Admin\TagAdmin;
58
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\BlogPost;
59
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Comment;
60
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Post;
61
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\PostCategory;
62
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Tag;
63
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToString;
64
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToStringNull;
65
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
66
use Sonata\AdminBundle\Translator\UnderscoreLabelTranslatorStrategy;
67
use Sonata\Doctrine\Adapter\AdapterInterface;
68
use Sonata\Exporter\Source\ArraySourceIterator;
69
use Symfony\Component\Filesystem\Filesystem;
70
use Symfony\Component\Form\FormBuilder;
71
use Symfony\Component\Form\FormBuilderInterface;
72
use Symfony\Component\Form\FormEvent;
73
use Symfony\Component\Form\FormEvents;
74
use Symfony\Component\Form\FormFactory;
75
use Symfony\Component\Form\FormRegistry;
76
use Symfony\Component\Form\ResolvedFormTypeFactory;
77
use Symfony\Component\HttpFoundation\ParameterBag;
78
use Symfony\Component\HttpFoundation\Request;
79
use Symfony\Component\PropertyAccess\PropertyAccess;
80
use Symfony\Component\Routing\RouterInterface;
81
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
82
use Symfony\Component\Validator\Mapping\MemberMetadata;
83
use Symfony\Component\Validator\Mapping\PropertyMetadataInterface;
84
use Symfony\Component\Validator\Validator\ValidatorInterface;
85
use Symfony\Contracts\Translation\TranslatorInterface;
86
87
class AdminTest extends TestCase
88
{
89
    protected $cacheTempFolder;
90
91
    protected function setUp(): void
92
    {
93
        $this->cacheTempFolder = sprintf('%s/sonata_test_route', sys_get_temp_dir());
94
        $filesystem = new Filesystem();
95
        $filesystem->remove($this->cacheTempFolder);
96
    }
97
98
    /**
99
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
100
     */
101
    public function testConstructor(): void
102
    {
103
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
104
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
105
106
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
107
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
108
        $this->assertSame($class, $admin->getClass());
109
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
110
    }
111
112
    public function testGetClass(): void
113
    {
114
        $class = Post::class;
115
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
116
117
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
118
119
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
120
121
        $admin->setSubject(new BlogPost());
122
        $this->assertSame(BlogPost::class, $admin->getClass());
123
124
        $admin->setSubClasses(['foo']);
125
        $this->assertSame(BlogPost::class, $admin->getClass());
126
127
        $admin->setSubject(null);
128
        $admin->setSubClasses([]);
129
        $this->assertSame($class, $admin->getClass());
130
131
        $admin->setSubClasses(['foo' => 'bar']);
132
        $admin->setRequest(new Request(['subclass' => 'foo']));
133
        $this->assertSame('bar', $admin->getClass());
134
    }
135
136
    public function testGetClassException(): void
137
    {
138
        $this->expectException(\RuntimeException::class);
139
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
140
141
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
142
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
143
144
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
145
        $admin->setParentFieldDescription(new FieldDescription());
146
        $admin->setSubClasses(['foo' => 'bar']);
147
        $admin->setRequest(new Request(['subclass' => 'foo']));
148
        $admin->getClass();
149
    }
150
151
    public function testCheckAccessThrowsExceptionOnMadeUpAction(): void
152
    {
153
        $admin = new PostAdmin(
154
            'sonata.post.admin.post',
155
            'Application\Sonata\NewsBundle\Entity\Post',
156
            'Sonata\NewsBundle\Controller\PostAdminController'
157
        );
158
        $this->expectException(
159
            \InvalidArgumentException::class
160
        );
161
        $this->expectExceptionMessage(
162
            'Action "made-up" could not be found'
163
        );
164
        $admin->checkAccess('made-up');
165
    }
166
167
    public function testCheckAccessThrowsAccessDeniedException(): void
168
    {
169
        $admin = new PostAdmin(
170
            'sonata.post.admin.post',
171
            'Application\Sonata\NewsBundle\Entity\Post',
172
            'Sonata\NewsBundle\Controller\PostAdminController'
173
        );
174
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
175
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
176
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
177
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
178
        $customExtension->getAccessMapping($admin)->willReturn(
179
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
180
        );
181
        $admin->addExtension($customExtension->reveal());
182
        $admin->setSecurityHandler($securityHandler->reveal());
183
        $this->expectException(
184
            AccessDeniedException::class
185
        );
186
        $this->expectExceptionMessage(
187
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
188
        );
189
        $admin->checkAccess('custom_action');
190
    }
191
192
    public function testHasAccessOnMadeUpAction(): void
193
    {
194
        $admin = new PostAdmin(
195
            'sonata.post.admin.post',
196
            'Application\Sonata\NewsBundle\Entity\Post',
197
            'Sonata\NewsBundle\Controller\PostAdminController'
198
        );
199
200
        $this->assertFalse($admin->hasAccess('made-up'));
201
    }
202
203
    public function testHasAccess(): void
204
    {
205
        $admin = new PostAdmin(
206
            'sonata.post.admin.post',
207
            'Application\Sonata\NewsBundle\Entity\Post',
208
            'Sonata\NewsBundle\Controller\PostAdminController'
209
        );
210
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
211
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
212
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
213
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
214
        $customExtension->getAccessMapping($admin)->willReturn(
215
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
216
        );
217
        $admin->addExtension($customExtension->reveal());
218
        $admin->setSecurityHandler($securityHandler->reveal());
219
220
        $this->assertFalse($admin->hasAccess('custom_action'));
221
    }
222
223
    public function testHasAccessAllowsAccess(): void
224
    {
225
        $admin = new PostAdmin(
226
            'sonata.post.admin.post',
227
            'Application\Sonata\NewsBundle\Entity\Post',
228
            'Sonata\NewsBundle\Controller\PostAdminController'
229
        );
230
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
231
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
232
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
233
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
234
        $customExtension->getAccessMapping($admin)->willReturn(
235
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
236
        );
237
        $admin->addExtension($customExtension->reveal());
238
        $admin->setSecurityHandler($securityHandler->reveal());
239
240
        $this->assertTrue($admin->hasAccess('custom_action'));
241
    }
242
243
    public function testHasAccessAllowsAccessEditAction(): void
244
    {
245
        $admin = new PostAdmin(
246
            'sonata.post.admin.post',
247
            'Application\Sonata\NewsBundle\Entity\Post',
248
            'Sonata\NewsBundle\Controller\PostAdminController'
249
        );
250
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
251
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
252
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
253
        $customExtension->getAccessMapping($admin)->willReturn(
254
            ['edit_action' => ['EDIT_ROLE']]
255
        );
256
        $admin->addExtension($customExtension->reveal());
257
        $admin->setSecurityHandler($securityHandler->reveal());
258
259
        $this->assertTrue($admin->hasAccess('edit_action'));
260
    }
261
262
    /**
263
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
264
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
265
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
266
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
267
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
268
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
269
     */
270
    public function testChildren(): void
271
    {
272
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
273
        $this->assertFalse($postAdmin->hasChildren());
274
        $this->assertFalse($postAdmin->hasChild('comment'));
275
276
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
277
        $postAdmin->addChild($commentAdmin, 'post');
278
279
        $this->assertTrue($postAdmin->hasChildren());
280
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
281
282
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
283
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
284
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
285
        $this->assertSame('post', $commentAdmin->getParentAssociationMapping());
286
287
        $this->assertFalse($postAdmin->isChild());
288
        $this->assertTrue($commentAdmin->isChild());
289
290
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
291
    }
292
293
    /**
294
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
295
     */
296
    public function testConfigure(): void
297
    {
298
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
299
        $this->assertNotNull($admin->getUniqid());
300
301
        $admin->initialize();
302
        $this->assertNotNull($admin->getUniqid());
303
        $this->assertSame('Post', $admin->getClassnameLabel());
304
305
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
306
        $admin->setClassnameLabel('postcomment');
307
308
        $admin->initialize();
309
        $this->assertSame('postcomment', $admin->getClassnameLabel());
310
    }
311
312
    public function testConfigureWithValidParentAssociationMapping(): void
313
    {
314
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
315
316
        $comment = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
317
        $comment->addChild($admin, 'comment');
318
319
        $admin->initialize();
320
321
        $this->assertSame('comment', $admin->getParentAssociationMapping());
322
    }
323
324
    public function provideGetBaseRoutePattern()
325
    {
326
        return [
327
            [
328
                'Application\Sonata\NewsBundle\Entity\Post',
329
                '/sonata/news/post',
330
            ],
331
            [
332
                'Application\Sonata\NewsBundle\Document\Post',
333
                '/sonata/news/post',
334
            ],
335
            [
336
                'MyApplication\MyBundle\Entity\Post',
337
                '/myapplication/my/post',
338
            ],
339
            [
340
                'MyApplication\MyBundle\Entity\Post\Category',
341
                '/myapplication/my/post-category',
342
            ],
343
            [
344
                'MyApplication\MyBundle\Entity\Product\Category',
345
                '/myapplication/my/product-category',
346
            ],
347
            [
348
                'MyApplication\MyBundle\Entity\Other\Product\Category',
349
                '/myapplication/my/other-product-category',
350
            ],
351
            [
352
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
353
                '/cmf/foo/menu',
354
            ],
355
            [
356
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
357
                '/cmf/foo/menu',
358
            ],
359
            [
360
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
361
                '/symfony/barbar/menu',
362
            ],
363
            [
364
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
365
                '/symfony/barbar/menu-item',
366
            ],
367
            [
368
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
369
                '/cmf/foo/menu',
370
            ],
371
            [
372
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
373
                '/cmf/foo/menu',
374
            ],
375
            [
376
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
377
                '/cmf/foo/menu',
378
            ],
379
            [
380
                'AppBundle\Entity\User',
381
                '/app/user',
382
            ],
383
            [
384
                'App\Entity\User',
385
                '/app/user',
386
            ],
387
        ];
388
    }
389
390
    /**
391
     * @dataProvider provideGetBaseRoutePattern
392
     */
393
    public function testGetBaseRoutePattern(string $objFqn, string $expected): void
394
    {
395
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
396
        $this->assertSame($expected, $admin->getBaseRoutePattern());
397
    }
398
399
    /**
400
     * @dataProvider provideGetBaseRoutePattern
401
     */
402
    public function testGetBaseRoutePatternWithChildAdmin(string $objFqn, string $expected): void
403
    {
404
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
405
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
406
        $commentAdmin->setParent($postAdmin);
407
408
        $this->assertSame(sprintf('%s/{id}/comment', $expected), $commentAdmin->getBaseRoutePattern());
409
    }
410
411
    /**
412
     * @dataProvider provideGetBaseRoutePattern
413
     */
414
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin(string $objFqn, string $expected): void
415
    {
416
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
417
        $commentAdmin = new CommentAdmin(
418
            'sonata.post.admin.comment',
419
            'Application\Sonata\NewsBundle\Entity\Comment',
420
            'Sonata\NewsBundle\Controller\CommentAdminController'
421
        );
422
        $commentVoteAdmin = new CommentVoteAdmin(
423
            'sonata.post.admin.comment_vote',
424
            'Application\Sonata\NewsBundle\Entity\CommentVote',
425
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
426
        );
427
        $commentAdmin->setParent($postAdmin);
428
        $commentVoteAdmin->setParent($commentAdmin);
429
430
        $this->assertSame(sprintf('%s/{id}/comment/{childId}/commentvote', $expected), $commentVoteAdmin->getBaseRoutePattern());
431
    }
432
433
    public function testGetBaseRoutePatternWithSpecifedPattern(): void
434
    {
435
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostWithCustomRouteAdminController');
436
437
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
438
    }
439
440
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern(): void
441
    {
442
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
443
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController');
444
        $commentAdmin->setParent($postAdmin);
445
446
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
447
    }
448
449
    public function testGetBaseRoutePatternWithUnreconizedClassname(): void
450
    {
451
        $this->expectException(\RuntimeException::class);
452
453
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
454
        $admin->getBaseRoutePattern();
455
    }
456
457
    public function provideGetBaseRouteName()
458
    {
459
        return [
460
            [
461
                'Application\Sonata\NewsBundle\Entity\Post',
462
                'admin_sonata_news_post',
463
            ],
464
            [
465
                'Application\Sonata\NewsBundle\Document\Post',
466
                'admin_sonata_news_post',
467
            ],
468
            [
469
                'MyApplication\MyBundle\Entity\Post',
470
                'admin_myapplication_my_post',
471
            ],
472
            [
473
                'MyApplication\MyBundle\Entity\Post\Category',
474
                'admin_myapplication_my_post_category',
475
            ],
476
            [
477
                'MyApplication\MyBundle\Entity\Product\Category',
478
                'admin_myapplication_my_product_category',
479
            ],
480
            [
481
                'MyApplication\MyBundle\Entity\Other\Product\Category',
482
                'admin_myapplication_my_other_product_category',
483
            ],
484
            [
485
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
486
                'admin_cmf_foo_menu',
487
            ],
488
            [
489
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
490
                'admin_cmf_foo_menu',
491
            ],
492
            [
493
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
494
                'admin_symfony_barbar_menu',
495
            ],
496
            [
497
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
498
                'admin_symfony_barbar_menu_item',
499
            ],
500
            [
501
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
502
                'admin_cmf_foo_menu',
503
            ],
504
            [
505
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
506
                'admin_cmf_foo_menu',
507
            ],
508
            [
509
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
510
                'admin_cmf_foo_menu',
511
            ],
512
            [
513
                'AppBundle\Entity\User',
514
                'admin_app_user',
515
            ],
516
            [
517
                'App\Entity\User',
518
                'admin_app_user',
519
            ],
520
        ];
521
    }
522
523
    /**
524
     * @dataProvider provideGetBaseRouteName
525
     */
526
    public function testGetBaseRouteName(string $objFqn, string $expected): void
527
    {
528
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
529
530
        $this->assertSame($expected, $admin->getBaseRouteName());
531
    }
532
533
    public function testGetBaseRouteNameWithUnreconizedClassname(): void
534
    {
535
        $this->expectException(\RuntimeException::class);
536
537
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
538
        $admin->getBaseRouteName();
539
    }
540
541
    public function testGetBaseRouteNameWithSpecifiedName(): void
542
    {
543
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
544
545
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
546
    }
547
548
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName(): void
549
    {
550
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
551
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController');
552
        $commentAdmin->setParent($postAdmin);
553
554
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
555
    }
556
557
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName(): void
558
    {
559
        $postAdmin = new PostAdmin(
560
            'sonata.post.admin.post',
561
            'Application\Sonata\NewsBundle\Entity\Post',
562
            'Sonata\NewsBundle\Controller\PostAdminController'
563
        );
564
        $commentAdmin = new CommentWithCustomRouteAdmin(
565
            'sonata.post.admin.comment_with_custom_route',
566
            'Application\Sonata\NewsBundle\Entity\Comment',
567
            'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController'
568
        );
569
        $commentVoteAdmin = new CommentVoteAdmin(
570
            'sonata.post.admin.comment_vote',
571
            'Application\Sonata\NewsBundle\Entity\CommentVote',
572
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
573
        );
574
        $commentAdmin->setParent($postAdmin);
575
        $commentVoteAdmin->setParent($commentAdmin);
576
577
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
578
    }
579
580
    /**
581
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
582
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
583
     */
584
    public function testSetUniqid(): void
585
    {
586
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
587
588
        $uniqid = uniqid();
589
        $admin->setUniqid($uniqid);
590
591
        $this->assertSame($uniqid, $admin->getUniqid());
592
    }
593
594
    public function testToString(): void
595
    {
596
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
597
598
        $s = new \stdClass();
599
600
        $this->assertNotEmpty($admin->toString($s));
601
602
        $s = new FooToString();
603
        $this->assertSame('salut', $admin->toString($s));
604
605
        // To string method is implemented, but returns null
606
        $s = new FooToStringNull();
607
        $this->assertNotEmpty($admin->toString($s));
608
609
        $this->assertSame('', $admin->toString(false));
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
610
    }
611
612
    public function testIsAclEnabled(): void
613
    {
614
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
615
616
        $this->assertFalse($postAdmin->isAclEnabled());
617
618
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
619
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
620
        $this->assertTrue($commentAdmin->isAclEnabled());
621
    }
622
623
    /**
624
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
625
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
626
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
627
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
628
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
629
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
630
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
631
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
632
     */
633
    public function testSubClass(): void
634
    {
635
        $admin = new PostAdmin(
636
            'sonata.post.admin.post',
637
            Post::class,
638
            'Sonata\NewsBundle\Controller\PostAdminController'
639
        );
640
        $this->assertFalse($admin->hasSubClass('test'));
641
        $this->assertFalse($admin->hasActiveSubClass());
642
        $this->assertCount(0, $admin->getSubClasses());
643
        $this->assertSame(Post::class, $admin->getClass());
644
645
        // Just for the record, if there is no inheritance set, the getSubject is not used
646
        // the getSubject can also lead to some issue
647
        $admin->setSubject(new BlogPost());
648
        $this->assertSame(BlogPost::class, $admin->getClass());
649
650
        $admin->setSubClasses([
651
            'extended1' => 'NewsBundle\Entity\PostExtended1',
652
            'extended2' => 'NewsBundle\Entity\PostExtended2',
653
        ]);
654
        $this->assertFalse($admin->hasSubClass('test'));
655
        $this->assertTrue($admin->hasSubClass('extended1'));
656
        $this->assertFalse($admin->hasActiveSubClass());
657
        $this->assertCount(2, $admin->getSubClasses());
658
        $this->assertSame(
659
            BlogPost::class,
660
            $admin->getClass(),
661
            'When there is no subclass in the query the class parameter should be returned'
662
        );
663
664
        $request = new Request(['subclass' => 'extended1']);
665
        $admin->setRequest($request);
666
        $this->assertFalse($admin->hasSubClass('test'));
667
        $this->assertTrue($admin->hasSubClass('extended1'));
668
        $this->assertTrue($admin->hasActiveSubClass());
669
        $this->assertCount(2, $admin->getSubClasses());
670
        $this->assertSame(
671
            'NewsBundle\Entity\PostExtended1',
672
            $admin->getActiveSubClass(),
673
            'It should return the curently active sub class.'
674
        );
675
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
676
        $this->assertSame(
677
            'NewsBundle\Entity\PostExtended1',
678
            $admin->getClass(),
679
            'getClass() should return the name of the sub class when passed through a request query parameter.'
680
        );
681
682
        $request->query->set('subclass', 'inject');
683
684
        $this->expectException(\LogicException::class);
685
        $this->expectExceptionMessage(sprintf('Admin "%s" has no active subclass.', PostAdmin::class));
686
687
        $admin->getActiveSubclassCode();
688
    }
689
690
    public function testNonExistantSubclass(): void
691
    {
692
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
693
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
694
695
        $admin->setRequest(new Request(['subclass' => 'inject']));
696
697
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
698
699
        $this->assertTrue($admin->hasActiveSubClass());
700
701
        $this->expectException(\LogicException::class);
702
703
        $admin->getActiveSubClass();
704
    }
705
706
    /**
707
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
708
     */
709
    public function testOnlyOneSubclassNeededToBeActive(): void
710
    {
711
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
712
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
713
        $request = new Request(['subclass' => 'extended1']);
714
        $admin->setRequest($request);
715
        $this->assertTrue($admin->hasActiveSubClass());
716
    }
717
718
    public function testGetLabelTranslatorStrategy(): void
719
    {
720
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
721
722
        $this->assertNull($admin->getLabelTranslatorStrategy());
723
724
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
725
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
726
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
727
    }
728
729
    public function testGetRouteBuilder(): void
730
    {
731
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
732
733
        $this->assertNull($admin->getRouteBuilder());
734
735
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
736
        $admin->setRouteBuilder($routeBuilder);
737
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
738
    }
739
740
    public function testGetMenuFactory(): void
741
    {
742
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
743
744
        $this->assertNull($admin->getMenuFactory());
745
746
        $menuFactory = $this->createMock(FactoryInterface::class);
747
        $admin->setMenuFactory($menuFactory);
748
        $this->assertSame($menuFactory, $admin->getMenuFactory());
749
    }
750
751
    public function testGetExtensions(): void
752
    {
753
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
754
755
        $this->assertSame([], $admin->getExtensions());
756
757
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
758
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
759
760
        $admin->addExtension($adminExtension1);
761
        $admin->addExtension($adminExtension2);
762
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
763
    }
764
765
    public function testGetFilterTheme(): void
766
    {
767
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
768
769
        $this->assertSame([], $admin->getFilterTheme());
770
771
        $admin->setFilterTheme(['FooTheme']);
772
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
773
    }
774
775
    public function testGetFormTheme(): void
776
    {
777
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
778
779
        $this->assertSame([], $admin->getFormTheme());
780
781
        $admin->setFormTheme(['FooTheme']);
782
783
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
784
    }
785
786
    public function testGetValidator(): void
787
    {
788
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
789
790
        $this->assertNull($admin->getValidator());
791
792
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
793
794
        $admin->setValidator($validator);
795
        $this->assertSame($validator, $admin->getValidator());
796
    }
797
798
    public function testGetSecurityHandler(): void
799
    {
800
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
801
802
        $this->assertNull($admin->getSecurityHandler());
803
804
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
805
        $admin->setSecurityHandler($securityHandler);
806
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
807
    }
808
809
    public function testGetSecurityInformation(): void
810
    {
811
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
812
813
        $this->assertSame([], $admin->getSecurityInformation());
814
815
        $securityInformation = [
816
            'GUEST' => ['VIEW', 'LIST'],
817
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
818
        ];
819
820
        $admin->setSecurityInformation($securityInformation);
821
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
822
    }
823
824
    public function testGetManagerType(): void
825
    {
826
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
827
828
        $this->assertNull($admin->getManagerType());
829
830
        $admin->setManagerType('foo_orm');
831
        $this->assertSame('foo_orm', $admin->getManagerType());
832
    }
833
834
    public function testGetModelManager(): void
835
    {
836
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
837
838
        $this->assertNull($admin->getModelManager());
839
840
        $modelManager = $this->createMock(ModelManagerInterface::class);
841
842
        $admin->setModelManager($modelManager);
843
        $this->assertSame($modelManager, $admin->getModelManager());
844
    }
845
846
    public function testGetBaseCodeRoute(): void
847
    {
848
        $postAdmin = new PostAdmin(
849
            'sonata.post.admin.post',
850
            'NewsBundle\Entity\Post',
851
            'Sonata\NewsBundle\Controller\PostAdminController'
852
        );
853
        $commentAdmin = new CommentAdmin(
854
            'sonata.post.admin.comment',
855
            'Application\Sonata\NewsBundle\Entity\Comment',
856
            'Sonata\NewsBundle\Controller\CommentAdminController'
857
        );
858
859
        $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
860
861
        $postAdmin->addChild($commentAdmin, 'post');
862
863
        $this->assertSame(
864
            'sonata.post.admin.post|sonata.post.admin.comment',
865
            $commentAdmin->getBaseCodeRoute()
866
        );
867
    }
868
869
    public function testGetRouteGenerator(): void
870
    {
871
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
872
873
        $this->assertNull($admin->getRouteGenerator());
874
875
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
876
877
        $admin->setRouteGenerator($routeGenerator);
878
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
879
    }
880
881
    public function testGetConfigurationPool(): void
882
    {
883
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
884
885
        $this->assertNull($admin->getConfigurationPool());
886
887
        $pool = $this->getMockBuilder(Pool::class)
888
            ->disableOriginalConstructor()
889
            ->getMock();
890
891
        $admin->setConfigurationPool($pool);
892
        $this->assertSame($pool, $admin->getConfigurationPool());
893
    }
894
895
    public function testGetShowBuilder(): void
896
    {
897
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
898
899
        $this->assertNull($admin->getShowBuilder());
900
901
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
902
903
        $admin->setShowBuilder($showBuilder);
904
        $this->assertSame($showBuilder, $admin->getShowBuilder());
905
    }
906
907
    public function testGetListBuilder(): void
908
    {
909
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
910
911
        $this->assertNull($admin->getListBuilder());
912
913
        $listBuilder = $this->createMock(ListBuilderInterface::class);
914
915
        $admin->setListBuilder($listBuilder);
916
        $this->assertSame($listBuilder, $admin->getListBuilder());
917
    }
918
919
    public function testGetDatagridBuilder(): void
920
    {
921
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
922
923
        $this->assertNull($admin->getDatagridBuilder());
924
925
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
926
927
        $admin->setDatagridBuilder($datagridBuilder);
928
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
929
    }
930
931
    public function testGetFormContractor(): void
932
    {
933
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
934
935
        $this->assertNull($admin->getFormContractor());
936
937
        $formContractor = $this->createMock(FormContractorInterface::class);
938
939
        $admin->setFormContractor($formContractor);
940
        $this->assertSame($formContractor, $admin->getFormContractor());
941
    }
942
943
    public function testGetRequest(): void
944
    {
945
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
946
947
        $this->assertFalse($admin->hasRequest());
948
949
        $request = new Request();
950
951
        $admin->setRequest($request);
952
        $this->assertSame($request, $admin->getRequest());
953
        $this->assertTrue($admin->hasRequest());
954
    }
955
956
    public function testGetRequestWithException(): void
957
    {
958
        $this->expectException(\LogicException::class);
959
        $this->expectExceptionMessage('The Request object has not been set');
960
961
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
962
        $admin->getRequest();
963
    }
964
965
    public function testGetTranslationDomain(): void
966
    {
967
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
968
969
        $this->assertSame('messages', $admin->getTranslationDomain());
970
971
        $admin->setTranslationDomain('foo');
972
        $this->assertSame('foo', $admin->getTranslationDomain());
973
    }
974
975
    public function testGetShowGroups(): void
976
    {
977
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
978
979
        $this->assertSame([], $admin->getShowGroups());
980
981
        $groups = ['foo', 'bar', 'baz'];
982
983
        $admin->setShowGroups($groups);
984
        $this->assertSame($groups, $admin->getShowGroups());
985
    }
986
987
    public function testGetFormGroups(): void
988
    {
989
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
990
991
        $this->assertSame([], $admin->getFormGroups());
992
993
        $groups = ['foo', 'bar', 'baz'];
994
995
        $admin->setFormGroups($groups);
996
        $this->assertSame($groups, $admin->getFormGroups());
997
    }
998
999
    public function testGetMaxPageLinks(): void
1000
    {
1001
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1002
1003
        $this->assertSame(25, $admin->getMaxPageLinks());
1004
1005
        $admin->setMaxPageLinks(14);
1006
        $this->assertSame(14, $admin->getMaxPageLinks());
1007
    }
1008
1009
    public function testGetLabel(): void
1010
    {
1011
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1012
1013
        $this->assertNull($admin->getLabel());
1014
1015
        $admin->setLabel('FooLabel');
1016
        $this->assertSame('FooLabel', $admin->getLabel());
1017
    }
1018
1019
    public function testGetBaseController(): void
1020
    {
1021
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1022
1023
        $this->assertSame('Sonata\NewsBundle\Controller\PostAdminController', $admin->getBaseControllerName());
1024
1025
        $admin->setBaseControllerName('Sonata\NewsBundle\Controller\FooAdminController');
1026
        $this->assertSame('Sonata\NewsBundle\Controller\FooAdminController', $admin->getBaseControllerName());
1027
    }
1028
1029
    public function testGetIdParameter(): void
1030
    {
1031
        $postAdmin = new PostAdmin(
1032
            'sonata.post.admin.post',
1033
            'NewsBundle\Entity\Post',
1034
            'Sonata\NewsBundle\Controller\PostAdminController'
1035
        );
1036
1037
        $this->assertSame('id', $postAdmin->getIdParameter());
1038
        $this->assertFalse($postAdmin->isChild());
1039
1040
        $commentAdmin = new CommentAdmin(
1041
            'sonata.post.admin.comment',
1042
            'Application\Sonata\NewsBundle\Entity\Comment',
1043
            'Sonata\NewsBundle\Controller\CommentAdminController'
1044
        );
1045
        $commentAdmin->setParent($postAdmin);
1046
1047
        $this->assertTrue($commentAdmin->isChild());
1048
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1049
1050
        $commentVoteAdmin = new CommentVoteAdmin(
1051
            'sonata.post.admin.comment_vote',
1052
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1053
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
1054
        );
1055
        $commentVoteAdmin->setParent($commentAdmin);
1056
1057
        $this->assertTrue($commentVoteAdmin->isChild());
1058
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1059
    }
1060
1061
    public function testGetExportFormats(): void
1062
    {
1063
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1064
1065
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1066
    }
1067
1068
    public function testGetUrlsafeIdentifier(): void
1069
    {
1070
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1071
1072
        $model = new \stdClass();
1073
1074
        $modelManager = $this->createMock(ModelManagerInterface::class);
1075
        $modelManager->expects($this->once())
1076
            ->method('getUrlSafeIdentifier')
1077
            ->with($this->equalTo($model))
1078
            ->willReturn('foo');
1079
        $admin->setModelManager($modelManager);
1080
1081
        $this->assertSame('foo', $admin->getUrlSafeIdentifier($model));
1082
    }
1083
1084
    public function testDeterminedPerPageValue(): void
1085
    {
1086
        $modelManager = $this->createStub(ModelManagerInterface::class);
1087
1088
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1089
        $admin->setModelManager($modelManager);
1090
1091
        $this->assertFalse($admin->determinedPerPageValue(123));
1092
        $this->assertTrue($admin->determinedPerPageValue(25));
1093
    }
1094
1095
    public function testIsGranted(): void
1096
    {
1097
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1098
        $modelManager = $this->createStub(ModelManagerInterface::class);
1099
        $modelManager
1100
            ->method('getNormalizedIdentifier')
1101
            ->willReturnCallback(static function (?object $model = null): ?string {
1102
                return $model ? $model->id : null;
1103
            });
1104
1105
        $admin->setModelManager($modelManager);
1106
1107
        $entity1 = new \stdClass();
1108
        $entity1->id = '1';
1109
1110
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1111
        $securityHandler
1112
            ->expects($this->exactly(6))
1113
            ->method('isGranted')
1114
            ->willReturnCallback(static function (
1115
                AdminInterface $adminIn,
1116
                string $attributes,
1117
                ?object $object = null
1118
            ) use (
1119
                $admin,
1120
                $entity1
1121
            ): bool {
1122
                return $admin === $adminIn && 'FOO' === $attributes &&
1123
                    ($object === $admin || $object === $entity1);
1124
            });
1125
1126
        $admin->setSecurityHandler($securityHandler);
1127
1128
        $this->assertTrue($admin->isGranted('FOO'));
1129
        $this->assertTrue($admin->isGranted('FOO'));
1130
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1131
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1132
        $this->assertFalse($admin->isGranted('BAR'));
1133
        $this->assertFalse($admin->isGranted('BAR'));
1134
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1135
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1136
1137
        $entity2 = new \stdClass();
1138
        $entity2->id = '2';
1139
1140
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1141
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1142
1143
        $entity3 = new \stdClass();
1144
        $entity3->id = '3';
1145
1146
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1147
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1148
    }
1149
1150
    public function testSupportsPreviewMode(): void
1151
    {
1152
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1153
1154
        $this->assertFalse($admin->supportsPreviewMode());
1155
    }
1156
1157
    public function testGetPermissionsShow(): void
1158
    {
1159
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1160
1161
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1162
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1163
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1164
    }
1165
1166
    public function testShowIn(): void
1167
    {
1168
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1169
1170
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1171
        $securityHandler
1172
            ->method('isGranted')
1173
            ->willReturnCallback(static function (AdminInterface $adminIn, array $attributes, $object = null) use ($admin): 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...
1174
                return $admin === $adminIn && $attributes === ['LIST'];
1175
            });
1176
1177
        $admin->setSecurityHandler($securityHandler);
1178
1179
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1180
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1181
        $this->assertTrue($admin->showIn('foo'));
1182
    }
1183
1184
    public function testGetObjectIdentifier(): void
1185
    {
1186
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1187
1188
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1189
    }
1190
1191
    /**
1192
     * @doesNotPerformAssertions
1193
     */
1194
    public function testSetFilterPersister(): void
1195
    {
1196
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle\Controller\PostAdminController');
1197
1198
        $filterPersister = $this->createMock(FilterPersisterInterface::class);
1199
1200
        $admin->setFilterPersister($filterPersister);
1201
    }
1202
1203
    public function testGetRootCode(): void
1204
    {
1205
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1206
1207
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1208
1209
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'Sonata\NewsBundle\Controller\PostParentAdminController');
1210
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1211
        $parentFieldDescription->expects($this->once())
1212
            ->method('getAdmin')
1213
            ->willReturn($parentAdmin);
1214
1215
        $this->assertFalse($admin->hasParentFieldDescription());
1216
        $admin->setParentFieldDescription($parentFieldDescription);
1217
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1218
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1219
    }
1220
1221
    public function testGetRoot(): void
1222
    {
1223
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1224
1225
        $this->assertSame($admin, $admin->getRoot());
1226
1227
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'Sonata\NewsBundle\Controller\PostParentAdminController');
1228
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1229
        $parentFieldDescription->expects($this->once())
1230
            ->method('getAdmin')
1231
            ->willReturn($parentAdmin);
1232
1233
        $this->assertFalse($admin->hasParentFieldDescription());
1234
        $admin->setParentFieldDescription($parentFieldDescription);
1235
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1236
        $this->assertSame($parentAdmin, $admin->getRoot());
1237
    }
1238
1239
    public function testGetExportFields(): void
1240
    {
1241
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1242
1243
        $modelManager = $this->createMock(ModelManagerInterface::class);
1244
        $modelManager->expects($this->once())
1245
            ->method('getExportFields')
1246
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1247
            ->willReturn(['foo', 'bar']);
1248
1249
        $admin->setModelManager($modelManager);
1250
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1251
    }
1252
1253
    public function testGetPersistentParametersWithNoExtension(): void
1254
    {
1255
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1256
1257
        $this->assertEmpty($admin->getPersistentParameters());
1258
    }
1259
1260
    public function testGetPersistentParametersWithValidExtension(): void
1261
    {
1262
        $expected = [
1263
            'context' => 'foobar',
1264
        ];
1265
1266
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1267
1268
        $extension = $this->createMock(AdminExtensionInterface::class);
1269
        $extension->expects($this->once())->method('getPersistentParameters')->willReturn($expected);
1270
1271
        $admin->addExtension($extension);
1272
1273
        $this->assertSame($expected, $admin->getPersistentParameters());
1274
    }
1275
1276
    public function testGetNewInstanceForChildAdminWithParentValue(): void
1277
    {
1278
        $post = new Post();
1279
1280
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1281
        $postAdmin->method('getObject')->willReturn($post);
1282
1283
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1284
        $formBuilder->method('getForm')->willReturn(null);
1285
1286
        $tag = new Tag();
1287
1288
        $modelManager = $this->createStub(ModelManagerInterface::class);
1289
        $modelManager->method('getModelInstance')->willReturn($tag);
1290
1291
        $tagAdmin = new TagAdmin('admin.tag', Tag::class, 'MyBundle\MyController');
1292
        $tagAdmin->setModelManager($modelManager);
1293
        $tagAdmin->setParent($postAdmin);
1294
1295
        $request = $this->createStub(Request::class);
1296
        $tagAdmin->setRequest($request);
1297
1298
        $configurationPool = $this->getMockBuilder(Pool::class)
1299
            ->disableOriginalConstructor()
1300
            ->getMock();
1301
1302
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1303
1304
        $tagAdmin->setConfigurationPool($configurationPool);
1305
1306
        $tag = $tagAdmin->getNewInstance();
1307
1308
        $this->assertSame($post, $tag->getPost());
1309
    }
1310
1311
    public function testGetNewInstanceForChildAdminWithCollectionParentValue(): void
1312
    {
1313
        $post = new Post();
1314
1315
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1316
        $postAdmin->method('getObject')->willReturn($post);
1317
1318
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1319
        $formBuilder->method('getForm')->willReturn(null);
1320
1321
        $postCategory = new PostCategory();
1322
1323
        $modelManager = $this->createStub(ModelManagerInterface::class);
1324
        $modelManager->method('getModelInstance')->willReturn($postCategory);
1325
1326
        $postCategoryAdmin = new PostCategoryAdmin('admin.post_category', PostCategoryAdmin::class, 'MyBundle\MyController');
1327
        $postCategoryAdmin->setModelManager($modelManager);
1328
        $postCategoryAdmin->setParent($postAdmin);
1329
1330
        $request = $this->createStub(Request::class);
1331
        $postCategoryAdmin->setRequest($request);
1332
1333
        $configurationPool = $this->getMockBuilder(Pool::class)
1334
            ->disableOriginalConstructor()
1335
            ->getMock();
1336
1337
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1338
1339
        $postCategoryAdmin->setConfigurationPool($configurationPool);
1340
1341
        $postCategory = $postCategoryAdmin->getNewInstance();
1342
1343
        $this->assertInstanceOf(Collection::class, $postCategory->getPosts());
1344
        $this->assertCount(1, $postCategory->getPosts());
1345
        $this->assertContains($post, $postCategory->getPosts());
1346
    }
1347
1348
    public function testGetNewInstanceForEmbededAdminWithParentValue(): void
1349
    {
1350
        $post = new Post();
1351
1352
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1353
        $postAdmin->method('getObject')->willReturn($post);
1354
1355
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1356
        $formBuilder->method('getForm')->willReturn(null);
1357
1358
        $parentField = $this->createStub(FieldDescriptionInterface::class);
1359
        $parentField->method('getAdmin')->willReturn($postAdmin);
1360
        $parentField->method('getParentAssociationMappings')->willReturn([]);
1361
        $parentField->method('getAssociationMapping')->willReturn(['fieldName' => 'tag', 'mappedBy' => 'post']);
1362
1363
        $tag = new Tag();
1364
1365
        $modelManager = $this->createStub(ModelManagerInterface::class);
1366
        $modelManager->method('getModelInstance')->willReturn($tag);
1367
1368
        $tagAdmin = new TagAdmin('admin.tag', Tag::class, 'MyBundle\MyController');
1369
        $tagAdmin->setModelManager($modelManager);
1370
        $tagAdmin->setParentFieldDescription($parentField);
1371
1372
        $request = $this->createStub(Request::class);
1373
        $tagAdmin->setRequest($request);
1374
1375
        $configurationPool = $this->getMockBuilder(Pool::class)
1376
            ->disableOriginalConstructor()
1377
            ->getMock();
1378
1379
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1380
1381
        $tagAdmin->setConfigurationPool($configurationPool);
1382
1383
        $tag = $tagAdmin->getNewInstance();
1384
1385
        $this->assertSame($post, $tag->getPost());
1386
    }
1387
1388
    public function testFormAddPostSubmitEventForPreValidation(): void
1389
    {
1390
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', \stdClass::class, 'Sonata\FooBundle\Controller\ModelAdminController');
1391
        $object = new \stdClass();
1392
1393
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1394
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1395
1396
        $validator = $this->createMock(ValidatorInterface::class);
1397
        $validator
1398
                ->method('getMetadataFor')
1399
                ->willReturn($this->createMock(MemberMetadata::class));
1400
        $modelAdmin->setValidator($validator);
1401
1402
        $modelManager = $this->createMock(ModelManagerInterface::class);
1403
        $modelManager
1404
            ->method('getNewFieldDescriptionInstance')
1405
            ->willReturn(new FieldDescription());
1406
        $modelAdmin->setModelManager($modelManager);
1407
1408
        // a Admin class to test that preValidate is called
1409
        $testAdminPreValidate = $this->createMock(AbstractAdmin::class);
1410
        $testAdminPreValidate->expects($this->once())
1411
                ->method('preValidate')
1412
                ->with($this->identicalTo($object));
1413
1414
        $event = $this->createMock(FormEvent::class);
1415
        $event
1416
                ->method('getData')
1417
                ->willReturn($object);
1418
1419
        $formBuild = $this->createMock(FormBuilder::class);
1420
        $formBuild->expects($this->once())
1421
                ->method('addEventListener')
1422
                ->with(
1423
                    $this->identicalTo(FormEvents::POST_SUBMIT),
1424
                    $this->callback(static function ($callback) use ($testAdminPreValidate, $event): bool {
1425
                        if (\is_callable($callback)) {
1426
                            $closure = $callback->bindTo($testAdminPreValidate);
0 ignored issues
show
Bug introduced by
The method bindTo cannot be called on $callback (of type callable).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1427
                            $closure($event);
1428
1429
                            return true;
1430
                        }
1431
1432
                        return false;
1433
                    }),
1434
                    $this->greaterThan(0)
1435
                );
1436
1437
        $formContractor = $this->createMock(FormContractorInterface::class);
1438
        $formContractor
1439
                ->method('getDefaultOptions')
1440
                ->willReturn([]);
1441
        $formContractor
1442
                ->method('getFormBuilder')
1443
                ->willReturn($formBuild);
1444
1445
        $modelAdmin->setFormContractor($formContractor);
1446
        $modelAdmin->setSubject($object);
1447
        $modelAdmin->defineFormBuilder($formBuild);
1448
        $modelAdmin->getForm();
1449
    }
1450
1451
    public function testCanAddInlineValidationOnlyForGenericMetadata(): void
1452
    {
1453
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', \stdClass::class, 'Sonata\FooBundle\Controller\ModelAdminController');
1454
        $object = new \stdClass();
1455
1456
        $labelTranslatorStrategy = $this->createStub(LabelTranslatorStrategyInterface::class);
1457
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1458
1459
        $validator = $this->createStub(ValidatorInterface::class);
1460
        $metadata = $this->createStub(PropertyMetadataInterface::class);
1461
        $validator
1462
            ->method('getMetadataFor')
1463
            ->willReturn($metadata);
1464
        $modelAdmin->setValidator($validator);
1465
1466
        $modelManager = $this->createStub(ModelManagerInterface::class);
1467
        $modelManager
1468
            ->method('getNewFieldDescriptionInstance')
1469
            ->willReturn(new FieldDescription());
1470
        $modelAdmin->setModelManager($modelManager);
1471
1472
        $event = $this->createStub(FormEvent::class);
1473
        $event
1474
            ->method('getData')
1475
            ->willReturn($object);
1476
1477
        $formBuild = $this->createStub(FormBuilder::class);
1478
1479
        $formContractor = $this->createStub(FormContractorInterface::class);
1480
        $formContractor
1481
            ->method('getDefaultOptions')
1482
            ->willReturn([]);
1483
        $formContractor
1484
            ->method('getFormBuilder')
1485
            ->willReturn($formBuild);
1486
1487
        $modelAdmin->setFormContractor($formContractor);
1488
        $modelAdmin->setSubject($object);
1489
1490
        $this->expectException(\RuntimeException::class);
1491
        $this->expectExceptionMessage(
1492
            sprintf(
1493
                'Cannot add inline validator for stdClass because its metadata is an instance of %s instead of Symfony\Component\Validator\Mapping\GenericMetadata',
1494
                \get_class($metadata)
1495
            )
1496
        );
1497
1498
        $modelAdmin->defineFormBuilder($formBuild);
1499
    }
1500
1501
    public function testRemoveFieldFromFormGroup(): void
1502
    {
1503
        $formGroups = [
1504
            'foobar' => [
1505
                'fields' => [
1506
                    'foo' => 'foo',
1507
                    'bar' => 'bar',
1508
                ],
1509
            ],
1510
        ];
1511
1512
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1513
        $admin->setFormGroups($formGroups);
1514
1515
        $admin->removeFieldFromFormGroup('foo');
1516
        $this->assertSame($admin->getFormGroups(), [
1517
            'foobar' => [
1518
                'fields' => [
1519
                    'bar' => 'bar',
1520
                ],
1521
            ],
1522
        ]);
1523
1524
        $admin->removeFieldFromFormGroup('bar');
1525
        $this->assertSame($admin->getFormGroups(), []);
1526
    }
1527
1528
    public function testGetFilterParameters(): void
1529
    {
1530
        $authorId = uniqid();
1531
1532
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
1533
1534
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1535
        $postAdmin->addChild($commentAdmin, 'post__author');
1536
1537
        $request = $this->createMock(Request::class);
1538
        $query = $this->createMock(ParameterBag::class);
1539
        $query
1540
            ->method('get')
1541
            ->willReturn([
1542
                'filter' => [
1543
                    '_page' => '1',
1544
                    '_per_page' => '32',
1545
                ],
1546
            ]);
1547
1548
        $request->query = $query;
1549
        $request
1550
            ->method('get')
1551
            ->willReturn($authorId);
1552
1553
        $commentAdmin->setRequest($request);
1554
1555
        $modelManager = $this->createMock(ModelManagerInterface::class);
1556
        $modelManager
1557
            ->method('getDefaultSortValues')
1558
            ->willReturn([]);
1559
1560
        $commentAdmin->setModelManager($modelManager);
1561
1562
        $parameters = $commentAdmin->getFilterParameters();
1563
1564
        $this->assertTrue(isset($parameters['post__author']));
1565
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1566
    }
1567
1568
    public function testGetFilterFieldDescription(): void
1569
    {
1570
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1571
1572
        $fooFieldDescription = new FieldDescription();
1573
        $barFieldDescription = new FieldDescription();
1574
        $bazFieldDescription = new FieldDescription();
1575
1576
        $modelManager = $this->createMock(ModelManagerInterface::class);
1577
        $modelManager->expects($this->exactly(3))
1578
            ->method('getNewFieldDescriptionInstance')
1579
            ->willReturnCallback(static function ($adminClass, string $name, $filterOptions) use ($fooFieldDescription, $barFieldDescription, $bazFieldDescription) {
0 ignored issues
show
Unused Code introduced by
The parameter $filterOptions 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...
1580
                switch ($name) {
1581
                    case 'foo':
1582
                        $fieldDescription = $fooFieldDescription;
1583
1584
                        break;
1585
1586
                    case 'bar':
1587
                        $fieldDescription = $barFieldDescription;
1588
1589
                        break;
1590
1591
                    case 'baz':
1592
                        $fieldDescription = $bazFieldDescription;
1593
1594
                        break;
1595
1596
                    default:
1597
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1598
                        break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1599
                }
1600
1601
                $fieldDescription->setName($name);
1602
1603
                return $fieldDescription;
1604
            });
1605
1606
        $modelAdmin->setModelManager($modelManager);
1607
1608
        $pager = $this->createMock(PagerInterface::class);
1609
1610
        $datagrid = $this->createMock(DatagridInterface::class);
1611
        $datagrid->expects($this->once())
1612
            ->method('getPager')
1613
            ->willReturn($pager);
1614
1615
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1616
        $datagridBuilder->expects($this->once())
1617
            ->method('getBaseDatagrid')
1618
            ->with($this->identicalTo($modelAdmin), [])
1619
            ->willReturn($datagrid);
1620
1621
        $datagridBuilder->expects($this->exactly(3))
1622
            ->method('addFilter')
1623
            ->willReturnCallback(static function ($datagrid, $type, $fieldDescription, AdminInterface $admin): void {
1624
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1625
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1626
            });
1627
1628
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1629
1630
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1631
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1632
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1633
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1634
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1635
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1636
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1637
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1638
    }
1639
1640
    public function testGetSubjectNoRequest(): void
1641
    {
1642
        $modelManager = $this->createMock(ModelManagerInterface::class);
1643
        $modelManager
1644
            ->expects($this->never())
1645
            ->method('find');
1646
1647
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1648
        $admin->setModelManager($modelManager);
1649
1650
        $this->assertFalse($admin->hasSubject());
1651
    }
1652
1653
    public function testGetSideMenu(): void
1654
    {
1655
        $item = $this->createMock(ItemInterface::class);
1656
        $item
1657
            ->expects($this->once())
1658
            ->method('setChildrenAttribute')
1659
            ->with('class', 'nav navbar-nav');
1660
        $item
1661
            ->expects($this->once())
1662
            ->method('setExtra')
1663
            ->with('translation_domain', 'foo_bar_baz');
1664
1665
        $menuFactory = $this->createMock(FactoryInterface::class);
1666
        $menuFactory
1667
            ->expects($this->once())
1668
            ->method('createItem')
1669
            ->willReturn($item);
1670
1671
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1672
        $modelAdmin->setMenuFactory($menuFactory);
1673
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1674
1675
        $modelAdmin->getSideMenu('foo');
1676
    }
1677
1678
    /**
1679
     * @return array
1680
     */
1681
    public function provideGetSubject()
1682
    {
1683
        return [
1684
            [23],
1685
            ['azerty'],
1686
            ['4f69bbb5f14a13347f000092'],
1687
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1688
            [sprintf('123%smy_type', AdapterInterface::ID_SEPARATOR)], // composite keys are supported
1689
        ];
1690
    }
1691
1692
    /**
1693
     * @dataProvider provideGetSubject
1694
     */
1695
    public function testGetSubjectFailed($id): void
1696
    {
1697
        $modelManager = $this->createMock(ModelManagerInterface::class);
1698
        $modelManager
1699
            ->expects($this->once())
1700
            ->method('find')
1701
            ->with('NewsBundle\Entity\Post', $id)
1702
            ->willReturn(null); // entity not found
1703
1704
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1705
        $admin->setModelManager($modelManager);
1706
1707
        $admin->setRequest(new Request(['id' => $id]));
1708
        $this->assertFalse($admin->hasSubject());
1709
    }
1710
1711
    /**
1712
     * @dataProvider provideGetSubject
1713
     */
1714
    public function testGetSubject($id): void
1715
    {
1716
        $model = new Post();
1717
1718
        $modelManager = $this->createMock(ModelManagerInterface::class);
1719
        $modelManager
1720
            ->expects($this->once())
1721
            ->method('find')
1722
            ->with('NewsBundle\Entity\Post', $id)
1723
            ->willReturn($model);
1724
1725
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1726
        $admin->setModelManager($modelManager);
1727
1728
        $admin->setRequest(new Request(['id' => $id]));
1729
        $this->assertTrue($admin->hasSubject());
1730
        $this->assertSame($model, $admin->getSubject());
1731
        $this->assertSame($model, $admin->getSubject()); // model manager must be used only once
1732
    }
1733
1734
    public function testGetSubjectWithParentDescription(): void
1735
    {
1736
        $adminId = 1;
1737
1738
        $comment = new Comment();
1739
1740
        $modelManager = $this->createMock(ModelManagerInterface::class);
1741
        $modelManager
1742
            ->method('find')
1743
            ->with('NewsBundle\Entity\Comment', $adminId)
1744
            ->willReturn($comment);
1745
1746
        $request = new Request(['id' => $adminId]);
1747
1748
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1749
        $postAdmin->setRequest($request);
1750
1751
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
1752
        $commentAdmin->setRequest($request);
1753
        $commentAdmin->setModelManager($modelManager);
1754
1755
        $this->assertTrue($commentAdmin->hasSubject());
1756
        $this->assertSame($comment, $commentAdmin->getSubject());
1757
1758
        $commentAdmin->setSubject(null);
1759
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1760
1761
        $this->assertFalse($commentAdmin->hasSubject());
1762
    }
1763
1764
    /**
1765
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1766
     */
1767
    public function testGetActionButtonsList(): void
1768
    {
1769
        $expected = [
1770
            'create' => [
1771
                'template' => 'Foo.html.twig',
1772
            ],
1773
        ];
1774
1775
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1776
1777
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1778
        $templateRegistry->getTemplate('button_create')->willReturn('Foo.html.twig');
1779
1780
        $admin->setTemplateRegistry($templateRegistry->reveal());
1781
1782
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1783
        $securityHandler
1784
            ->expects($this->once())
1785
            ->method('isGranted')
1786
            ->with($admin, 'CREATE', $admin)
1787
            ->willReturn(true);
1788
        $admin->setSecurityHandler($securityHandler);
1789
1790
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1791
        $routeGenerator
1792
            ->expects($this->once())
1793
            ->method('hasAdminRoute')
1794
            ->with($admin, 'create')
1795
            ->willReturn(true);
1796
        $admin->setRouteGenerator($routeGenerator);
1797
1798
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1799
    }
1800
1801
    /**
1802
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1803
     */
1804
    public function testGetActionButtonsListCreateDisabled(): void
1805
    {
1806
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1807
1808
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1809
        $securityHandler
1810
            ->expects($this->once())
1811
            ->method('isGranted')
1812
            ->with($admin, 'CREATE', $admin)
1813
            ->willReturn(false);
1814
        $admin->setSecurityHandler($securityHandler);
1815
1816
        $this->assertSame([], $admin->getActionButtons('list', null));
1817
    }
1818
1819
    /**
1820
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1821
     */
1822
    public function testGetBatchActions(): void
1823
    {
1824
        $expected = [
1825
            'delete' => [
1826
                'label' => 'action_delete',
1827
                'translation_domain' => 'SonataAdminBundle',
1828
                'ask_confirmation' => true, // by default always true
1829
            ],
1830
            'foo' => [
1831
                'label' => 'action_foo',
1832
                'translation_domain' => 'SonataAdminBundle',
1833
            ],
1834
            'bar' => [
1835
                'label' => 'batch.label_bar',
1836
                'translation_domain' => 'SonataAdminBundle',
1837
            ],
1838
            'baz' => [
1839
                'label' => 'action_baz',
1840
                'translation_domain' => 'AcmeAdminBundle',
1841
            ],
1842
        ];
1843
1844
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1845
1846
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1847
        $labelTranslatorStrategy
1848
            ->method('getLabel')
1849
            ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string {
1850
                return sprintf('%s.%s_%s', $context, $type, $label);
1851
            });
1852
1853
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1854
        $admin->setRouteBuilder($pathInfo);
1855
        $admin->setTranslationDomain('SonataAdminBundle');
1856
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1857
1858
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1859
        $routeGenerator
1860
            ->expects($this->once())
1861
            ->method('hasAdminRoute')
1862
            ->with($admin, 'delete')
1863
            ->willReturn(true);
1864
        $admin->setRouteGenerator($routeGenerator);
1865
1866
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1867
        $securityHandler
1868
            ->method('isGranted')
1869
            ->willReturnCallback(static function (AdminInterface $adminIn, string $attributes, $object = null) use ($admin): 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...
1870
                return $admin === $adminIn && 'DELETE' === $attributes;
1871
            });
1872
        $admin->setSecurityHandler($securityHandler);
1873
1874
        $this->assertSame($expected, $admin->getBatchActions());
1875
    }
1876
1877
    /**
1878
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1879
     */
1880
    public function testShowMosaicButton(): void
1881
    {
1882
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1883
        $listModes = $admin->getListModes();
1884
1885
        $admin->showMosaicButton(true);
1886
1887
        $this->assertSame($listModes, $admin->getListModes());
1888
    }
1889
1890
    /**
1891
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1892
     */
1893
    public function testShowMosaicButtonHideMosaic(): void
1894
    {
1895
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1896
        $listModes = $admin->getListModes();
1897
        $expected['list'] = $listModes['list'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$expected was never initialized. Although not strictly required by PHP, it is generally a good practice to add $expected = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1898
1899
        $admin->showMosaicButton(false);
1900
1901
        $this->assertSame($expected, $admin->getListModes());
1902
    }
1903
1904
    /**
1905
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
1906
     * @dataProvider provideGetBaseRouteName
1907
     */
1908
    public function testDefaultDashboardActionsArePresent(string $objFqn, string $expected): void
1909
    {
1910
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1911
        $routerMock = $this->createMock(RouterInterface::class);
1912
1913
        $routerMock->method('generate')->willReturn('/admin/post');
1914
1915
        $routeGenerator = new DefaultRouteGenerator(
1916
            $routerMock,
1917
            new RoutesCache($this->cacheTempFolder, true)
1918
        );
1919
1920
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
1921
        $admin->setRouteBuilder($pathInfo);
1922
        $admin->setRouteGenerator($routeGenerator);
1923
        $admin->initialize();
1924
1925
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1926
        $templateRegistry->getTemplate('action_create')->willReturn('Foo.html.twig');
1927
1928
        $admin->setTemplateRegistry($templateRegistry->reveal());
1929
1930
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1931
        $securityHandler
1932
            ->method('isGranted')
1933
            ->willReturnCallback(static function (AdminInterface $adminIn, string $attributes, $object = null) use ($admin): 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...
1934
                return $admin === $adminIn && ('CREATE' === $attributes || 'LIST' === $attributes);
1935
            });
1936
1937
        $admin->setSecurityHandler($securityHandler);
1938
1939
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
1940
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
1941
    }
1942
1943
    public function testDefaultFilters(): void
1944
    {
1945
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1946
1947
        $subjectId = uniqid();
1948
1949
        $request = $this->createMock(Request::class);
1950
        $query = $this->createMock(ParameterBag::class);
1951
        $query
1952
            ->method('get')
1953
            ->with($this->equalTo('filter'))
1954
            ->willReturn([
1955
                'a' => [
1956
                    'value' => 'b',
1957
                ],
1958
                'foo' => [
1959
                    'type' => '1',
1960
                    'value' => 'bar',
1961
                ],
1962
                'baz' => [
1963
                    'type' => '5',
1964
                    'value' => 'test',
1965
                ],
1966
            ]);
1967
        $request->query = $query;
1968
1969
        $request
1970
            ->method('get')
1971
            ->willReturn($subjectId);
1972
1973
        $admin->setRequest($request);
1974
1975
        $modelManager = $this->createMock(ModelManagerInterface::class);
1976
        $modelManager
1977
            ->method('getDefaultSortValues')
1978
            ->willReturn([]);
1979
1980
        $admin->setModelManager($modelManager);
1981
1982
        $this->assertSame([
1983
            'foo' => [
1984
                'type' => '1',
1985
                'value' => 'bar',
1986
            ],
1987
            'baz' => [
1988
                'type' => '5',
1989
                'value' => 'test',
1990
            ],
1991
            'a' => [
1992
                'value' => 'b',
1993
            ],
1994
            '_per_page' => 25,
1995
        ], $admin->getFilterParameters());
1996
    }
1997
1998
    public function testGetDataSourceIterator(): void
1999
    {
2000
        $pager = $this->createStub(PagerInterface::class);
2001
        $translator = $this->createStub(TranslatorInterface::class);
2002
        $modelManager = $this->createMock(ModelManagerInterface::class);
2003
2004
        $admin = new PostAdmin(
2005
            'sonata.post.admin.post',
2006
            'Application\Sonata\NewsBundle\Entity\Post',
2007
            'Sonata\NewsBundle\Controller\PostAdminController'
2008
        );
2009
2010
        $formFactory = new FormFactory(new FormRegistry([], new ResolvedFormTypeFactory()));
2011
        $datagridBuilder = new DatagridBuilder($formFactory, $pager);
2012
2013
        $translator->method('trans')->willReturnCallback(static function (string $label): string {
2014
            if ('export.label_field' === $label) {
2015
                return 'Feld';
2016
            }
2017
2018
            return $label;
2019
        });
2020
2021
        $modelManager->method('getExportFields')->willReturn([
2022
            'field',
2023
            'foo',
2024
            'bar',
2025
        ]);
2026
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2027
            ->with($this->equalTo($datagridBuilder->getBaseDatagrid($admin)), $this->equalTo([
2028
                'Feld' => 'field',
2029
                1 => 'foo',
2030
                2 => 'bar',
2031
            ]))
2032
            ->willReturn(new ArraySourceIterator([]));
2033
2034
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2035
        $admin->setDatagridBuilder($datagridBuilder);
2036
        $admin->setModelManager($modelManager);
2037
        $admin->setLabelTranslatorStrategy(new UnderscoreLabelTranslatorStrategy());
2038
2039
        $admin->getDataSourceIterator();
2040
    }
2041
2042
    public function testCircularChildAdmin(): void
2043
    {
2044
        $this->expectException(\RuntimeException::class);
2045
        $this->expectExceptionMessage(
2046
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2047
        );
2048
2049
        $postAdmin = new PostAdmin(
2050
            'sonata.post.admin.post',
2051
            'Application\Sonata\NewsBundle\Entity\Post',
2052
            'Sonata\NewsBundle\Controller\PostAdminController'
2053
        );
2054
        $commentAdmin = new CommentAdmin(
2055
            'sonata.post.admin.comment',
2056
            'Application\Sonata\NewsBundle\Entity\Comment',
2057
            'Sonata\NewsBundle\Controller\CommentAdminController'
2058
        );
2059
        $postAdmin->addChild($commentAdmin, 'post');
2060
        $commentAdmin->addChild($postAdmin, 'comment');
2061
    }
2062
2063
    public function testCircularChildAdminTripleLevel(): void
2064
    {
2065
        $this->expectException(\RuntimeException::class);
2066
        $this->expectExceptionMessage(
2067
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2068
        );
2069
2070
        $postAdmin = new PostAdmin(
2071
            'sonata.post.admin.post',
2072
            'Application\Sonata\NewsBundle\Entity\Post',
2073
            'Sonata\NewsBundle\Controller\PostAdminController'
2074
        );
2075
        $commentAdmin = new CommentAdmin(
2076
            'sonata.post.admin.comment',
2077
            'Application\Sonata\NewsBundle\Entity\Comment',
2078
            'Sonata\NewsBundle\Controller\CommentAdminController'
2079
        );
2080
        $commentVoteAdmin = new CommentVoteAdmin(
2081
            'sonata.post.admin.comment_vote',
2082
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2083
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2084
        );
2085
        $postAdmin->addChild($commentAdmin, 'post');
2086
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2087
        $commentVoteAdmin->addChild($postAdmin, 'post');
2088
    }
2089
2090
    public function testCircularChildAdminWithItself(): void
2091
    {
2092
        $this->expectException(\RuntimeException::class);
2093
        $this->expectExceptionMessage(
2094
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2095
        );
2096
2097
        $postAdmin = new PostAdmin(
2098
            'sonata.post.admin.post',
2099
            'Application\Sonata\NewsBundle\Entity\Post',
2100
            'Sonata\NewsBundle\Controller\PostAdminController'
2101
        );
2102
        $postAdmin->addChild($postAdmin, 'post');
2103
    }
2104
2105
    public function testGetRootAncestor(): void
2106
    {
2107
        $postAdmin = new PostAdmin(
2108
            'sonata.post.admin.post',
2109
            'Application\Sonata\NewsBundle\Entity\Post',
2110
            'Sonata\NewsBundle\Controller\PostAdminController'
2111
        );
2112
        $commentAdmin = new CommentAdmin(
2113
            'sonata.post.admin.comment',
2114
            'Application\Sonata\NewsBundle\Entity\Comment',
2115
            'Sonata\NewsBundle\Controller\CommentAdminController'
2116
        );
2117
        $commentVoteAdmin = new CommentVoteAdmin(
2118
            'sonata.post.admin.comment_vote',
2119
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2120
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2121
        );
2122
2123
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2124
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2125
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2126
2127
        $postAdmin->addChild($commentAdmin, 'post');
2128
2129
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2130
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2131
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2132
2133
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2134
2135
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2136
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2137
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2138
    }
2139
2140
    public function testGetChildDepth(): void
2141
    {
2142
        $postAdmin = new PostAdmin(
2143
            'sonata.post.admin.post',
2144
            'Application\Sonata\NewsBundle\Entity\Post',
2145
            'Sonata\NewsBundle\Controller\PostAdminController'
2146
        );
2147
        $commentAdmin = new CommentAdmin(
2148
            'sonata.post.admin.comment',
2149
            'Application\Sonata\NewsBundle\Entity\Comment',
2150
            'Sonata\NewsBundle\Controller\CommentAdminController'
2151
        );
2152
        $commentVoteAdmin = new CommentVoteAdmin(
2153
            'sonata.post.admin.comment_vote',
2154
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2155
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2156
        );
2157
2158
        $this->assertSame(0, $postAdmin->getChildDepth());
2159
        $this->assertSame(0, $commentAdmin->getChildDepth());
2160
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2161
2162
        $postAdmin->addChild($commentAdmin, 'post');
2163
2164
        $this->assertSame(0, $postAdmin->getChildDepth());
2165
        $this->assertSame(1, $commentAdmin->getChildDepth());
2166
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2167
2168
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2169
2170
        $this->assertSame(0, $postAdmin->getChildDepth());
2171
        $this->assertSame(1, $commentAdmin->getChildDepth());
2172
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2173
    }
2174
2175
    public function testGetCurrentLeafChildAdmin(): void
2176
    {
2177
        $postAdmin = new PostAdmin(
2178
            'sonata.post.admin.post',
2179
            'Application\Sonata\NewsBundle\Entity\Post',
2180
            'Sonata\NewsBundle\Controller\PostAdminController'
2181
        );
2182
        $commentAdmin = new CommentAdmin(
2183
            'sonata.post.admin.comment',
2184
            'Application\Sonata\NewsBundle\Entity\Comment',
2185
            'Sonata\NewsBundle\Controller\CommentAdminController'
2186
        );
2187
        $commentVoteAdmin = new CommentVoteAdmin(
2188
            'sonata.post.admin.comment_vote',
2189
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2190
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2191
        );
2192
2193
        $postAdmin->addChild($commentAdmin, 'post');
2194
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2195
2196
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2197
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2198
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2199
2200
        $commentAdmin->setCurrentChild(true);
2201
2202
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2203
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2204
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2205
2206
        $commentVoteAdmin->setCurrentChild(true);
2207
2208
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2209
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2210
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2211
    }
2212
2213
    public function testAdminAvoidInifiniteLoop(): void
2214
    {
2215
        $this->expectNotToPerformAssertions();
2216
2217
        $formFactory = new FormFactory(new FormRegistry([], new ResolvedFormTypeFactory()));
2218
2219
        $admin = new AvoidInfiniteLoopAdmin('code', \stdClass::class, null);
2220
        $admin->setSubject(new \stdClass());
2221
2222
        $admin->setFormContractor(new FormContractor($formFactory));
2223
2224
        $admin->setShowBuilder(new ShowBuilder());
2225
2226
        $admin->setListBuilder(new ListBuilder());
2227
2228
        $pager = $this->createStub(PagerInterface::class);
2229
        $admin->setDatagridBuilder(new DatagridBuilder($formFactory, $pager));
2230
2231
        $validator = $this->createMock(ValidatorInterface::class);
2232
        $validator->method('getMetadataFor')->willReturn($this->createStub(MemberMetadata::class));
2233
        $admin->setValidator($validator);
2234
2235
        $routeGenerator = $this->createStub(RouteGeneratorInterface::class);
2236
        $routeGenerator->method('hasAdminRoute')->willReturn(false);
2237
        $admin->setRouteGenerator($routeGenerator);
2238
2239
        $admin->getForm();
2240
        $admin->getShow();
2241
        $admin->getList();
2242
        $admin->getDatagrid();
2243
    }
2244
}
2245