Completed
Pull Request — master (#5032)
by Grégoire
03:41
created

AdminTest::testGetTemplate2()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 0
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\Model\AuditManagerInterface;
34
use Sonata\AdminBundle\Model\ModelManagerInterface;
35
use Sonata\AdminBundle\Route\DefaultRouteGenerator;
36
use Sonata\AdminBundle\Route\PathInfoBuilder;
37
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
38
use Sonata\AdminBundle\Route\RoutesCache;
39
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
40
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
41
use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface;
42
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentAdmin;
43
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentVoteAdmin;
44
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentWithCustomRouteAdmin;
45
use Sonata\AdminBundle\Tests\Fixtures\Admin\FieldDescription;
46
use Sonata\AdminBundle\Tests\Fixtures\Admin\FilteredAdmin;
47
use Sonata\AdminBundle\Tests\Fixtures\Admin\ModelAdmin;
48
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostAdmin;
49
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostWithCustomRouteAdmin;
50
use Sonata\AdminBundle\Tests\Fixtures\Admin\TagAdmin;
51
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\BlogPost;
52
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Comment;
53
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Post;
54
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Tag;
55
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToString;
56
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToStringNull;
57
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
58
use Sonata\CoreBundle\Model\Adapter\AdapterInterface;
59
use Symfony\Component\DependencyInjection\Container;
60
use Symfony\Component\Form\FormBuilder;
61
use Symfony\Component\Form\FormBuilderInterface;
62
use Symfony\Component\Form\FormEvent;
63
use Symfony\Component\Form\FormEvents;
64
use Symfony\Component\HttpFoundation\ParameterBag;
65
use Symfony\Component\HttpFoundation\Request;
66
use Symfony\Component\PropertyAccess\PropertyAccess;
67
use Symfony\Component\Routing\RouterInterface;
68
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
69
use Symfony\Component\Translation\TranslatorInterface;
70
use Symfony\Component\Validator\Mapping\MemberMetadata;
71
use Symfony\Component\Validator\Validator\ValidatorInterface;
72
73
class AdminTest extends TestCase
74
{
75
    protected $cacheTempFolder;
76
77
    public function setUp(): void
78
    {
79
        $this->cacheTempFolder = sys_get_temp_dir().'/sonata_test_route';
80
81
        exec('rm -rf '.$this->cacheTempFolder);
82
    }
83
84
    /**
85
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
86
     */
87
    public function testConstructor(): void
88
    {
89
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
90
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
91
92
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
93
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
94
        $this->assertSame($class, $admin->getClass());
95
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
96
    }
97
98
    public function testGetClass(): void
99
    {
100
        $class = Post::class;
101
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
102
103
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
104
105
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
106
107
        $admin->setSubject(new BlogPost());
108
        $this->assertSame(BlogPost::class, $admin->getClass());
109
110
        $admin->setSubClasses(['foo']);
111
        $this->assertSame(BlogPost::class, $admin->getClass());
112
113
        $admin->setSubject(null);
0 ignored issues
show
Documentation introduced by
null is of type null, 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...
114
        $admin->setSubClasses([]);
115
        $this->assertSame($class, $admin->getClass());
116
117
        $admin->setSubClasses(['foo' => 'bar']);
118
        $admin->setRequest(new Request(['subclass' => 'foo']));
119
        $this->assertSame('bar', $admin->getClass());
120
    }
121
122
    public function testGetClassException(): void
123
    {
124
        $this->expectException(\RuntimeException::class);
125
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
126
127
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
128
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
129
130
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
131
        $admin->setParentFieldDescription(new FieldDescription());
132
        $admin->setSubClasses(['foo' => 'bar']);
133
        $admin->setRequest(new Request(['subclass' => 'foo']));
134
        $admin->getClass();
135
    }
136
137
    public function testCheckAccessThrowsExceptionOnMadeUpAction(): void
138
    {
139
        $admin = new PostAdmin(
140
            'sonata.post.admin.post',
141
            'Application\Sonata\NewsBundle\Entity\Post',
142
            'SonataNewsBundle:PostAdmin'
143
        );
144
        $this->expectException(
145
            \InvalidArgumentException::class
146
        );
147
        $this->expectExceptionMessage(
148
            'Action "made-up" could not be found'
149
        );
150
        $admin->checkAccess('made-up');
151
    }
152
153
    public function testCheckAccessThrowsAccessDeniedException(): void
154
    {
155
        $admin = new PostAdmin(
156
            'sonata.post.admin.post',
157
            'Application\Sonata\NewsBundle\Entity\Post',
158
            'SonataNewsBundle:PostAdmin'
159
        );
160
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
161
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
162
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
163
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
164
        $customExtension->getAccessMapping($admin)->willReturn(
165
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
166
        );
167
        $admin->addExtension($customExtension->reveal());
168
        $admin->setSecurityHandler($securityHandler->reveal());
169
        $this->expectException(
170
            AccessDeniedException::class
171
        );
172
        $this->expectExceptionMessage(
173
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
174
        );
175
        $admin->checkAccess('custom_action');
176
    }
177
178
    public function testHasAccessOnMadeUpAction(): void
179
    {
180
        $admin = new PostAdmin(
181
            'sonata.post.admin.post',
182
            'Application\Sonata\NewsBundle\Entity\Post',
183
            'SonataNewsBundle:PostAdmin'
184
        );
185
186
        $this->assertFalse($admin->hasAccess('made-up'));
187
    }
188
189
    public function testHasAccess(): void
190
    {
191
        $admin = new PostAdmin(
192
            'sonata.post.admin.post',
193
            'Application\Sonata\NewsBundle\Entity\Post',
194
            'SonataNewsBundle:PostAdmin'
195
        );
196
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
197
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
198
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
199
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
200
        $customExtension->getAccessMapping($admin)->willReturn(
201
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
202
        );
203
        $admin->addExtension($customExtension->reveal());
204
        $admin->setSecurityHandler($securityHandler->reveal());
205
206
        $this->assertFalse($admin->hasAccess('custom_action'));
207
    }
208
209
    public function testHasAccessAllowsAccess(): void
210
    {
211
        $admin = new PostAdmin(
212
            'sonata.post.admin.post',
213
            'Application\Sonata\NewsBundle\Entity\Post',
214
            'SonataNewsBundle:PostAdmin'
215
        );
216
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
217
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
218
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
219
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
220
        $customExtension->getAccessMapping($admin)->willReturn(
221
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
222
        );
223
        $admin->addExtension($customExtension->reveal());
224
        $admin->setSecurityHandler($securityHandler->reveal());
225
226
        $this->assertTrue($admin->hasAccess('custom_action'));
227
    }
228
229
    public function testHasAccessAllowsAccessEditAction(): void
230
    {
231
        $admin = new PostAdmin(
232
            'sonata.post.admin.post',
233
            'Application\Sonata\NewsBundle\Entity\Post',
234
            'SonataNewsBundle:PostAdmin'
235
        );
236
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
237
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
238
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
239
        $customExtension->getAccessMapping($admin)->willReturn(
240
            ['edit_action' => ['EDIT_ROLE']]
241
        );
242
        $admin->addExtension($customExtension->reveal());
243
        $admin->setSecurityHandler($securityHandler->reveal());
244
245
        $this->assertTrue($admin->hasAccess('edit_action'));
246
    }
247
248
    /**
249
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
250
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
251
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
252
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
253
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
254
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
255
     */
256
    public function testChildren(): void
257
    {
258
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
259
        $this->assertFalse($postAdmin->hasChildren());
260
        $this->assertFalse($postAdmin->hasChild('comment'));
261
262
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
263
        $postAdmin->addChild($commentAdmin);
264
        $this->assertTrue($postAdmin->hasChildren());
265
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
266
267
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
268
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
269
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
270
271
        $this->assertFalse($postAdmin->isChild());
272
        $this->assertTrue($commentAdmin->isChild());
273
274
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
275
    }
276
277
    /**
278
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
279
     */
280
    public function testConfigure(): void
281
    {
282
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
283
        $this->assertNotNull($admin->getUniqid());
284
285
        $admin->initialize();
286
        $this->assertNotNull($admin->getUniqid());
287
        $this->assertSame('Post', $admin->getClassnameLabel());
288
289
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
290
        $admin->setClassnameLabel('postcomment');
291
292
        $admin->initialize();
293
        $this->assertSame('postcomment', $admin->getClassnameLabel());
294
    }
295
296
    public function testConfigureWithValidParentAssociationMapping(): void
297
    {
298
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
299
        $admin->setParentAssociationMapping('Category');
300
301
        $admin->initialize();
302
        $this->assertSame('Category', $admin->getParentAssociationMapping());
303
    }
304
305
    public function provideGetBaseRoutePattern()
306
    {
307
        return [
308
            [
309
                'Application\Sonata\NewsBundle\Entity\Post',
310
                '/sonata/news/post',
311
            ],
312
            [
313
                'Application\Sonata\NewsBundle\Document\Post',
314
                '/sonata/news/post',
315
            ],
316
            [
317
                'MyApplication\MyBundle\Entity\Post',
318
                '/myapplication/my/post',
319
            ],
320
            [
321
                'MyApplication\MyBundle\Entity\Post\Category',
322
                '/myapplication/my/post-category',
323
            ],
324
            [
325
                'MyApplication\MyBundle\Entity\Product\Category',
326
                '/myapplication/my/product-category',
327
            ],
328
            [
329
                'MyApplication\MyBundle\Entity\Other\Product\Category',
330
                '/myapplication/my/other-product-category',
331
            ],
332
            [
333
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
334
                '/cmf/foo/menu',
335
            ],
336
            [
337
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
338
                '/cmf/foo/menu',
339
            ],
340
            [
341
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
342
                '/symfony/barbar/menu',
343
            ],
344
            [
345
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
346
                '/symfony/barbar/menu-item',
347
            ],
348
            [
349
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
350
                '/cmf/foo/menu',
351
            ],
352
            [
353
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
354
                '/cmf/foo/menu',
355
            ],
356
            [
357
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
358
                '/cmf/foo/menu',
359
            ],
360
            [
361
                'AppBundle\Entity\User',
362
                '/app/user',
363
            ],
364
            [
365
                'App\Entity\User',
366
                '/app/user',
367
            ],
368
        ];
369
    }
370
371
    /**
372
     * @dataProvider provideGetBaseRoutePattern
373
     */
374
    public function testGetBaseRoutePattern($objFqn, $expected): void
375
    {
376
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
377
        $this->assertSame($expected, $admin->getBaseRoutePattern());
378
    }
379
380
    /**
381
     * @dataProvider provideGetBaseRoutePattern
382
     */
383
    public function testGetBaseRoutePatternWithChildAdmin($objFqn, $expected): void
384
    {
385
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
386
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
387
        $commentAdmin->setParent($postAdmin);
388
389
        $this->assertSame($expected.'/{id}/comment', $commentAdmin->getBaseRoutePattern());
390
    }
391
392
    /**
393
     * @dataProvider provideGetBaseRoutePattern
394
     */
395
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin($objFqn, $expected): void
396
    {
397
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
398
        $commentAdmin = new CommentAdmin(
399
            'sonata.post.admin.comment',
400
            'Application\Sonata\NewsBundle\Entity\Comment',
401
            'SonataNewsBundle:CommentAdmin'
402
        );
403
        $commentVoteAdmin = new CommentVoteAdmin(
404
            'sonata.post.admin.comment_vote',
405
            'Application\Sonata\NewsBundle\Entity\CommentVote',
406
            'SonataNewsBundle:CommentVoteAdmin'
407
        );
408
        $commentAdmin->setParent($postAdmin);
409
        $commentVoteAdmin->setParent($commentAdmin);
410
411
        $this->assertSame($expected.'/{id}/comment/{childId}/commentvote', $commentVoteAdmin->getBaseRoutePattern());
412
    }
413
414
    public function testGetBaseRoutePatternWithSpecifedPattern(): void
415
    {
416
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostWithCustomRouteAdmin');
417
418
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
419
    }
420
421
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern(): void
422
    {
423
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
424
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
425
        $commentAdmin->setParent($postAdmin);
426
427
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
428
    }
429
430
    public function testGetBaseRoutePatternWithUnreconizedClassname(): void
431
    {
432
        $this->expectException(\RuntimeException::class);
433
434
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
435
        $admin->getBaseRoutePattern();
436
    }
437
438
    public function provideGetBaseRouteName()
439
    {
440
        return [
441
            [
442
                'Application\Sonata\NewsBundle\Entity\Post',
443
                'admin_sonata_news_post',
444
            ],
445
            [
446
                'Application\Sonata\NewsBundle\Document\Post',
447
                'admin_sonata_news_post',
448
            ],
449
            [
450
                'MyApplication\MyBundle\Entity\Post',
451
                'admin_myapplication_my_post',
452
            ],
453
            [
454
                'MyApplication\MyBundle\Entity\Post\Category',
455
                'admin_myapplication_my_post_category',
456
            ],
457
            [
458
                'MyApplication\MyBundle\Entity\Product\Category',
459
                'admin_myapplication_my_product_category',
460
            ],
461
            [
462
                'MyApplication\MyBundle\Entity\Other\Product\Category',
463
                'admin_myapplication_my_other_product_category',
464
            ],
465
            [
466
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
467
                'admin_cmf_foo_menu',
468
            ],
469
            [
470
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
471
                'admin_cmf_foo_menu',
472
            ],
473
            [
474
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
475
                'admin_symfony_barbar_menu',
476
            ],
477
            [
478
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
479
                'admin_symfony_barbar_menu_item',
480
            ],
481
            [
482
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
483
                'admin_cmf_foo_menu',
484
            ],
485
            [
486
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
487
                'admin_cmf_foo_menu',
488
            ],
489
            [
490
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
491
                'admin_cmf_foo_menu',
492
            ],
493
            [
494
                'AppBundle\Entity\User',
495
                'admin_app_user',
496
            ],
497
            [
498
                'App\Entity\User',
499
                'admin_app_user',
500
            ],
501
        ];
502
    }
503
504
    /**
505
     * @dataProvider provideGetBaseRouteName
506
     */
507
    public function testGetBaseRouteName($objFqn, $expected): void
508
    {
509
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
510
511
        $this->assertSame($expected, $admin->getBaseRouteName());
512
    }
513
514
    /**
515
     * @dataProvider provideGetBaseRouteName
516
     */
517
    public function testGetBaseRouteNameWithChildAdmin($objFqn, $expected): void
518
    {
519
        $routeGenerator = new DefaultRouteGenerator(
520
            $this->createMock(RouterInterface::class),
521
            new RoutesCache($this->cacheTempFolder, true)
522
        );
523
524
        $container = new Container();
525
        $pool = new Pool($container, 'Sonata Admin', '/path/to/pic.png');
526
527
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
528
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
529
        $container->set('sonata.post.admin.post', $postAdmin);
530
        $postAdmin->setConfigurationPool($pool);
531
        $postAdmin->setRouteBuilder($pathInfo);
532
        $postAdmin->setRouteGenerator($routeGenerator);
533
        $postAdmin->initialize();
534
535
        $commentAdmin = new CommentAdmin(
536
            'sonata.post.admin.comment',
537
            'Application\Sonata\NewsBundle\Entity\Comment',
538
            'SonataNewsBundle:CommentAdmin'
539
        );
540
        $container->set('sonata.post.admin.comment', $commentAdmin);
541
        $commentAdmin->setConfigurationPool($pool);
542
        $commentAdmin->setRouteBuilder($pathInfo);
543
        $commentAdmin->setRouteGenerator($routeGenerator);
544
        $commentAdmin->initialize();
545
546
        $postAdmin->addChild($commentAdmin);
547
548
        $commentVoteAdmin = new CommentVoteAdmin(
549
            'sonata.post.admin.comment_vote',
550
            'Application\Sonata\NewsBundle\Entity\CommentVote',
551
            'SonataNewsBundle:CommentVoteAdmin'
552
        );
553
        $container->set('sonata.post.admin.comment_vote', $commentVoteAdmin);
554
        $commentVoteAdmin->setConfigurationPool($pool);
555
        $commentVoteAdmin->setRouteBuilder($pathInfo);
556
        $commentVoteAdmin->setRouteGenerator($routeGenerator);
557
        $commentVoteAdmin->initialize();
558
559
        $commentAdmin->addChild($commentVoteAdmin);
560
        $pool->setAdminServiceIds([
561
            'sonata.post.admin.post',
562
            'sonata.post.admin.comment',
563
            'sonata.post.admin.comment_vote',
564
        ]);
565
566
        $this->assertSame($expected.'_comment', $commentAdmin->getBaseRouteName());
567
568
        $this->assertTrue($postAdmin->hasRoute('show'));
569
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show'));
570
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.show'));
571
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment|sonata.post.admin.comment_vote.show'));
572
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment.list'));
573
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment|sonata.post.admin.comment_vote.list'));
574
        $this->assertFalse($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.edit'));
575
        $this->assertFalse($commentAdmin->hasRoute('edit'));
576
577
        /*
578
         * Test the route name from request
579
         */
580
        $postListRequest = new Request(
581
            [],
582
            [],
583
            [
584
                '_route' => $postAdmin->getBaseRouteName().'_list',
585
            ]
586
        );
587
588
        $postAdmin->setRequest($postListRequest);
589
        $commentAdmin->setRequest($postListRequest);
590
591
        $this->assertTrue($postAdmin->isCurrentRoute('list'));
592
        $this->assertFalse($postAdmin->isCurrentRoute('create'));
593
        $this->assertFalse($commentAdmin->isCurrentRoute('list'));
594
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('list'));
595
        $this->assertTrue($commentAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
596
        $this->assertFalse($commentAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
597
        $this->assertTrue($commentVoteAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
598
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
599
    }
600
601
    public function testGetBaseRouteNameWithUnreconizedClassname(): void
602
    {
603
        $this->expectException(\RuntimeException::class);
604
605
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
606
        $admin->getBaseRouteName();
607
    }
608
609
    public function testGetBaseRouteNameWithSpecifiedName(): void
610
    {
611
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
612
613
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
614
    }
615
616
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName(): void
617
    {
618
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
619
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
620
        $commentAdmin->setParent($postAdmin);
621
622
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
623
    }
624
625
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName(): void
626
    {
627
        $postAdmin = new PostAdmin(
628
            'sonata.post.admin.post',
629
            'Application\Sonata\NewsBundle\Entity\Post',
630
            'SonataNewsBundle:PostAdmin'
631
        );
632
        $commentAdmin = new CommentWithCustomRouteAdmin(
633
            'sonata.post.admin.comment_with_custom_route',
634
            'Application\Sonata\NewsBundle\Entity\Comment',
635
            'SonataNewsBundle:CommentWithCustomRouteAdmin'
636
        );
637
        $commentVoteAdmin = new CommentVoteAdmin(
638
            'sonata.post.admin.comment_vote',
639
            'Application\Sonata\NewsBundle\Entity\CommentVote',
640
            'SonataNewsBundle:CommentVoteAdmin'
641
        );
642
        $commentAdmin->setParent($postAdmin);
643
        $commentVoteAdmin->setParent($commentAdmin);
644
645
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
646
    }
647
648
    /**
649
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
650
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
651
     */
652
    public function testUniqid(): void
653
    {
654
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
655
656
        $uniqid = uniqid();
657
        $admin->setUniqid($uniqid);
658
659
        $this->assertSame($uniqid, $admin->getUniqid());
660
    }
661
662
    public function testToString(): void
663
    {
664
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
665
666
        $s = new \stdClass();
667
668
        $this->assertNotEmpty($admin->toString($s));
669
670
        $s = new FooToString();
671
        $this->assertSame('salut', $admin->toString($s));
672
673
        // To string method is implemented, but returns null
674
        $s = new FooToStringNull();
675
        $this->assertNotEmpty($admin->toString($s));
676
677
        $this->assertSame('', $admin->toString(false));
678
    }
679
680
    public function testIsAclEnabled(): void
681
    {
682
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
683
684
        $this->assertFalse($postAdmin->isAclEnabled());
685
686
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
687
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
688
        $this->assertTrue($commentAdmin->isAclEnabled());
689
    }
690
691
    /**
692
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
693
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
694
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
695
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
696
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
697
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
698
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
699
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
700
     */
701
    public function testSubClass(): void
702
    {
703
        $admin = new PostAdmin(
704
            'sonata.post.admin.post',
705
            Post::class,
706
            'SonataNewsBundle:PostAdmin'
707
        );
708
        $this->assertFalse($admin->hasSubClass('test'));
709
        $this->assertFalse($admin->hasActiveSubClass());
710
        $this->assertCount(0, $admin->getSubClasses());
711
        $this->assertNull($admin->getActiveSubClass());
712
        $this->assertNull($admin->getActiveSubclassCode());
713
        $this->assertSame(Post::class, $admin->getClass());
714
715
        // Just for the record, if there is no inheritance set, the getSubject is not used
716
        // the getSubject can also lead to some issue
717
        $admin->setSubject(new BlogPost());
718
        $this->assertSame(BlogPost::class, $admin->getClass());
719
720
        $admin->setSubClasses([
721
            'extended1' => 'NewsBundle\Entity\PostExtended1',
722
            'extended2' => 'NewsBundle\Entity\PostExtended2',
723
        ]);
724
        $this->assertFalse($admin->hasSubClass('test'));
725
        $this->assertTrue($admin->hasSubClass('extended1'));
726
        $this->assertFalse($admin->hasActiveSubClass());
727
        $this->assertCount(2, $admin->getSubClasses());
728
        $this->assertNull($admin->getActiveSubClass());
729
        $this->assertNull($admin->getActiveSubclassCode());
730
        $this->assertSame(
731
            BlogPost::class,
732
            $admin->getClass(),
733
            'When there is no subclass in the query the class parameter should be returned'
734
        );
735
736
        $request = new Request(['subclass' => 'extended1']);
737
        $admin->setRequest($request);
738
        $this->assertFalse($admin->hasSubClass('test'));
739
        $this->assertTrue($admin->hasSubClass('extended1'));
740
        $this->assertTrue($admin->hasActiveSubClass());
741
        $this->assertCount(2, $admin->getSubClasses());
742
        $this->assertSame(
743
            'NewsBundle\Entity\PostExtended1',
744
            $admin->getActiveSubClass(),
745
            'It should return the curently active sub class.'
746
        );
747
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
748
        $this->assertSame(
749
            'NewsBundle\Entity\PostExtended1',
750
            $admin->getClass(),
751
            'getClass() should return the name of the sub class when passed through a request query parameter.'
752
        );
753
754
        $request->query->set('subclass', 'inject');
755
        $this->assertNull($admin->getActiveSubclassCode());
756
    }
757
758
    public function testNonExistantSubclass(): void
759
    {
760
        $this->expectException(\RuntimeException::class);
761
762
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
763
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
764
765
        $admin->setRequest(new Request(['subclass' => 'inject']));
766
767
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
768
769
        $this->assertTrue($admin->hasActiveSubClass());
770
771
        $admin->getActiveSubClass();
772
    }
773
774
    /**
775
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
776
     */
777
    public function testOnlyOneSubclassNeededToBeActive(): void
778
    {
779
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
780
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
781
        $request = new Request(['subclass' => 'extended1']);
782
        $admin->setRequest($request);
783
        $this->assertTrue($admin->hasActiveSubClass());
784
    }
785
786
    /**
787
     * @group legacy
788
     * @expectedDeprecation Method "Sonata\AdminBundle\Admin\AbstractAdmin::addSubClass" is deprecated since 3.30 and will be removed in 4.0.
789
     */
790
    public function testAddSubClassIsDeprecated(): void
791
    {
792
        $admin = new PostAdmin(
793
            'sonata.post.admin.post',
794
            Post::class,
795
            'SonataNewsBundle:PostAdmin'
796
        );
797
        $admin->addSubClass('whatever');
798
    }
799
800
    public function testGetPerPageOptions(): void
801
    {
802
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
803
804
        $this->assertSame([16, 32, 64, 128, 192], $admin->getPerPageOptions());
805
        $admin->setPerPageOptions([500, 1000]);
806
        $this->assertSame([500, 1000], $admin->getPerPageOptions());
807
    }
808
809
    public function testGetLabelTranslatorStrategy(): void
810
    {
811
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
812
813
        $this->assertNull($admin->getLabelTranslatorStrategy());
814
815
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
816
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
817
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
818
    }
819
820
    public function testGetRouteBuilder(): void
821
    {
822
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
823
824
        $this->assertNull($admin->getRouteBuilder());
825
826
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
827
        $admin->setRouteBuilder($routeBuilder);
828
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
829
    }
830
831
    public function testGetMenuFactory(): void
832
    {
833
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
834
835
        $this->assertNull($admin->getMenuFactory());
836
837
        $menuFactory = $this->createMock(FactoryInterface::class);
838
        $admin->setMenuFactory($menuFactory);
839
        $this->assertSame($menuFactory, $admin->getMenuFactory());
840
    }
841
842
    public function testGetExtensions(): void
843
    {
844
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
845
846
        $this->assertSame([], $admin->getExtensions());
847
848
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
849
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
850
851
        $admin->addExtension($adminExtension1);
852
        $admin->addExtension($adminExtension2);
853
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
854
    }
855
856
    public function testGetFilterTheme(): void
857
    {
858
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
859
860
        $this->assertSame([], $admin->getFilterTheme());
861
862
        $admin->setFilterTheme(['FooTheme']);
863
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
864
    }
865
866
    public function testGetFormTheme(): void
867
    {
868
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
869
870
        $this->assertSame([], $admin->getFormTheme());
871
872
        $admin->setFormTheme(['FooTheme']);
873
874
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
875
    }
876
877
    public function testGetValidator(): void
878
    {
879
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
880
881
        $this->assertNull($admin->getValidator());
882
883
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
884
885
        $admin->setValidator($validator);
886
        $this->assertSame($validator, $admin->getValidator());
887
    }
888
889
    public function testGetSecurityHandler(): void
890
    {
891
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
892
893
        $this->assertNull($admin->getSecurityHandler());
894
895
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
896
        $admin->setSecurityHandler($securityHandler);
897
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
898
    }
899
900
    public function testGetSecurityInformation(): void
901
    {
902
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
903
904
        $this->assertSame([], $admin->getSecurityInformation());
905
906
        $securityInformation = [
907
            'GUEST' => ['VIEW', 'LIST'],
908
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
909
        ];
910
911
        $admin->setSecurityInformation($securityInformation);
912
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
913
    }
914
915
    public function testGetManagerType(): void
916
    {
917
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
918
919
        $this->assertNull($admin->getManagerType());
920
921
        $admin->setManagerType('foo_orm');
922
        $this->assertSame('foo_orm', $admin->getManagerType());
923
    }
924
925
    public function testGetModelManager(): void
926
    {
927
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
928
929
        $this->assertNull($admin->getModelManager());
930
931
        $modelManager = $this->createMock(ModelManagerInterface::class);
932
933
        $admin->setModelManager($modelManager);
934
        $this->assertSame($modelManager, $admin->getModelManager());
935
    }
936
937
    public function testGetBaseCodeRoute(): void
938
    {
939
        $postAdmin = new PostAdmin(
940
            'sonata.post.admin.post',
941
            'NewsBundle\Entity\Post',
942
            'SonataNewsBundle:PostAdmin'
943
        );
944
        $commentAdmin = new CommentAdmin(
945
            'sonata.post.admin.comment',
946
            'Application\Sonata\NewsBundle\Entity\Comment',
947
            'SonataNewsBundle:CommentAdmin'
948
        );
949
950
        $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
951
952
        $postAdmin->addChild($commentAdmin);
953
954
        $this->assertSame(
955
            'sonata.post.admin.post|sonata.post.admin.comment',
956
            $commentAdmin->getBaseCodeRoute()
957
        );
958
    }
959
960
    public function testGetRouteGenerator(): void
961
    {
962
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
963
964
        $this->assertNull($admin->getRouteGenerator());
965
966
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
967
968
        $admin->setRouteGenerator($routeGenerator);
969
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
970
    }
971
972
    public function testGetConfigurationPool(): void
973
    {
974
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
975
976
        $this->assertNull($admin->getConfigurationPool());
977
978
        $pool = $this->getMockBuilder(Pool::class)
979
            ->disableOriginalConstructor()
980
            ->getMock();
981
982
        $admin->setConfigurationPool($pool);
983
        $this->assertSame($pool, $admin->getConfigurationPool());
984
    }
985
986
    public function testGetShowBuilder(): void
987
    {
988
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
989
990
        $this->assertNull($admin->getShowBuilder());
991
992
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
993
994
        $admin->setShowBuilder($showBuilder);
995
        $this->assertSame($showBuilder, $admin->getShowBuilder());
996
    }
997
998
    public function testGetListBuilder(): void
999
    {
1000
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1001
1002
        $this->assertNull($admin->getListBuilder());
1003
1004
        $listBuilder = $this->createMock(ListBuilderInterface::class);
1005
1006
        $admin->setListBuilder($listBuilder);
1007
        $this->assertSame($listBuilder, $admin->getListBuilder());
1008
    }
1009
1010
    public function testGetDatagridBuilder(): void
1011
    {
1012
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1013
1014
        $this->assertNull($admin->getDatagridBuilder());
1015
1016
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1017
1018
        $admin->setDatagridBuilder($datagridBuilder);
1019
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
1020
    }
1021
1022
    public function testGetFormContractor(): void
1023
    {
1024
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1025
1026
        $this->assertNull($admin->getFormContractor());
1027
1028
        $formContractor = $this->createMock(FormContractorInterface::class);
1029
1030
        $admin->setFormContractor($formContractor);
1031
        $this->assertSame($formContractor, $admin->getFormContractor());
1032
    }
1033
1034
    public function testGetRequest(): void
1035
    {
1036
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1037
1038
        $this->assertFalse($admin->hasRequest());
1039
1040
        $request = new Request();
1041
1042
        $admin->setRequest($request);
1043
        $this->assertSame($request, $admin->getRequest());
1044
        $this->assertTrue($admin->hasRequest());
1045
    }
1046
1047
    public function testGetRequestWithException(): void
1048
    {
1049
        $this->expectException(\RuntimeException::class);
1050
        $this->expectExceptionMessage('The Request object has not been set');
1051
1052
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1053
        $admin->getRequest();
1054
    }
1055
1056
    public function testGetTranslationDomain(): void
1057
    {
1058
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1059
1060
        $this->assertSame('messages', $admin->getTranslationDomain());
1061
1062
        $admin->setTranslationDomain('foo');
1063
        $this->assertSame('foo', $admin->getTranslationDomain());
1064
    }
1065
1066
    /**
1067
     * @group legacy
1068
     */
1069
    public function testGetTranslator(): void
1070
    {
1071
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1072
1073
        $this->assertNull($admin->getTranslator());
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::getTranslator() has been deprecated with message: since 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...
1074
1075
        $translator = $this->createMock(TranslatorInterface::class);
1076
1077
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 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...
1078
        $this->assertSame($translator, $admin->getTranslator());
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::getTranslator() has been deprecated with message: since 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...
1079
    }
1080
1081
    public function testGetShowGroups(): void
1082
    {
1083
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1084
1085
        $this->assertFalse($admin->getShowGroups());
1086
1087
        $groups = ['foo', 'bar', 'baz'];
1088
1089
        $admin->setShowGroups($groups);
1090
        $this->assertSame($groups, $admin->getShowGroups());
1091
    }
1092
1093
    public function testGetFormGroups(): void
1094
    {
1095
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1096
1097
        $this->assertFalse($admin->getFormGroups());
1098
1099
        $groups = ['foo', 'bar', 'baz'];
1100
1101
        $admin->setFormGroups($groups);
1102
        $this->assertSame($groups, $admin->getFormGroups());
1103
    }
1104
1105
    public function testGetMaxPageLinks(): void
1106
    {
1107
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1108
1109
        $this->assertSame(25, $admin->getMaxPageLinks());
1110
1111
        $admin->setMaxPageLinks(14);
1112
        $this->assertSame(14, $admin->getMaxPageLinks());
1113
    }
1114
1115
    public function testGetMaxPerPage(): void
1116
    {
1117
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1118
1119
        $this->assertSame(32, $admin->getMaxPerPage());
1120
1121
        $admin->setMaxPerPage(94);
1122
        $this->assertSame(94, $admin->getMaxPerPage());
1123
    }
1124
1125
    public function testGetLabel(): void
1126
    {
1127
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1128
1129
        $this->assertNull($admin->getLabel());
1130
1131
        $admin->setLabel('FooLabel');
1132
        $this->assertSame('FooLabel', $admin->getLabel());
1133
    }
1134
1135
    public function testGetBaseController(): void
1136
    {
1137
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1138
1139
        $this->assertSame('SonataNewsBundle:PostAdmin', $admin->getBaseControllerName());
1140
1141
        $admin->setBaseControllerName('SonataNewsBundle:FooAdmin');
1142
        $this->assertSame('SonataNewsBundle:FooAdmin', $admin->getBaseControllerName());
1143
    }
1144
1145
    public function testGetTemplates(): void
1146
    {
1147
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1148
1149
        $templates = [
1150
            'list' => '@FooAdmin/CRUD/list.html.twig',
1151
            'show' => '@FooAdmin/CRUD/show.html.twig',
1152
            'edit' => '@FooAdmin/CRUD/edit.html.twig',
1153
        ];
1154
1155
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1156
        $templateRegistry->getTemplates()->shouldBeCalled()->willReturn($templates);
1157
1158
        $admin->setTemplateRegistry($templateRegistry->reveal());
1159
1160
        $this->assertSame($templates, $admin->getTemplates());
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...ctAdmin::getTemplates() has been deprecated with message: since 3.x, will be dropped in 4.0. Use TemplateRegistry services instead

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...
1161
    }
1162
1163
    public function testGetTemplate1(): void
1164
    {
1165
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1166
1167
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1168
        $templateRegistry->getTemplate('edit')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/edit.html.twig');
1169
        $templateRegistry->getTemplate('show')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/show.html.twig');
1170
1171
        $admin->setTemplateRegistry($templateRegistry->reveal());
1172
1173
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since 3.x, will be dropped in 4.0. Use TemplateRegistry services instead

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...
1174
        $this->assertSame('@FooAdmin/CRUD/show.html.twig', $admin->getTemplate('show'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since 3.x, will be dropped in 4.0. Use TemplateRegistry services instead

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...
1175
    }
1176
1177
    public function testGetIdParameter(): void
1178
    {
1179
        $postAdmin = new PostAdmin(
1180
            'sonata.post.admin.post',
1181
            'NewsBundle\Entity\Post',
1182
            'SonataNewsBundle:PostAdmin'
1183
        );
1184
1185
        $this->assertSame('id', $postAdmin->getIdParameter());
1186
        $this->assertFalse($postAdmin->isChild());
1187
1188
        $commentAdmin = new CommentAdmin(
1189
            'sonata.post.admin.comment',
1190
            'Application\Sonata\NewsBundle\Entity\Comment',
1191
            'SonataNewsBundle:CommentAdmin'
1192
        );
1193
        $commentAdmin->setParent($postAdmin);
1194
1195
        $this->assertTrue($commentAdmin->isChild());
1196
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1197
1198
        $commentVoteAdmin = new CommentVoteAdmin(
1199
            'sonata.post.admin.comment_vote',
1200
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1201
            'SonataNewsBundle:CommentVoteAdmin'
1202
        );
1203
        $commentVoteAdmin->setParent($commentAdmin);
1204
1205
        $this->assertTrue($commentVoteAdmin->isChild());
1206
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1207
    }
1208
1209
    public function testGetExportFormats(): void
1210
    {
1211
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1212
1213
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1214
    }
1215
1216
    public function testGetUrlsafeIdentifier(): void
1217
    {
1218
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1219
1220
        $entity = new \stdClass();
1221
1222
        $modelManager = $this->createMock(ModelManagerInterface::class);
1223
        $modelManager->expects($this->once())
1224
            ->method('getUrlsafeIdentifier')
1225
            ->with($this->equalTo($entity))
1226
            ->will($this->returnValue('foo'));
1227
        $admin->setModelManager($modelManager);
1228
1229
        $this->assertSame('foo', $admin->getUrlsafeIdentifier($entity));
1230
    }
1231
1232
    public function testDeterminedPerPageValue(): void
1233
    {
1234
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1235
1236
        $this->assertFalse($admin->determinedPerPageValue('foo'));
1237
        $this->assertFalse($admin->determinedPerPageValue(123));
1238
        $this->assertTrue($admin->determinedPerPageValue(16));
1239
        $this->assertTrue($admin->determinedPerPageValue(32));
1240
        $this->assertTrue($admin->determinedPerPageValue(64));
1241
        $this->assertTrue($admin->determinedPerPageValue(128));
1242
        $this->assertTrue($admin->determinedPerPageValue(192));
1243
1244
        $admin->setPerPageOptions([101, 102, 103]);
1245
        $this->assertFalse($admin->determinedPerPageValue(15));
1246
        $this->assertFalse($admin->determinedPerPageValue(25));
1247
        $this->assertFalse($admin->determinedPerPageValue(200));
1248
        $this->assertTrue($admin->determinedPerPageValue(101));
1249
        $this->assertTrue($admin->determinedPerPageValue(102));
1250
        $this->assertTrue($admin->determinedPerPageValue(103));
1251
    }
1252
1253
    public function testIsGranted(): void
1254
    {
1255
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1256
1257
        $entity = new \stdClass();
1258
1259
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1260
        $securityHandler->expects($this->any())
1261
            ->method('isGranted')
1262
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin, $entity) {
1263
                if ($admin == $adminIn && 'FOO' == $attributes) {
1264
                    if (($object == $admin) || ($object == $entity)) {
1265
                        return true;
1266
                    }
1267
                }
1268
1269
                return false;
1270
            }));
1271
1272
        $admin->setSecurityHandler($securityHandler);
1273
1274
        $this->assertTrue($admin->isGranted('FOO'));
1275
        $this->assertTrue($admin->isGranted('FOO', $entity));
1276
        $this->assertFalse($admin->isGranted('BAR'));
1277
        $this->assertFalse($admin->isGranted('BAR', $entity));
1278
    }
1279
1280
    public function testSupportsPreviewMode(): void
1281
    {
1282
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1283
1284
        $this->assertFalse($admin->supportsPreviewMode());
1285
    }
1286
1287
    public function testGetPermissionsShow(): void
1288
    {
1289
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1290
1291
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1292
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1293
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1294
    }
1295
1296
    public function testShowIn(): void
1297
    {
1298
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1299
1300
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1301
        $securityHandler->expects($this->any())
1302
            ->method('isGranted')
1303
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin) {
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...
1304
                if ($admin == $adminIn && $attributes == ['LIST']) {
1305
                    return true;
1306
                }
1307
1308
                return false;
1309
            }));
1310
1311
        $admin->setSecurityHandler($securityHandler);
1312
1313
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1314
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1315
        $this->assertTrue($admin->showIn('foo'));
1316
    }
1317
1318
    public function testGetObjectIdentifier(): void
1319
    {
1320
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1321
1322
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1323
    }
1324
1325
    /**
1326
     * @group legacy
1327
     */
1328
    public function testTrans(): void
1329
    {
1330
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1331
        $admin->setTranslationDomain('fooMessageDomain');
1332
1333
        $translator = $this->createMock(TranslatorInterface::class);
1334
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 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...
1335
1336
        $translator->expects($this->once())
1337
            ->method('trans')
1338
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1339
            ->will($this->returnValue('fooTranslated'));
1340
1341
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1342
    }
1343
1344
    /**
1345
     * @group legacy
1346
     */
1347
    public function testTransWithMessageDomain(): void
1348
    {
1349
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1350
1351
        $translator = $this->createMock(TranslatorInterface::class);
1352
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 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...
1353
1354
        $translator->expects($this->once())
1355
            ->method('trans')
1356
            ->with($this->equalTo('foo'), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1357
            ->will($this->returnValue('fooTranslated'));
1358
1359
        $this->assertSame('fooTranslated', $admin->trans('foo', ['name' => 'Andrej'], 'fooMessageDomain'));
1360
    }
1361
1362
    /**
1363
     * @group legacy
1364
     */
1365
    public function testTransChoice(): void
1366
    {
1367
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1368
        $admin->setTranslationDomain('fooMessageDomain');
1369
1370
        $translator = $this->createMock(TranslatorInterface::class);
1371
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 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...
1372
1373
        $translator->expects($this->once())
1374
            ->method('transChoice')
1375
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1376
            ->will($this->returnValue('fooTranslated'));
1377
1378
        $this->assertSame('fooTranslated', $admin->transChoice('foo', 2));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::transChoice() has been deprecated with message: since 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...
1379
    }
1380
1381
    /**
1382
     * @group legacy
1383
     */
1384
    public function testTransChoiceWithMessageDomain(): void
1385
    {
1386
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1387
1388
        $translator = $this->createMock(TranslatorInterface::class);
1389
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 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...
1390
1391
        $translator->expects($this->once())
1392
            ->method('transChoice')
1393
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1394
            ->will($this->returnValue('fooTranslated'));
1395
1396
        $this->assertSame('fooTranslated', $admin->transChoice('foo', 2, ['name' => 'Andrej'], 'fooMessageDomain'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::transChoice() has been deprecated with message: since 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...
1397
    }
1398
1399
    public function testSetFilterPersister(): void
1400
    {
1401
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1402
1403
        $filterPersister = $this->createMock('Sonata\AdminBundle\Filter\Persister\FilterPersisterInterface');
1404
1405
        $this->assertAttributeSame(null, 'filterPersister', $admin);
1406
        $admin->setFilterPersister($filterPersister);
1407
        $this->assertAttributeSame($filterPersister, 'filterPersister', $admin);
1408
    }
1409
1410
    public function testGetRootCode(): void
1411
    {
1412
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1413
1414
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1415
1416
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1417
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1418
        $parentFieldDescription->expects($this->once())
1419
            ->method('getAdmin')
1420
            ->will($this->returnValue($parentAdmin));
1421
1422
        $this->assertNull($admin->getParentFieldDescription());
1423
        $admin->setParentFieldDescription($parentFieldDescription);
1424
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1425
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1426
    }
1427
1428
    public function testGetRoot(): void
1429
    {
1430
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1431
1432
        $this->assertSame($admin, $admin->getRoot());
1433
1434
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1435
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1436
        $parentFieldDescription->expects($this->once())
1437
            ->method('getAdmin')
1438
            ->will($this->returnValue($parentAdmin));
1439
1440
        $this->assertNull($admin->getParentFieldDescription());
1441
        $admin->setParentFieldDescription($parentFieldDescription);
1442
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1443
        $this->assertSame($parentAdmin, $admin->getRoot());
1444
    }
1445
1446
    public function testGetExportFields(): void
1447
    {
1448
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1449
1450
        $modelManager = $this->createMock(ModelManagerInterface::class);
1451
        $modelManager->expects($this->once())
1452
            ->method('getExportFields')
1453
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1454
            ->will($this->returnValue(['foo', 'bar']));
1455
1456
        $admin->setModelManager($modelManager);
1457
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1458
    }
1459
1460
    public function testGetPersistentParametersWithNoExtension(): void
1461
    {
1462
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1463
1464
        $this->assertEmpty($admin->getPersistentParameters());
1465
    }
1466
1467
    public function testGetPersistentParametersWithInvalidExtension(): void
1468
    {
1469
        $this->expectException(\RuntimeException::class);
1470
1471
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1472
1473
        $extension = $this->createMock(AdminExtensionInterface::class);
1474
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue(null));
1475
1476
        $admin->addExtension($extension);
1477
1478
        $admin->getPersistentParameters();
1479
    }
1480
1481
    public function testGetPersistentParametersWithValidExtension(): void
1482
    {
1483
        $expected = [
1484
            'context' => 'foobar',
1485
        ];
1486
1487
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1488
1489
        $extension = $this->createMock(AdminExtensionInterface::class);
1490
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue($expected));
1491
1492
        $admin->addExtension($extension);
1493
1494
        $this->assertSame($expected, $admin->getPersistentParameters());
1495
    }
1496
1497
    public function testGetFormWithNonCollectionParentValue(): void
1498
    {
1499
        $post = new Post();
1500
        $tagAdmin = $this->createTagAdmin($post);
1501
        $tag = $tagAdmin->getSubject();
1502
1503
        $tag->setPosts(null);
1504
        $tagAdmin->getForm();
1505
        $this->assertSame($post, $tag->getPosts());
1506
    }
1507
1508
    public function testGetFormWithCollectionParentValue(): void
1509
    {
1510
        $post = new Post();
1511
        $tagAdmin = $this->createTagAdmin($post);
1512
        $tag = $tagAdmin->getSubject();
1513
1514
        // Case of a doctrine collection
1515
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1516
        $this->assertCount(0, $tag->getPosts());
1517
1518
        $tag->addPost(new Post());
1519
1520
        $this->assertCount(1, $tag->getPosts());
1521
1522
        $tagAdmin->getForm();
1523
1524
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1525
        $this->assertCount(2, $tag->getPosts());
1526
        $this->assertContains($post, $tag->getPosts());
1527
1528
        // Case of an array
1529
        $tag->setPosts([]);
1530
        $this->assertCount(0, $tag->getPosts());
1531
1532
        $tag->addPost(new Post());
1533
1534
        $this->assertCount(1, $tag->getPosts());
1535
1536
        $tagAdmin->getForm();
1537
1538
        $this->assertInternalType('array', $tag->getPosts());
1539
        $this->assertCount(2, $tag->getPosts());
1540
        $this->assertContains($post, $tag->getPosts());
1541
    }
1542
1543
    public function testFormAddPostSubmitEventForPreValidation(): void
1544
    {
1545
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1546
        $object = new \stdClass();
1547
1548
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1549
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1550
1551
        $validator = $this->createMock(ValidatorInterface::class);
1552
        $validator->expects($this->any())
1553
                ->method('getMetadataFor')
1554
                ->will($this->returnValue($this->createMock(MemberMetadata::class)));
1555
        $modelAdmin->setValidator($validator);
1556
1557
        $modelManager = $this->createMock(ModelManagerInterface::class);
1558
        $modelManager->expects($this->any())
1559
            ->method('getNewFieldDescriptionInstance')
1560
            ->will($this->returnValue(new FieldDescription()));
1561
        $modelAdmin->setModelManager($modelManager);
1562
1563
        // a Admin class to test that preValidate is called
1564
        $testAdminPreValidate = $this->createMock(AbstractAdmin::class, ['preValidate']);
1565
        $testAdminPreValidate->expects($this->once())
1566
                ->method('preValidate')
1567
                ->with($this->identicalTo($object));
1568
1569
        $event = $this->createMock(FormEvent::class);
1570
        $event->expects($this->any())
1571
                ->method('getData')
1572
                ->will($this->returnValue($object));
1573
1574
        $formBuild = $this->createMock(FormBuilder::class, ['addEventListener']);
1575
        $formBuild->expects($this->once())
1576
                ->method('addEventListener')
1577
                ->with($this->identicalTo(FormEvents::POST_SUBMIT),
1578
                        $this->callback(function ($callback) use ($testAdminPreValidate, $event) {
1579
                            if (is_callable($callback)) {
1580
                                $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...
1581
                                $closure($event);
1582
1583
                                return true;
1584
                            }
1585
1586
                            return false;
1587
                        }),
1588
                        $this->greaterThan(0)
1589
                    );
1590
1591
        $formContractor = $this->createMock(FormContractorInterface::class, ['getDefaultOptions', 'getFormBuilder']);
1592
        $formContractor->expects($this->any())
1593
                ->method('getDefaultOptions')
1594
                ->will($this->returnValue([]));
1595
        $formContractor->expects($this->any())
1596
                ->method('getFormBuilder')
1597
                ->will($this->returnValue($formBuild));
1598
1599
        $modelAdmin->setFormContractor($formContractor);
1600
        $modelAdmin->defineFormBuilder($formBuild);
1601
        $modelAdmin->getForm();
1602
    }
1603
1604
    public function testRemoveFieldFromFormGroup(): void
1605
    {
1606
        $formGroups = [
1607
            'foobar' => [
1608
                'fields' => [
1609
                    'foo' => 'foo',
1610
                    'bar' => 'bar',
1611
                ],
1612
            ],
1613
        ];
1614
1615
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1616
        $admin->setFormGroups($formGroups);
1617
1618
        $admin->removeFieldFromFormGroup('foo');
1619
        $this->assertSame($admin->getFormGroups(), [
1620
            'foobar' => [
1621
                'fields' => [
1622
                    'bar' => 'bar',
1623
                ],
1624
            ],
1625
        ]);
1626
1627
        $admin->removeFieldFromFormGroup('bar');
1628
        $this->assertSame($admin->getFormGroups(), []);
1629
    }
1630
1631
    public function testGetFilterParameters(): void
1632
    {
1633
        $authorId = uniqid();
1634
1635
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1636
1637
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1638
        $commentAdmin->setParentAssociationMapping('post.author');
1639
        $commentAdmin->setParent($postAdmin);
1640
1641
        $request = $this->createMock(Request::class, ['get']);
1642
        $query = $this->createMock(ParameterBag::class, ['get']);
1643
        $query->expects($this->any())
1644
            ->method('get')
1645
            ->will($this->returnValue([]));
1646
        $request->query = $query;
1647
        $request->expects($this->any())
1648
            ->method('get')
1649
            ->will($this->returnValue($authorId));
1650
1651
        $commentAdmin->setRequest($request);
1652
1653
        $modelManager = $this->createMock(ModelManagerInterface::class);
1654
        $modelManager->expects($this->any())
1655
            ->method('getDefaultSortValues')
1656
            ->will($this->returnValue([]));
1657
1658
        $commentAdmin->setModelManager($modelManager);
1659
1660
        $parameters = $commentAdmin->getFilterParameters();
1661
1662
        $this->assertTrue(isset($parameters['post__author']));
1663
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1664
    }
1665
1666
    public function testGetFilterFieldDescription(): void
1667
    {
1668
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1669
1670
        $fooFieldDescription = new FieldDescription();
1671
        $barFieldDescription = new FieldDescription();
1672
        $bazFieldDescription = new FieldDescription();
1673
1674
        $modelManager = $this->createMock(ModelManagerInterface::class);
1675
        $modelManager->expects($this->exactly(3))
1676
            ->method('getNewFieldDescriptionInstance')
1677
            ->will($this->returnCallback(function ($adminClass, $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...
1678
                switch ($name) {
1679
                    case 'foo':
1680
                        $fieldDescription = $fooFieldDescription;
1681
1682
                        break;
1683
1684
                    case 'bar':
1685
                        $fieldDescription = $barFieldDescription;
1686
1687
                        break;
1688
1689
                    case 'baz':
1690
                        $fieldDescription = $bazFieldDescription;
1691
1692
                        break;
1693
1694
                    default:
1695
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1696
                        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...
1697
                }
1698
1699
                $fieldDescription->setName($name);
1700
1701
                return $fieldDescription;
1702
            }));
1703
1704
        $modelAdmin->setModelManager($modelManager);
1705
1706
        $pager = $this->createMock(PagerInterface::class);
1707
1708
        $datagrid = $this->createMock(DatagridInterface::class);
1709
        $datagrid->expects($this->once())
1710
            ->method('getPager')
1711
            ->will($this->returnValue($pager));
1712
1713
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1714
        $datagridBuilder->expects($this->once())
1715
            ->method('getBaseDatagrid')
1716
            ->with($this->identicalTo($modelAdmin), [])
1717
            ->will($this->returnValue($datagrid));
1718
1719
        $datagridBuilder->expects($this->exactly(3))
1720
            ->method('addFilter')
1721
            ->will($this->returnCallback(function ($datagrid, $type, $fieldDescription, AdminInterface $admin): void {
1722
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1723
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1724
            }));
1725
1726
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1727
1728
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1729
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1730
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1731
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1732
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1733
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1734
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1735
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1736
    }
1737
1738
    public function testGetSubjectNoRequest(): void
1739
    {
1740
        $modelManager = $this->createMock(ModelManagerInterface::class);
1741
        $modelManager
1742
            ->expects($this->never())
1743
            ->method('find');
1744
1745
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1746
        $admin->setModelManager($modelManager);
1747
1748
        $this->assertNull($admin->getSubject());
1749
    }
1750
1751
    public function testGetSideMenu(): void
1752
    {
1753
        $item = $this->createMock(ItemInterface::class);
1754
        $item
1755
            ->expects($this->once())
1756
            ->method('setChildrenAttribute')
1757
            ->with('class', 'nav navbar-nav');
1758
        $item
1759
            ->expects($this->once())
1760
            ->method('setExtra')
1761
            ->with('translation_domain', 'foo_bar_baz');
1762
1763
        $menuFactory = $this->createMock(FactoryInterface::class);
1764
        $menuFactory
1765
            ->expects($this->once())
1766
            ->method('createItem')
1767
            ->will($this->returnValue($item));
1768
1769
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1770
        $modelAdmin->setMenuFactory($menuFactory);
1771
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1772
1773
        $modelAdmin->getSideMenu('foo');
1774
    }
1775
1776
    /**
1777
     * @return array
1778
     */
1779
    public function provideGetSubject()
1780
    {
1781
        return [
1782
            [23],
1783
            ['azerty'],
1784
            ['4f69bbb5f14a13347f000092'],
1785
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1786
            ['123'.AdapterInterface::ID_SEPARATOR.'my_type'], // composite keys are supported
1787
        ];
1788
    }
1789
1790
    /**
1791
     * @dataProvider provideGetSubject
1792
     */
1793
    public function testGetSubjectFailed($id): void
1794
    {
1795
        $modelManager = $this->createMock(ModelManagerInterface::class);
1796
        $modelManager
1797
            ->expects($this->once())
1798
            ->method('find')
1799
            ->with('NewsBundle\Entity\Post', $id)
1800
            ->will($this->returnValue(null)); // entity not found
1801
1802
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1803
        $admin->setModelManager($modelManager);
1804
1805
        $admin->setRequest(new Request(['id' => $id]));
1806
        $this->assertNull($admin->getSubject());
1807
    }
1808
1809
    /**
1810
     * @dataProvider provideGetSubject
1811
     */
1812
    public function testGetSubject($id): void
1813
    {
1814
        $entity = new Post();
1815
1816
        $modelManager = $this->createMock(ModelManagerInterface::class);
1817
        $modelManager
1818
            ->expects($this->once())
1819
            ->method('find')
1820
            ->with('NewsBundle\Entity\Post', $id)
1821
            ->will($this->returnValue($entity));
1822
1823
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1824
        $admin->setModelManager($modelManager);
1825
1826
        $admin->setRequest(new Request(['id' => $id]));
1827
        $this->assertSame($entity, $admin->getSubject());
1828
        $this->assertSame($entity, $admin->getSubject()); // model manager must be used only once
1829
    }
1830
1831
    public function testGetSubjectWithParentDescription(): void
1832
    {
1833
        $adminId = 1;
1834
1835
        $comment = new Comment();
1836
1837
        $modelManager = $this->createMock(ModelManagerInterface::class);
1838
        $modelManager
1839
            ->expects($this->any())
1840
            ->method('find')
1841
            ->with('NewsBundle\Entity\Comment', $adminId)
1842
            ->will($this->returnValue($comment));
1843
1844
        $request = new Request(['id' => $adminId]);
1845
1846
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1847
        $postAdmin->setRequest($request);
1848
1849
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1850
        $commentAdmin->setRequest($request);
1851
        $commentAdmin->setModelManager($modelManager);
1852
1853
        $this->assertEquals($comment, $commentAdmin->getSubject());
1854
1855
        $commentAdmin->setSubject(null);
0 ignored issues
show
Documentation introduced by
null is of type null, 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...
1856
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1857
1858
        $this->assertNull($commentAdmin->getSubject());
1859
    }
1860
1861
    /**
1862
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1863
     */
1864
    public function testGetActionButtonsList(): void
1865
    {
1866
        $expected = [
1867
            'create' => [
1868
                'template' => 'Foo.html.twig',
1869
            ],
1870
        ];
1871
1872
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1873
1874
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1875
        $templateRegistry->getTemplate('button_create')->willReturn('Foo.html.twig');
1876
1877
        $admin->setTemplateRegistry($templateRegistry->reveal());
1878
1879
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1880
        $securityHandler
1881
            ->expects($this->once())
1882
            ->method('isGranted')
1883
            ->with($admin, 'CREATE', $admin)
1884
            ->will($this->returnValue(true));
1885
        $admin->setSecurityHandler($securityHandler);
1886
1887
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1888
        $routeGenerator
1889
            ->expects($this->once())
1890
            ->method('hasAdminRoute')
1891
            ->with($admin, 'create')
1892
            ->will($this->returnValue(true));
1893
        $admin->setRouteGenerator($routeGenerator);
1894
1895
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1896
    }
1897
1898
    /**
1899
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1900
     */
1901
    public function testGetActionButtonsListCreateDisabled(): void
1902
    {
1903
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1904
1905
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1906
        $securityHandler
1907
            ->expects($this->once())
1908
            ->method('isGranted')
1909
            ->with($admin, 'CREATE', $admin)
1910
            ->will($this->returnValue(false));
1911
        $admin->setSecurityHandler($securityHandler);
1912
1913
        $this->assertSame([], $admin->getActionButtons('list', null));
1914
    }
1915
1916
    /**
1917
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1918
     */
1919
    public function testGetBatchActions(): void
1920
    {
1921
        $expected = [
1922
            'delete' => [
1923
                'label' => 'action_delete',
1924
                'translation_domain' => 'SonataAdminBundle',
1925
                'ask_confirmation' => true, // by default always true
1926
            ],
1927
            'foo' => [
1928
                'label' => 'action_foo',
1929
                'translation_domain' => 'SonataAdminBundle',
1930
            ],
1931
            'bar' => [
1932
                'label' => 'batch.label_bar',
1933
                'translation_domain' => 'SonataAdminBundle',
1934
            ],
1935
            'baz' => [
1936
                'label' => 'action_baz',
1937
                'translation_domain' => 'AcmeAdminBundle',
1938
            ],
1939
        ];
1940
1941
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1942
1943
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1944
        $labelTranslatorStrategy->expects($this->any())
1945
            ->method('getLabel')
1946
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
1947
                return $context.'.'.$type.'_'.$label;
1948
            }));
1949
1950
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1951
        $admin->setRouteBuilder($pathInfo);
1952
        $admin->setTranslationDomain('SonataAdminBundle');
1953
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1954
1955
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1956
        $routeGenerator
1957
            ->expects($this->once())
1958
            ->method('hasAdminRoute')
1959
            ->with($admin, 'delete')
1960
            ->will($this->returnValue(true));
1961
        $admin->setRouteGenerator($routeGenerator);
1962
1963
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1964
        $securityHandler->expects($this->any())
1965
            ->method('isGranted')
1966
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin) {
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...
1967
                if ($admin == $adminIn && 'DELETE' == $attributes) {
1968
                    return true;
1969
                }
1970
1971
                return false;
1972
            }));
1973
        $admin->setSecurityHandler($securityHandler);
1974
1975
        $this->assertSame($expected, $admin->getBatchActions());
1976
    }
1977
1978
    /**
1979
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1980
     */
1981
    public function testShowMosaicButton(): void
1982
    {
1983
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1984
        $listModes = $admin->getListModes();
1985
1986
        $admin->showMosaicButton(true);
1987
1988
        $this->assertSame($listModes, $admin->getListModes());
1989
    }
1990
1991
    /**
1992
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1993
     */
1994
    public function testShowMosaicButtonHideMosaic(): void
1995
    {
1996
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1997
        $listModes = $admin->getListModes();
1998
        $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...
1999
2000
        $admin->showMosaicButton(false);
2001
2002
        $this->assertSame($expected, $admin->getListModes());
2003
    }
2004
2005
    /**
2006
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
2007
     * @dataProvider provideGetBaseRouteName
2008
     */
2009
    public function testDefaultDashboardActionsArePresent($objFqn, $expected): void
2010
    {
2011
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
2012
2013
        $routeGenerator = new DefaultRouteGenerator(
2014
            $this->createMock(RouterInterface::class),
2015
            new RoutesCache($this->cacheTempFolder, true)
2016
        );
2017
2018
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
2019
        $admin->setRouteBuilder($pathInfo);
2020
        $admin->setRouteGenerator($routeGenerator);
2021
        $admin->initialize();
2022
2023
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
2024
        $templateRegistry->getTemplate('action_create')->willReturn('Foo.html.twig');
2025
2026
        $admin->setTemplateRegistry($templateRegistry->reveal());
2027
2028
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
2029
        $securityHandler->expects($this->any())
2030
            ->method('isGranted')
2031
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin) {
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...
2032
                if ($admin == $adminIn && ('CREATE' == $attributes || 'LIST' == $attributes)) {
2033
                    return true;
2034
                }
2035
2036
                return false;
2037
            }));
2038
2039
        $admin->setSecurityHandler($securityHandler);
2040
2041
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
2042
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
2043
    }
2044
2045
    public function testDefaultFilters(): void
2046
    {
2047
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
2048
2049
        $subjectId = uniqid();
2050
2051
        $request = $this->createMock(Request::class, ['get']);
2052
        $query = $this->createMock(ParameterBag::class, ['set', 'get']);
2053
        $query->expects($this->any())
2054
            ->method('get')
2055
            ->with($this->equalTo('filter'))
2056
            ->will($this->returnValue([
2057
                'a' => [
2058
                    'value' => 'b',
2059
                ],
2060
                'foo' => [
2061
                    'type' => '1',
2062
                    'value' => 'bar',
2063
                ],
2064
                'baz' => [
2065
                    'type' => '5',
2066
                    'value' => 'test',
2067
                ],
2068
            ]));
2069
        $request->query = $query;
2070
2071
        $request->expects($this->any())
2072
            ->method('get')
2073
            ->will($this->returnValue($subjectId));
2074
2075
        $admin->setRequest($request);
2076
2077
        $modelManager = $this->createMock(ModelManagerInterface::class);
2078
        $modelManager->expects($this->any())
2079
            ->method('getDefaultSortValues')
2080
            ->will($this->returnValue([]));
2081
2082
        $admin->setModelManager($modelManager);
2083
2084
        $this->assertEquals([
2085
            'foo' => [
2086
                'type' => '1',
2087
                'value' => 'bar',
2088
            ],
2089
            'baz' => [
2090
                'type' => '5',
2091
                'value' => 'test',
2092
            ],
2093
            '_page' => 1,
2094
            '_per_page' => 32,
2095
            'a' => [
2096
                'value' => 'b',
2097
            ],
2098
        ], $admin->getFilterParameters());
2099
2100
        $this->assertTrue($admin->isDefaultFilter('foo'));
2101
        $this->assertFalse($admin->isDefaultFilter('bar'));
2102
        $this->assertFalse($admin->isDefaultFilter('a'));
2103
    }
2104
2105
    /**
2106
     * NEXT_MAJOR: remove this method.
2107
     *
2108
     * @group legacy
2109
     */
2110
    public function testCreateQueryLegacyCallWorks(): void
2111
    {
2112
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2113
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2114
        ]);
2115
        $modelManager = $this->createMock(ModelManagerInterface::class);
2116
        $modelManager->expects($this->once())
2117
            ->method('createQuery')
2118
            ->with('My\Class')
2119
            ->willReturn('a query');
2120
2121
        $admin->setModelManager($modelManager);
2122
        $this->assertSame('a query', $admin->createQuery('list'));
2123
    }
2124
2125
    public function testGetDataSourceIterator(): void
2126
    {
2127
        $datagrid = $this->createMock(DatagridInterface::class);
2128
        $datagrid->method('buildPager');
2129
2130
        $modelManager = $this->createMock(ModelManagerInterface::class);
2131
        $modelManager->method('getExportFields')->will($this->returnValue([
2132
            'field',
2133
            'foo',
2134
            'bar',
2135
        ]));
2136
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2137
            ->with($this->equalTo($datagrid), $this->equalTo([
2138
                'Feld' => 'field',
2139
                1 => 'foo',
2140
                2 => 'bar',
2141
            ]));
2142
2143
        $admin = $this->getMockBuilder(AbstractAdmin::class)
2144
            ->disableOriginalConstructor()
2145
            ->setMethods(['getDatagrid', 'getTranslationLabel', 'trans'])
2146
            ->getMockForAbstractClass();
2147
        $admin->method('getDatagrid')->will($this->returnValue($datagrid));
2148
        $admin->setModelManager($modelManager);
2149
2150
        $admin->expects($this->any())
2151
            ->method('getTranslationLabel')
2152
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
2153
                return $context.'.'.$type.'_'.$label;
2154
            }));
2155
        $admin->expects($this->any())
2156
            ->method('trans')
2157
            ->will($this->returnCallback(function ($label) {
2158
                if ('export.label_field' == $label) {
2159
                    return 'Feld';
2160
                }
2161
2162
                return $label;
2163
            }));
2164
2165
        $admin->getDataSourceIterator();
2166
    }
2167
2168
    public function testCircularChildAdmin(): void
2169
    {
2170
        $this->expectException(
2171
            \RuntimeException::class,
2172
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2173
        );
2174
2175
        $postAdmin = new PostAdmin(
2176
            'sonata.post.admin.post',
2177
            'Application\Sonata\NewsBundle\Entity\Post',
2178
            'SonataNewsBundle:PostAdmin'
2179
        );
2180
        $commentAdmin = new CommentAdmin(
2181
            'sonata.post.admin.comment',
2182
            'Application\Sonata\NewsBundle\Entity\Comment',
2183
            'SonataNewsBundle:CommentAdmin'
2184
        );
2185
        $postAdmin->addChild($commentAdmin);
2186
        $commentAdmin->addChild($postAdmin);
2187
    }
2188
2189
    public function testCircularChildAdminTripleLevel(): void
2190
    {
2191
        $this->expectException(
2192
            \RuntimeException::class,
2193
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2194
        );
2195
2196
        $postAdmin = new PostAdmin(
2197
            'sonata.post.admin.post',
2198
            'Application\Sonata\NewsBundle\Entity\Post',
2199
            'SonataNewsBundle:PostAdmin'
2200
        );
2201
        $commentAdmin = new CommentAdmin(
2202
            'sonata.post.admin.comment',
2203
            'Application\Sonata\NewsBundle\Entity\Comment',
2204
            'SonataNewsBundle:CommentAdmin'
2205
        );
2206
        $commentVoteAdmin = new CommentVoteAdmin(
2207
            'sonata.post.admin.comment_vote',
2208
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2209
            'SonataNewsBundle:CommentVoteAdmin'
2210
        );
2211
        $postAdmin->addChild($commentAdmin);
2212
        $commentAdmin->addChild($commentVoteAdmin);
2213
        $commentVoteAdmin->addChild($postAdmin);
2214
    }
2215
2216
    public function testCircularChildAdminWithItself(): void
2217
    {
2218
        $this->expectException(
2219
            \RuntimeException::class,
2220
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2221
        );
2222
2223
        $postAdmin = new PostAdmin(
2224
            'sonata.post.admin.post',
2225
            'Application\Sonata\NewsBundle\Entity\Post',
2226
            'SonataNewsBundle:PostAdmin'
2227
        );
2228
        $postAdmin->addChild($postAdmin);
2229
    }
2230
2231
    public function testGetRootAncestor(): void
2232
    {
2233
        $postAdmin = new PostAdmin(
2234
            'sonata.post.admin.post',
2235
            'Application\Sonata\NewsBundle\Entity\Post',
2236
            'SonataNewsBundle:PostAdmin'
2237
        );
2238
        $commentAdmin = new CommentAdmin(
2239
            'sonata.post.admin.comment',
2240
            'Application\Sonata\NewsBundle\Entity\Comment',
2241
            'SonataNewsBundle:CommentAdmin'
2242
        );
2243
        $commentVoteAdmin = new CommentVoteAdmin(
2244
            'sonata.post.admin.comment_vote',
2245
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2246
            'SonataNewsBundle:CommentVoteAdmin'
2247
        );
2248
2249
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2250
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2251
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2252
2253
        $postAdmin->addChild($commentAdmin);
2254
2255
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2256
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2257
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2258
2259
        $commentAdmin->addChild($commentVoteAdmin);
2260
2261
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2262
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2263
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2264
    }
2265
2266
    public function testGetChildDepth(): void
2267
    {
2268
        $postAdmin = new PostAdmin(
2269
            'sonata.post.admin.post',
2270
            'Application\Sonata\NewsBundle\Entity\Post',
2271
            'SonataNewsBundle:PostAdmin'
2272
        );
2273
        $commentAdmin = new CommentAdmin(
2274
            'sonata.post.admin.comment',
2275
            'Application\Sonata\NewsBundle\Entity\Comment',
2276
            'SonataNewsBundle:CommentAdmin'
2277
        );
2278
        $commentVoteAdmin = new CommentVoteAdmin(
2279
            'sonata.post.admin.comment_vote',
2280
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2281
            'SonataNewsBundle:CommentVoteAdmin'
2282
        );
2283
2284
        $this->assertSame(0, $postAdmin->getChildDepth());
2285
        $this->assertSame(0, $commentAdmin->getChildDepth());
2286
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2287
2288
        $postAdmin->addChild($commentAdmin);
2289
2290
        $this->assertSame(0, $postAdmin->getChildDepth());
2291
        $this->assertSame(1, $commentAdmin->getChildDepth());
2292
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2293
2294
        $commentAdmin->addChild($commentVoteAdmin);
2295
2296
        $this->assertSame(0, $postAdmin->getChildDepth());
2297
        $this->assertSame(1, $commentAdmin->getChildDepth());
2298
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2299
    }
2300
2301
    public function testGetCurrentLeafChildAdmin(): void
2302
    {
2303
        $postAdmin = new PostAdmin(
2304
            'sonata.post.admin.post',
2305
            'Application\Sonata\NewsBundle\Entity\Post',
2306
            'SonataNewsBundle:PostAdmin'
2307
        );
2308
        $commentAdmin = new CommentAdmin(
2309
            'sonata.post.admin.comment',
2310
            'Application\Sonata\NewsBundle\Entity\Comment',
2311
            'SonataNewsBundle:CommentAdmin'
2312
        );
2313
        $commentVoteAdmin = new CommentVoteAdmin(
2314
            'sonata.post.admin.comment_vote',
2315
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2316
            'SonataNewsBundle:CommentVoteAdmin'
2317
        );
2318
2319
        $postAdmin->addChild($commentAdmin);
2320
        $commentAdmin->addChild($commentVoteAdmin);
2321
2322
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2323
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2324
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2325
2326
        $commentAdmin->setCurrentChild(true);
2327
2328
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2329
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2330
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2331
2332
        $commentVoteAdmin->setCurrentChild(true);
2333
2334
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2335
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2336
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2337
    }
2338
2339
    private function createTagAdmin(Post $post)
2340
    {
2341
        $postAdmin = $this->getMockBuilder(PostAdmin::class)
2342
            ->disableOriginalConstructor()
2343
            ->getMock();
2344
2345
        $postAdmin->expects($this->any())->method('getObject')->will($this->returnValue($post));
2346
2347
        $formBuilder = $this->createMock(FormBuilderInterface::class);
2348
        $formBuilder->expects($this->any())->method('getForm')->will($this->returnValue(null));
2349
2350
        $tagAdmin = $this->getMockBuilder(TagAdmin::class)
2351
            ->setConstructorArgs([
2352
                'admin.tag',
2353
                Tag::class,
2354
                'MyBundle:MyController',
2355
            ])
2356
            ->setMethods(['getFormBuilder'])
2357
            ->getMock();
2358
2359
        $tagAdmin->expects($this->any())->method('getFormBuilder')->will($this->returnValue($formBuilder));
2360
        $tagAdmin->setParent($postAdmin);
2361
2362
        $tag = new Tag();
2363
        $tagAdmin->setSubject($tag);
2364
2365
        $request = $this->createMock(Request::class);
2366
        $tagAdmin->setRequest($request);
2367
2368
        $configurationPool = $this->getMockBuilder(Pool::class)
2369
            ->disableOriginalConstructor()
2370
            ->getMock();
2371
2372
        $configurationPool->expects($this->any())->method('getPropertyAccessor')->will($this->returnValue(PropertyAccess::createPropertyAccessor()));
2373
2374
        $tagAdmin->setConfigurationPool($configurationPool);
2375
2376
        return $tagAdmin;
2377
    }
2378
}
2379