Completed
Push — 3.x ( 6ccec9...24ead9 )
by Grégoire
04:39
created

AdminTest::testSetUniqid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\AdminBundle\Tests\Admin;
13
14
use Doctrine\Common\Collections\Collection;
15
use Knp\Menu\FactoryInterface;
16
use Knp\Menu\ItemInterface;
17
use PHPUnit\Framework\TestCase;
18
use Sonata\AdminBundle\Admin\AbstractAdmin;
19
use Sonata\AdminBundle\Admin\AbstractAdminExtension;
20
use Sonata\AdminBundle\Admin\AdminExtensionInterface;
21
use Sonata\AdminBundle\Admin\AdminInterface;
22
use Sonata\AdminBundle\Admin\BreadcrumbsBuilder;
23
use Sonata\AdminBundle\Admin\BreadcrumbsBuilderInterface;
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\DependencyInjection\ContainerInterface;
61
use Symfony\Component\Form\FormBuilder;
62
use Symfony\Component\Form\FormBuilderInterface;
63
use Symfony\Component\Form\FormEvent;
64
use Symfony\Component\Form\FormEvents;
65
use Symfony\Component\HttpFoundation\ParameterBag;
66
use Symfony\Component\HttpFoundation\Request;
67
use Symfony\Component\PropertyAccess\PropertyAccess;
68
use Symfony\Component\Routing\RouterInterface;
69
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
70
use Symfony\Component\Translation\TranslatorInterface;
71
use Symfony\Component\Validator\Mapping\MemberMetadata;
72
use Symfony\Component\Validator\Validator\ValidatorInterface;
73
74
class AdminTest extends TestCase
75
{
76
    protected $cacheTempFolder;
77
78
    public function setUp()
79
    {
80
        $this->cacheTempFolder = sys_get_temp_dir().'/sonata_test_route';
81
82
        exec('rm -rf '.$this->cacheTempFolder);
83
    }
84
85
    /**
86
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
87
     */
88
    public function testConstructor()
89
    {
90
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
91
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
92
93
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
94
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
95
        $this->assertSame($class, $admin->getClass());
96
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
97
    }
98
99
    public function testGetClass()
100
    {
101
        $class = Post::class;
102
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
103
104
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
105
106
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
107
108
        $admin->setSubject(new BlogPost());
109
        $this->assertSame(BlogPost::class, $admin->getClass());
110
111
        $admin->setSubClasses(['foo']);
112
        $this->assertSame(BlogPost::class, $admin->getClass());
113
114
        $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...
115
        $admin->setSubClasses([]);
116
        $this->assertSame($class, $admin->getClass());
117
118
        $admin->setSubClasses(['foo' => 'bar']);
119
        $admin->setRequest(new Request(['subclass' => 'foo']));
120
        $this->assertSame('bar', $admin->getClass());
121
    }
122
123
    public function testGetClassException()
124
    {
125
        $this->expectException(\RuntimeException::class);
126
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
127
128
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
129
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
130
131
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
132
        $admin->setParentFieldDescription(new FieldDescription());
133
        $admin->setSubClasses(['foo' => 'bar']);
134
        $admin->setRequest(new Request(['subclass' => 'foo']));
135
        $admin->getClass();
136
    }
137
138
    public function testCheckAccessThrowsExceptionOnMadeUpAction()
139
    {
140
        $admin = new PostAdmin(
141
            'sonata.post.admin.post',
142
            'Application\Sonata\NewsBundle\Entity\Post',
143
            'SonataNewsBundle:PostAdmin'
144
        );
145
        $this->expectException(
146
            \InvalidArgumentException::class
147
        );
148
        $this->expectExceptionMessage(
149
            'Action "made-up" could not be found'
150
        );
151
        $admin->checkAccess('made-up');
152
    }
153
154
    public function testCheckAccessThrowsAccessDeniedException()
155
    {
156
        $admin = new PostAdmin(
157
            'sonata.post.admin.post',
158
            'Application\Sonata\NewsBundle\Entity\Post',
159
            'SonataNewsBundle:PostAdmin'
160
        );
161
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
162
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
163
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
164
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
165
        $customExtension->getAccessMapping($admin)->willReturn(
166
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
167
        );
168
        $admin->addExtension($customExtension->reveal());
169
        $admin->setSecurityHandler($securityHandler->reveal());
170
        $this->expectException(
171
            AccessDeniedException::class
172
        );
173
        $this->expectExceptionMessage(
174
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
175
        );
176
        $admin->checkAccess('custom_action');
177
    }
178
179
    public function testHasAccessOnMadeUpAction()
180
    {
181
        $admin = new PostAdmin(
182
            'sonata.post.admin.post',
183
            'Application\Sonata\NewsBundle\Entity\Post',
184
            'SonataNewsBundle:PostAdmin'
185
        );
186
187
        $this->assertFalse($admin->hasAccess('made-up'));
188
    }
189
190
    public function testHasAccess()
191
    {
192
        $admin = new PostAdmin(
193
            'sonata.post.admin.post',
194
            'Application\Sonata\NewsBundle\Entity\Post',
195
            'SonataNewsBundle:PostAdmin'
196
        );
197
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
198
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
199
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
200
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
201
        $customExtension->getAccessMapping($admin)->willReturn(
202
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
203
        );
204
        $admin->addExtension($customExtension->reveal());
205
        $admin->setSecurityHandler($securityHandler->reveal());
206
207
        $this->assertFalse($admin->hasAccess('custom_action'));
208
    }
209
210
    public function testHasAccessAllowsAccess()
211
    {
212
        $admin = new PostAdmin(
213
            'sonata.post.admin.post',
214
            'Application\Sonata\NewsBundle\Entity\Post',
215
            'SonataNewsBundle:PostAdmin'
216
        );
217
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
218
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
219
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
220
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
221
        $customExtension->getAccessMapping($admin)->willReturn(
222
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
223
        );
224
        $admin->addExtension($customExtension->reveal());
225
        $admin->setSecurityHandler($securityHandler->reveal());
226
227
        $this->assertTrue($admin->hasAccess('custom_action'));
228
    }
229
230
    public function testHasAccessAllowsAccessEditAction()
231
    {
232
        $admin = new PostAdmin(
233
            'sonata.post.admin.post',
234
            'Application\Sonata\NewsBundle\Entity\Post',
235
            'SonataNewsBundle:PostAdmin'
236
        );
237
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
238
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
239
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
240
        $customExtension->getAccessMapping($admin)->willReturn(
241
            ['edit_action' => ['EDIT_ROLE']]
242
        );
243
        $admin->addExtension($customExtension->reveal());
244
        $admin->setSecurityHandler($securityHandler->reveal());
245
246
        $this->assertTrue($admin->hasAccess('edit_action'));
247
    }
248
249
    /**
250
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
251
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
252
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
253
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
254
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
255
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
256
     */
257
    public function testChildren()
258
    {
259
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
260
        $this->assertFalse($postAdmin->hasChildren());
261
        $this->assertFalse($postAdmin->hasChild('comment'));
262
263
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
264
        $postAdmin->addChild($commentAdmin, 'post');
265
266
        $this->assertTrue($postAdmin->hasChildren());
267
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
268
269
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
270
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
271
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
272
        $this->assertSame('post', $commentAdmin->getParentAssociationMapping());
273
274
        $this->assertFalse($postAdmin->isChild());
275
        $this->assertTrue($commentAdmin->isChild());
276
277
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
278
    }
279
280
    /**
281
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
282
     */
283
    public function testConfigure()
284
    {
285
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
286
        $this->assertNotNull($admin->getUniqid());
287
288
        $admin->initialize();
289
        $this->assertNotNull($admin->getUniqid());
290
        $this->assertSame('Post', $admin->getClassnameLabel());
291
292
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
293
        $admin->setClassnameLabel('postcomment');
294
295
        $admin->initialize();
296
        $this->assertSame('postcomment', $admin->getClassnameLabel());
297
    }
298
299
    public function testConfigureWithValidParentAssociationMapping()
300
    {
301
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
302
        $admin->setParentAssociationMapping('Category');
303
304
        $admin->initialize();
305
        $this->assertSame('Category', $admin->getParentAssociationMapping());
306
    }
307
308
    public function provideGetBaseRoutePattern()
309
    {
310
        return [
311
            [
312
                'Application\Sonata\NewsBundle\Entity\Post',
313
                '/sonata/news/post',
314
            ],
315
            [
316
                'Application\Sonata\NewsBundle\Document\Post',
317
                '/sonata/news/post',
318
            ],
319
            [
320
                'MyApplication\MyBundle\Entity\Post',
321
                '/myapplication/my/post',
322
            ],
323
            [
324
                'MyApplication\MyBundle\Entity\Post\Category',
325
                '/myapplication/my/post-category',
326
            ],
327
            [
328
                'MyApplication\MyBundle\Entity\Product\Category',
329
                '/myapplication/my/product-category',
330
            ],
331
            [
332
                'MyApplication\MyBundle\Entity\Other\Product\Category',
333
                '/myapplication/my/other-product-category',
334
            ],
335
            [
336
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
337
                '/cmf/foo/menu',
338
            ],
339
            [
340
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
341
                '/cmf/foo/menu',
342
            ],
343
            [
344
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
345
                '/symfony/barbar/menu',
346
            ],
347
            [
348
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
349
                '/symfony/barbar/menu-item',
350
            ],
351
            [
352
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
353
                '/cmf/foo/menu',
354
            ],
355
            [
356
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
357
                '/cmf/foo/menu',
358
            ],
359
            [
360
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
361
                '/cmf/foo/menu',
362
            ],
363
            [
364
                'AppBundle\Entity\User',
365
                '/app/user',
366
            ],
367
            [
368
                'App\Entity\User',
369
                '/app/user',
370
            ],
371
        ];
372
    }
373
374
    /**
375
     * @dataProvider provideGetBaseRoutePattern
376
     */
377
    public function testGetBaseRoutePattern($objFqn, $expected)
378
    {
379
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
380
        $this->assertSame($expected, $admin->getBaseRoutePattern());
381
    }
382
383
    /**
384
     * @dataProvider provideGetBaseRoutePattern
385
     */
386
    public function testGetBaseRoutePatternWithChildAdmin($objFqn, $expected)
387
    {
388
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
389
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
390
        $commentAdmin->setParent($postAdmin);
391
392
        $this->assertSame($expected.'/{id}/comment', $commentAdmin->getBaseRoutePattern());
393
    }
394
395
    /**
396
     * @dataProvider provideGetBaseRoutePattern
397
     */
398
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin($objFqn, $expected)
399
    {
400
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
401
        $commentAdmin = new CommentAdmin(
402
            'sonata.post.admin.comment',
403
            'Application\Sonata\NewsBundle\Entity\Comment',
404
            'SonataNewsBundle:CommentAdmin'
405
        );
406
        $commentVoteAdmin = new CommentVoteAdmin(
407
            'sonata.post.admin.comment_vote',
408
            'Application\Sonata\NewsBundle\Entity\CommentVote',
409
            'SonataNewsBundle:CommentVoteAdmin'
410
        );
411
        $commentAdmin->setParent($postAdmin);
412
        $commentVoteAdmin->setParent($commentAdmin);
413
414
        $this->assertSame($expected.'/{id}/comment/{childId}/commentvote', $commentVoteAdmin->getBaseRoutePattern());
415
    }
416
417
    public function testGetBaseRoutePatternWithSpecifedPattern()
418
    {
419
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostWithCustomRouteAdmin');
420
421
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
422
    }
423
424
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern()
425
    {
426
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
427
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
428
        $commentAdmin->setParent($postAdmin);
429
430
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
431
    }
432
433
    public function testGetBaseRoutePatternWithUnreconizedClassname()
434
    {
435
        $this->expectException(\RuntimeException::class);
436
437
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
438
        $admin->getBaseRoutePattern();
439
    }
440
441
    public function provideGetBaseRouteName()
442
    {
443
        return [
444
            [
445
                'Application\Sonata\NewsBundle\Entity\Post',
446
                'admin_sonata_news_post',
447
            ],
448
            [
449
                'Application\Sonata\NewsBundle\Document\Post',
450
                'admin_sonata_news_post',
451
            ],
452
            [
453
                'MyApplication\MyBundle\Entity\Post',
454
                'admin_myapplication_my_post',
455
            ],
456
            [
457
                'MyApplication\MyBundle\Entity\Post\Category',
458
                'admin_myapplication_my_post_category',
459
            ],
460
            [
461
                'MyApplication\MyBundle\Entity\Product\Category',
462
                'admin_myapplication_my_product_category',
463
            ],
464
            [
465
                'MyApplication\MyBundle\Entity\Other\Product\Category',
466
                'admin_myapplication_my_other_product_category',
467
            ],
468
            [
469
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
470
                'admin_cmf_foo_menu',
471
            ],
472
            [
473
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
474
                'admin_cmf_foo_menu',
475
            ],
476
            [
477
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
478
                'admin_symfony_barbar_menu',
479
            ],
480
            [
481
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
482
                'admin_symfony_barbar_menu_item',
483
            ],
484
            [
485
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
486
                'admin_cmf_foo_menu',
487
            ],
488
            [
489
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
490
                'admin_cmf_foo_menu',
491
            ],
492
            [
493
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
494
                'admin_cmf_foo_menu',
495
            ],
496
            [
497
                'AppBundle\Entity\User',
498
                'admin_app_user',
499
            ],
500
            [
501
                'App\Entity\User',
502
                'admin_app_user',
503
            ],
504
        ];
505
    }
506
507
    /**
508
     * @dataProvider provideGetBaseRouteName
509
     */
510
    public function testGetBaseRouteName($objFqn, $expected)
511
    {
512
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
513
514
        $this->assertSame($expected, $admin->getBaseRouteName());
515
    }
516
517
    /**
518
     * @group legacy
519
     * @expectedDeprecation Calling "addChild" without second argument is deprecated since 3.35 and will not be allowed in 4.0.
520
     * @dataProvider provideGetBaseRouteName
521
     */
522
    public function testGetBaseRouteNameWithChildAdmin($objFqn, $expected)
523
    {
524
        $routeGenerator = new DefaultRouteGenerator(
525
            $this->createMock(RouterInterface::class),
526
            new RoutesCache($this->cacheTempFolder, true)
527
        );
528
529
        $container = new Container();
530
        $pool = new Pool($container, 'Sonata Admin', '/path/to/pic.png');
531
532
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
533
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
534
        $container->set('sonata.post.admin.post', $postAdmin);
535
        $postAdmin->setConfigurationPool($pool);
536
        $postAdmin->setRouteBuilder($pathInfo);
537
        $postAdmin->setRouteGenerator($routeGenerator);
538
        $postAdmin->initialize();
539
540
        $commentAdmin = new CommentAdmin(
541
            'sonata.post.admin.comment',
542
            'Application\Sonata\NewsBundle\Entity\Comment',
543
            'SonataNewsBundle:CommentAdmin'
544
        );
545
        $container->set('sonata.post.admin.comment', $commentAdmin);
546
        $commentAdmin->setConfigurationPool($pool);
547
        $commentAdmin->setRouteBuilder($pathInfo);
548
        $commentAdmin->setRouteGenerator($routeGenerator);
549
        $commentAdmin->initialize();
550
551
        $postAdmin->addChild($commentAdmin, 'post');
552
553
        $commentVoteAdmin = new CommentVoteAdmin(
554
            'sonata.post.admin.comment_vote',
555
            'Application\Sonata\NewsBundle\Entity\CommentVote',
556
            'SonataNewsBundle:CommentVoteAdmin'
557
        );
558
559
        $container->set('sonata.post.admin.comment_vote', $commentVoteAdmin);
560
        $commentVoteAdmin->setConfigurationPool($pool);
561
        $commentVoteAdmin->setRouteBuilder($pathInfo);
562
        $commentVoteAdmin->setRouteGenerator($routeGenerator);
563
        $commentVoteAdmin->initialize();
564
565
        $commentAdmin->addChild($commentVoteAdmin);
566
        $pool->setAdminServiceIds([
567
            'sonata.post.admin.post',
568
            'sonata.post.admin.comment',
569
            'sonata.post.admin.comment_vote',
570
        ]);
571
572
        $this->assertSame($expected.'_comment', $commentAdmin->getBaseRouteName());
573
574
        $this->assertTrue($postAdmin->hasRoute('show'));
575
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show'));
576
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.show'));
577
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment|sonata.post.admin.comment_vote.show'));
578
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment.list'));
579
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment|sonata.post.admin.comment_vote.list'));
580
        $this->assertFalse($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.edit'));
581
        $this->assertFalse($commentAdmin->hasRoute('edit'));
582
        $this->assertSame('post', $commentAdmin->getParentAssociationMapping());
583
584
        /*
585
         * Test the route name from request
586
         */
587
        $postListRequest = new Request(
588
            [],
589
            [],
590
            [
591
                '_route' => $postAdmin->getBaseRouteName().'_list',
592
            ]
593
        );
594
595
        $postAdmin->setRequest($postListRequest);
596
        $commentAdmin->setRequest($postListRequest);
597
598
        $this->assertTrue($postAdmin->isCurrentRoute('list'));
599
        $this->assertFalse($postAdmin->isCurrentRoute('create'));
600
        $this->assertFalse($commentAdmin->isCurrentRoute('list'));
601
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('list'));
602
        $this->assertTrue($commentAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
603
        $this->assertFalse($commentAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
604
        $this->assertTrue($commentVoteAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
605
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
606
    }
607
608
    public function testGetBaseRouteNameWithUnreconizedClassname()
609
    {
610
        $this->expectException(\RuntimeException::class);
611
612
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
613
        $admin->getBaseRouteName();
614
    }
615
616
    public function testGetBaseRouteNameWithSpecifiedName()
617
    {
618
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
619
620
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
621
    }
622
623
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName()
624
    {
625
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
626
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
627
        $commentAdmin->setParent($postAdmin);
628
629
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
630
    }
631
632
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName()
633
    {
634
        $postAdmin = new PostAdmin(
635
            'sonata.post.admin.post',
636
            'Application\Sonata\NewsBundle\Entity\Post',
637
            'SonataNewsBundle:PostAdmin'
638
        );
639
        $commentAdmin = new CommentWithCustomRouteAdmin(
640
            'sonata.post.admin.comment_with_custom_route',
641
            'Application\Sonata\NewsBundle\Entity\Comment',
642
            'SonataNewsBundle:CommentWithCustomRouteAdmin'
643
        );
644
        $commentVoteAdmin = new CommentVoteAdmin(
645
            'sonata.post.admin.comment_vote',
646
            'Application\Sonata\NewsBundle\Entity\CommentVote',
647
            'SonataNewsBundle:CommentVoteAdmin'
648
        );
649
        $commentAdmin->setParent($postAdmin);
650
        $commentVoteAdmin->setParent($commentAdmin);
651
652
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
653
    }
654
655
    /**
656
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
657
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
658
     */
659
    public function testSetUniqid()
660
    {
661
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
662
663
        $uniqid = uniqid();
664
        $admin->setUniqid($uniqid);
665
666
        $this->assertSame($uniqid, $admin->getUniqid());
667
    }
668
669
    public function testUniqidConsistency()
670
    {
671
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
672
            'sonata.abstract.admin',
673
            'AbstractBundle\Entity\Foo',
674
            'SonataAbstractBundle:FooAdmin',
675
        ]);
676
        $admin->initialize();
677
678
        $uniqid = $admin->getUniqid();
679
        $admin->setUniqid(null);
680
681
        $this->assertSame($uniqid, $admin->getUniqid());
682
683
        $parentAdmin = $this->getMockForAbstractClass(AbstractAdmin::class, [
684
            'sonata.abstract.parent.admin',
685
            'AbstractBundle\Entity\Bar',
686
            'SonataAbstractBundle:BarAdmin',
687
        ]);
688
        $parentAdmin->initialize();
689
690
        $admin->setParent($parentAdmin);
691
        $admin->setUniqid(null);
692
693
        $this->assertNotSame($uniqid, $admin->getUniqid());
694
    }
695
696
    public function testToString()
697
    {
698
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
699
700
        $s = new \stdClass();
701
702
        $this->assertNotEmpty($admin->toString($s));
703
704
        $s = new FooToString();
705
        $this->assertSame('salut', $admin->toString($s));
706
707
        // To string method is implemented, but returns null
708
        $s = new FooToStringNull();
709
        $this->assertNotEmpty($admin->toString($s));
710
711
        $this->assertSame('', $admin->toString(false));
712
    }
713
714
    public function testIsAclEnabled()
715
    {
716
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
717
718
        $this->assertFalse($postAdmin->isAclEnabled());
719
720
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
721
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
722
        $this->assertTrue($commentAdmin->isAclEnabled());
723
    }
724
725
    /**
726
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
727
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
728
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
729
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
730
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
731
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
732
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
733
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
734
     */
735
    public function testSubClass()
736
    {
737
        $admin = new PostAdmin(
738
            'sonata.post.admin.post',
739
            Post::class,
740
            'SonataNewsBundle:PostAdmin'
741
        );
742
        $this->assertFalse($admin->hasSubClass('test'));
743
        $this->assertFalse($admin->hasActiveSubClass());
744
        $this->assertCount(0, $admin->getSubClasses());
745
        $this->assertNull($admin->getActiveSubClass());
746
        $this->assertNull($admin->getActiveSubclassCode());
747
        $this->assertSame(Post::class, $admin->getClass());
748
749
        // Just for the record, if there is no inheritance set, the getSubject is not used
750
        // the getSubject can also lead to some issue
751
        $admin->setSubject(new BlogPost());
752
        $this->assertSame(BlogPost::class, $admin->getClass());
753
754
        $admin->setSubClasses([
755
            'extended1' => 'NewsBundle\Entity\PostExtended1',
756
            'extended2' => 'NewsBundle\Entity\PostExtended2',
757
        ]);
758
        $this->assertFalse($admin->hasSubClass('test'));
759
        $this->assertTrue($admin->hasSubClass('extended1'));
760
        $this->assertFalse($admin->hasActiveSubClass());
761
        $this->assertCount(2, $admin->getSubClasses());
762
        $this->assertNull($admin->getActiveSubClass());
763
        $this->assertNull($admin->getActiveSubclassCode());
764
        $this->assertSame(
765
            BlogPost::class,
766
            $admin->getClass(),
767
            'When there is no subclass in the query the class parameter should be returned'
768
        );
769
770
        $request = new Request(['subclass' => 'extended1']);
771
        $admin->setRequest($request);
772
        $this->assertFalse($admin->hasSubClass('test'));
773
        $this->assertTrue($admin->hasSubClass('extended1'));
774
        $this->assertTrue($admin->hasActiveSubClass());
775
        $this->assertCount(2, $admin->getSubClasses());
776
        $this->assertSame(
777
            'NewsBundle\Entity\PostExtended1',
778
            $admin->getActiveSubClass(),
779
            'It should return the curently active sub class.'
780
        );
781
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
782
        $this->assertSame(
783
            'NewsBundle\Entity\PostExtended1',
784
            $admin->getClass(),
785
            'getClass() should return the name of the sub class when passed through a request query parameter.'
786
        );
787
788
        $request->query->set('subclass', 'inject');
789
        $this->assertNull($admin->getActiveSubclassCode());
790
    }
791
792
    public function testNonExistantSubclass()
793
    {
794
        $this->expectException(\RuntimeException::class);
795
796
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
797
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
798
799
        $admin->setRequest(new Request(['subclass' => 'inject']));
800
801
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
802
803
        $this->assertTrue($admin->hasActiveSubClass());
804
805
        $admin->getActiveSubClass();
806
    }
807
808
    /**
809
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
810
     */
811
    public function testOnlyOneSubclassNeededToBeActive()
812
    {
813
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
814
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
815
        $request = new Request(['subclass' => 'extended1']);
816
        $admin->setRequest($request);
817
        $this->assertTrue($admin->hasActiveSubClass());
818
    }
819
820
    /**
821
     * @group legacy
822
     * @expectedDeprecation Method "Sonata\AdminBundle\Admin\AbstractAdmin::addSubClass" is deprecated since 3.30 and will be removed in 4.0.
823
     */
824
    public function testAddSubClassIsDeprecated()
825
    {
826
        $admin = new PostAdmin(
827
            'sonata.post.admin.post',
828
            Post::class,
829
            'SonataNewsBundle:PostAdmin'
830
        );
831
        $admin->addSubClass('whatever');
832
    }
833
834
    public function testGetPerPageOptions()
835
    {
836
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
837
838
        $perPageOptions = $admin->getPerPageOptions();
839
840
        foreach ($perPageOptions as $perPage) {
841
            $this->assertEquals(0, $perPage % 4);
842
        }
843
844
        $admin->setPerPageOptions([500, 1000]);
845
        $this->assertSame([500, 1000], $admin->getPerPageOptions());
846
    }
847
848
    public function testGetLabelTranslatorStrategy()
849
    {
850
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
851
852
        $this->assertNull($admin->getLabelTranslatorStrategy());
853
854
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
855
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
856
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
857
    }
858
859
    public function testGetRouteBuilder()
860
    {
861
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
862
863
        $this->assertNull($admin->getRouteBuilder());
864
865
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
866
        $admin->setRouteBuilder($routeBuilder);
867
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
868
    }
869
870
    public function testGetMenuFactory()
871
    {
872
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
873
874
        $this->assertNull($admin->getMenuFactory());
875
876
        $menuFactory = $this->createMock(FactoryInterface::class);
877
        $admin->setMenuFactory($menuFactory);
878
        $this->assertSame($menuFactory, $admin->getMenuFactory());
879
    }
880
881
    public function testGetExtensions()
882
    {
883
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
884
885
        $this->assertSame([], $admin->getExtensions());
886
887
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
888
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
889
890
        $admin->addExtension($adminExtension1);
891
        $admin->addExtension($adminExtension2);
892
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
893
    }
894
895
    public function testGetFilterTheme()
896
    {
897
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
898
899
        $this->assertSame([], $admin->getFilterTheme());
900
901
        $admin->setFilterTheme(['FooTheme']);
902
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
903
    }
904
905
    public function testGetFormTheme()
906
    {
907
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
908
909
        $this->assertSame([], $admin->getFormTheme());
910
911
        $admin->setFormTheme(['FooTheme']);
912
913
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
914
    }
915
916
    public function testGetValidator()
917
    {
918
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
919
920
        $this->assertNull($admin->getValidator());
921
922
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
923
924
        $admin->setValidator($validator);
925
        $this->assertSame($validator, $admin->getValidator());
926
    }
927
928
    public function testGetSecurityHandler()
929
    {
930
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
931
932
        $this->assertNull($admin->getSecurityHandler());
933
934
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
935
        $admin->setSecurityHandler($securityHandler);
936
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
937
    }
938
939
    public function testGetSecurityInformation()
940
    {
941
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
942
943
        $this->assertSame([], $admin->getSecurityInformation());
944
945
        $securityInformation = [
946
            'GUEST' => ['VIEW', 'LIST'],
947
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
948
        ];
949
950
        $admin->setSecurityInformation($securityInformation);
951
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
952
    }
953
954
    public function testGetManagerType()
955
    {
956
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
957
958
        $this->assertNull($admin->getManagerType());
959
960
        $admin->setManagerType('foo_orm');
961
        $this->assertSame('foo_orm', $admin->getManagerType());
962
    }
963
964
    public function testGetModelManager()
965
    {
966
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
967
968
        $this->assertNull($admin->getModelManager());
969
970
        $modelManager = $this->createMock(ModelManagerInterface::class);
971
972
        $admin->setModelManager($modelManager);
973
        $this->assertSame($modelManager, $admin->getModelManager());
974
    }
975
976
    /**
977
     * NEXT_MAJOR: remove this method.
978
     *
979
     * @group legacy
980
     */
981
    public function testGetBaseCodeRoute()
982
    {
983
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
984
985
        $this->assertSame('', $admin->getBaseCodeRoute());
986
987
        $admin->setBaseCodeRoute('foo');
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...min::setBaseCodeRoute() has been deprecated with message: This method is deprecated since 3.24 and will be removed in 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...
988
        $this->assertSame('foo', $admin->getBaseCodeRoute());
989
    }
990
991
    // NEXT_MAJOR: uncomment this method.
992
    // public function testGetBaseCodeRoute()
993
    // {
994
    //     $postAdmin = new PostAdmin(
995
    //         'sonata.post.admin.post',
996
    //         'NewsBundle\Entity\Post',
997
    //         'SonataNewsBundle:PostAdmin'
998
    //     );
999
    //     $commentAdmin = new CommentAdmin(
1000
    //         'sonata.post.admin.comment',
1001
    //         'Application\Sonata\NewsBundle\Entity\Comment',
1002
    //         'SonataNewsBundle:CommentAdmin'
1003
    //     );
1004
    //
1005
    //     $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
1006
    //
1007
    //     $postAdmin->addChild($commentAdmin);
1008
    //
1009
    //     $this->assertSame(
1010
    //         'sonata.post.admin.post|sonata.post.admin.comment',
1011
    //         $commentAdmin->getBaseCodeRoute()
1012
    //     );
1013
    // }
1014
1015
    public function testGetRouteGenerator()
1016
    {
1017
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1018
1019
        $this->assertNull($admin->getRouteGenerator());
1020
1021
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1022
1023
        $admin->setRouteGenerator($routeGenerator);
1024
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
1025
    }
1026
1027
    public function testGetConfigurationPool()
1028
    {
1029
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1030
1031
        $this->assertNull($admin->getConfigurationPool());
1032
1033
        $pool = $this->getMockBuilder(Pool::class)
1034
            ->disableOriginalConstructor()
1035
            ->getMock();
1036
1037
        $admin->setConfigurationPool($pool);
1038
        $this->assertSame($pool, $admin->getConfigurationPool());
1039
    }
1040
1041
    public function testGetShowBuilder()
1042
    {
1043
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1044
1045
        $this->assertNull($admin->getShowBuilder());
1046
1047
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
1048
1049
        $admin->setShowBuilder($showBuilder);
1050
        $this->assertSame($showBuilder, $admin->getShowBuilder());
1051
    }
1052
1053
    public function testGetListBuilder()
1054
    {
1055
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1056
1057
        $this->assertNull($admin->getListBuilder());
1058
1059
        $listBuilder = $this->createMock(ListBuilderInterface::class);
1060
1061
        $admin->setListBuilder($listBuilder);
1062
        $this->assertSame($listBuilder, $admin->getListBuilder());
1063
    }
1064
1065
    public function testGetDatagridBuilder()
1066
    {
1067
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1068
1069
        $this->assertNull($admin->getDatagridBuilder());
1070
1071
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1072
1073
        $admin->setDatagridBuilder($datagridBuilder);
1074
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
1075
    }
1076
1077
    public function testGetFormContractor()
1078
    {
1079
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1080
1081
        $this->assertNull($admin->getFormContractor());
1082
1083
        $formContractor = $this->createMock(FormContractorInterface::class);
1084
1085
        $admin->setFormContractor($formContractor);
1086
        $this->assertSame($formContractor, $admin->getFormContractor());
1087
    }
1088
1089
    public function testGetRequest()
1090
    {
1091
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1092
1093
        $this->assertFalse($admin->hasRequest());
1094
1095
        $request = new Request();
1096
1097
        $admin->setRequest($request);
1098
        $this->assertSame($request, $admin->getRequest());
1099
        $this->assertTrue($admin->hasRequest());
1100
    }
1101
1102
    public function testGetRequestWithException()
1103
    {
1104
        $this->expectException(\RuntimeException::class);
1105
        $this->expectExceptionMessage('The Request object has not been set');
1106
1107
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1108
        $admin->getRequest();
1109
    }
1110
1111
    public function testGetTranslationDomain()
1112
    {
1113
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1114
1115
        $this->assertSame('messages', $admin->getTranslationDomain());
1116
1117
        $admin->setTranslationDomain('foo');
1118
        $this->assertSame('foo', $admin->getTranslationDomain());
1119
    }
1120
1121
    /**
1122
     * @group legacy
1123
     */
1124
    public function testGetTranslator()
1125
    {
1126
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1127
1128
        $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...
1129
1130
        $translator = $this->createMock(TranslatorInterface::class);
1131
1132
        $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...
1133
        $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...
1134
    }
1135
1136
    public function testGetShowGroups()
1137
    {
1138
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1139
1140
        $this->assertFalse($admin->getShowGroups());
1141
1142
        $groups = ['foo', 'bar', 'baz'];
1143
1144
        $admin->setShowGroups($groups);
1145
        $this->assertSame($groups, $admin->getShowGroups());
1146
    }
1147
1148
    public function testGetFormGroups()
1149
    {
1150
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1151
1152
        $this->assertFalse($admin->getFormGroups());
1153
1154
        $groups = ['foo', 'bar', 'baz'];
1155
1156
        $admin->setFormGroups($groups);
1157
        $this->assertSame($groups, $admin->getFormGroups());
1158
    }
1159
1160
    public function testGetMaxPageLinks()
1161
    {
1162
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1163
1164
        $this->assertSame(25, $admin->getMaxPageLinks());
1165
1166
        $admin->setMaxPageLinks(14);
1167
        $this->assertSame(14, $admin->getMaxPageLinks());
1168
    }
1169
1170
    public function testGetMaxPerPage()
1171
    {
1172
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1173
1174
        $this->assertSame(32, $admin->getMaxPerPage());
1175
1176
        $admin->setMaxPerPage(94);
1177
        $this->assertSame(94, $admin->getMaxPerPage());
1178
    }
1179
1180
    public function testGetLabel()
1181
    {
1182
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1183
1184
        $this->assertNull($admin->getLabel());
1185
1186
        $admin->setLabel('FooLabel');
1187
        $this->assertSame('FooLabel', $admin->getLabel());
1188
    }
1189
1190
    public function testGetBaseController()
1191
    {
1192
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1193
1194
        $this->assertSame('SonataNewsBundle:PostAdmin', $admin->getBaseControllerName());
1195
1196
        $admin->setBaseControllerName('SonataNewsBundle:FooAdmin');
1197
        $this->assertSame('SonataNewsBundle:FooAdmin', $admin->getBaseControllerName());
1198
    }
1199
1200
    public function testGetTemplates()
1201
    {
1202
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1203
1204
        $templates = [
1205
            'list' => '@FooAdmin/CRUD/list.html.twig',
1206
            'show' => '@FooAdmin/CRUD/show.html.twig',
1207
            'edit' => '@FooAdmin/CRUD/edit.html.twig',
1208
        ];
1209
1210
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1211
        $templateRegistry->getTemplates()->shouldBeCalled()->willReturn($templates);
1212
1213
        $admin->setTemplateRegistry($templateRegistry->reveal());
1214
1215
        $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.34, 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...
1216
    }
1217
1218
    public function testGetTemplate1()
1219
    {
1220
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1221
1222
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1223
        $templateRegistry->getTemplate('edit')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/edit.html.twig');
1224
        $templateRegistry->getTemplate('show')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/show.html.twig');
1225
1226
        $admin->setTemplateRegistry($templateRegistry->reveal());
1227
1228
        $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.34, 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...
1229
        $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.34, 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...
1230
    }
1231
1232
    public function testGetIdParameter()
1233
    {
1234
        $postAdmin = new PostAdmin(
1235
            'sonata.post.admin.post',
1236
            'NewsBundle\Entity\Post',
1237
            'SonataNewsBundle:PostAdmin'
1238
        );
1239
1240
        $this->assertSame('id', $postAdmin->getIdParameter());
1241
        $this->assertFalse($postAdmin->isChild());
1242
1243
        $commentAdmin = new CommentAdmin(
1244
            'sonata.post.admin.comment',
1245
            'Application\Sonata\NewsBundle\Entity\Comment',
1246
            'SonataNewsBundle:CommentAdmin'
1247
        );
1248
        $commentAdmin->setParent($postAdmin);
1249
1250
        $this->assertTrue($commentAdmin->isChild());
1251
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1252
1253
        $commentVoteAdmin = new CommentVoteAdmin(
1254
            'sonata.post.admin.comment_vote',
1255
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1256
            'SonataNewsBundle:CommentVoteAdmin'
1257
        );
1258
        $commentVoteAdmin->setParent($commentAdmin);
1259
1260
        $this->assertTrue($commentVoteAdmin->isChild());
1261
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1262
    }
1263
1264
    public function testGetExportFormats()
1265
    {
1266
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1267
1268
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1269
    }
1270
1271
    public function testGetUrlsafeIdentifier()
1272
    {
1273
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1274
1275
        $entity = new \stdClass();
1276
1277
        $modelManager = $this->createMock(ModelManagerInterface::class);
1278
        $modelManager->expects($this->once())
1279
            ->method('getUrlsafeIdentifier')
1280
            ->with($this->equalTo($entity))
1281
            ->will($this->returnValue('foo'));
1282
        $admin->setModelManager($modelManager);
1283
1284
        $this->assertSame('foo', $admin->getUrlsafeIdentifier($entity));
1285
    }
1286
1287
    public function testDeterminedPerPageValue()
1288
    {
1289
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1290
1291
        $this->assertFalse($admin->determinedPerPageValue('foo'));
1292
        $this->assertFalse($admin->determinedPerPageValue(123));
1293
        $this->assertTrue($admin->determinedPerPageValue(16));
1294
1295
        $admin->setPerPageOptions([101, 102, 103]);
1296
        $this->assertFalse($admin->determinedPerPageValue(16));
1297
        $this->assertTrue($admin->determinedPerPageValue(101));
1298
    }
1299
1300
    public function testIsGranted()
1301
    {
1302
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1303
1304
        $entity = new \stdClass();
1305
1306
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1307
        $securityHandler->expects($this->any())
1308
            ->method('isGranted')
1309
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin, $entity) {
1310
                if ($admin == $adminIn && 'FOO' == $attributes) {
1311
                    if (($object == $admin) || ($object == $entity)) {
1312
                        return true;
1313
                    }
1314
                }
1315
1316
                return false;
1317
            }));
1318
1319
        $admin->setSecurityHandler($securityHandler);
1320
1321
        $this->assertTrue($admin->isGranted('FOO'));
1322
        $this->assertTrue($admin->isGranted('FOO', $entity));
1323
        $this->assertFalse($admin->isGranted('BAR'));
1324
        $this->assertFalse($admin->isGranted('BAR', $entity));
1325
    }
1326
1327
    public function testSupportsPreviewMode()
1328
    {
1329
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1330
1331
        $this->assertFalse($admin->supportsPreviewMode());
1332
    }
1333
1334
    public function testGetPermissionsShow()
1335
    {
1336
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1337
1338
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1339
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1340
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1341
    }
1342
1343
    public function testShowIn()
1344
    {
1345
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1346
1347
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1348
        $securityHandler->expects($this->any())
1349
            ->method('isGranted')
1350
            ->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...
1351
                if ($admin == $adminIn && $attributes == ['LIST']) {
1352
                    return true;
1353
                }
1354
1355
                return false;
1356
            }));
1357
1358
        $admin->setSecurityHandler($securityHandler);
1359
1360
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1361
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1362
        $this->assertTrue($admin->showIn('foo'));
1363
    }
1364
1365
    public function testGetObjectIdentifier()
1366
    {
1367
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1368
1369
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1370
    }
1371
1372
    /**
1373
     * @group legacy
1374
     */
1375
    public function testTrans()
1376
    {
1377
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1378
        $admin->setTranslationDomain('fooMessageDomain');
1379
1380
        $translator = $this->createMock(TranslatorInterface::class);
1381
        $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...
1382
1383
        $translator->expects($this->once())
1384
            ->method('trans')
1385
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1386
            ->will($this->returnValue('fooTranslated'));
1387
1388
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1389
    }
1390
1391
    /**
1392
     * @group legacy
1393
     */
1394
    public function testTransWithMessageDomain()
1395
    {
1396
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1397
1398
        $translator = $this->createMock(TranslatorInterface::class);
1399
        $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...
1400
1401
        $translator->expects($this->once())
1402
            ->method('trans')
1403
            ->with($this->equalTo('foo'), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1404
            ->will($this->returnValue('fooTranslated'));
1405
1406
        $this->assertSame('fooTranslated', $admin->trans('foo', ['name' => 'Andrej'], 'fooMessageDomain'));
1407
    }
1408
1409
    /**
1410
     * @group legacy
1411
     */
1412
    public function testTransChoice()
1413
    {
1414
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1415
        $admin->setTranslationDomain('fooMessageDomain');
1416
1417
        $translator = $this->createMock(TranslatorInterface::class);
1418
        $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...
1419
1420
        $translator->expects($this->once())
1421
            ->method('transChoice')
1422
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1423
            ->will($this->returnValue('fooTranslated'));
1424
1425
        $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...
1426
    }
1427
1428
    /**
1429
     * @group legacy
1430
     */
1431
    public function testTransChoiceWithMessageDomain()
1432
    {
1433
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1434
1435
        $translator = $this->createMock(TranslatorInterface::class);
1436
        $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...
1437
1438
        $translator->expects($this->once())
1439
            ->method('transChoice')
1440
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1441
            ->will($this->returnValue('fooTranslated'));
1442
1443
        $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...
1444
    }
1445
1446
    public function testSetFilterPersister()
1447
    {
1448
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1449
1450
        $filterPersister = $this->createMock('Sonata\AdminBundle\Filter\Persister\FilterPersisterInterface');
1451
1452
        $this->assertAttributeSame(null, 'filterPersister', $admin);
1453
        $admin->setFilterPersister($filterPersister);
1454
        $this->assertAttributeSame($filterPersister, 'filterPersister', $admin);
1455
        $this->assertAttributeSame(true, 'persistFilters', $admin);
1456
    }
1457
1458
    public function testGetRootCode()
1459
    {
1460
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1461
1462
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1463
1464
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1465
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1466
        $parentFieldDescription->expects($this->once())
1467
            ->method('getAdmin')
1468
            ->will($this->returnValue($parentAdmin));
1469
1470
        $this->assertNull($admin->getParentFieldDescription());
1471
        $admin->setParentFieldDescription($parentFieldDescription);
1472
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1473
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1474
    }
1475
1476
    public function testGetRoot()
1477
    {
1478
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1479
1480
        $this->assertSame($admin, $admin->getRoot());
1481
1482
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1483
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1484
        $parentFieldDescription->expects($this->once())
1485
            ->method('getAdmin')
1486
            ->will($this->returnValue($parentAdmin));
1487
1488
        $this->assertNull($admin->getParentFieldDescription());
1489
        $admin->setParentFieldDescription($parentFieldDescription);
1490
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1491
        $this->assertSame($parentAdmin, $admin->getRoot());
1492
    }
1493
1494
    public function testGetExportFields()
1495
    {
1496
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1497
1498
        $modelManager = $this->createMock(ModelManagerInterface::class);
1499
        $modelManager->expects($this->once())
1500
            ->method('getExportFields')
1501
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1502
            ->will($this->returnValue(['foo', 'bar']));
1503
1504
        $admin->setModelManager($modelManager);
1505
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1506
    }
1507
1508
    public function testGetPersistentParametersWithNoExtension()
1509
    {
1510
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1511
1512
        $this->assertEmpty($admin->getPersistentParameters());
1513
    }
1514
1515
    public function testGetPersistentParametersWithInvalidExtension()
1516
    {
1517
        $this->expectException(\RuntimeException::class);
1518
1519
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1520
1521
        $extension = $this->createMock(AdminExtensionInterface::class);
1522
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue(null));
1523
1524
        $admin->addExtension($extension);
1525
1526
        $admin->getPersistentParameters();
1527
    }
1528
1529
    public function testGetPersistentParametersWithValidExtension()
1530
    {
1531
        $expected = [
1532
            'context' => 'foobar',
1533
        ];
1534
1535
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1536
1537
        $extension = $this->createMock(AdminExtensionInterface::class);
1538
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue($expected));
1539
1540
        $admin->addExtension($extension);
1541
1542
        $this->assertSame($expected, $admin->getPersistentParameters());
1543
    }
1544
1545
    public function testGetFormWithNonCollectionParentValue()
1546
    {
1547
        $post = new Post();
1548
        $tagAdmin = $this->createTagAdmin($post);
1549
        $tag = $tagAdmin->getSubject();
1550
1551
        $tag->setPosts(null);
1552
        $tagAdmin->getForm();
1553
        $this->assertSame($post, $tag->getPosts());
1554
    }
1555
1556
    public function testGetFormWithCollectionParentValue()
1557
    {
1558
        $post = new Post();
1559
        $tagAdmin = $this->createTagAdmin($post);
1560
        $tag = $tagAdmin->getSubject();
1561
1562
        // Case of a doctrine collection
1563
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1564
        $this->assertCount(0, $tag->getPosts());
1565
1566
        $tag->addPost(new Post());
1567
1568
        $this->assertCount(1, $tag->getPosts());
1569
1570
        $tagAdmin->getForm();
1571
1572
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1573
        $this->assertCount(2, $tag->getPosts());
1574
        $this->assertContains($post, $tag->getPosts());
1575
1576
        // Case of an array
1577
        $tag->setPosts([]);
1578
        $this->assertCount(0, $tag->getPosts());
1579
1580
        $tag->addPost(new Post());
1581
1582
        $this->assertCount(1, $tag->getPosts());
1583
1584
        $tagAdmin->getForm();
1585
1586
        $this->assertInternalType('array', $tag->getPosts());
1587
        $this->assertCount(2, $tag->getPosts());
1588
        $this->assertContains($post, $tag->getPosts());
1589
    }
1590
1591
    public function testFormAddPostSubmitEventForPreValidation()
1592
    {
1593
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1594
        $object = new \stdClass();
1595
1596
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1597
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1598
1599
        $validator = $this->createMock(ValidatorInterface::class);
1600
        $validator->expects($this->any())
1601
                ->method('getMetadataFor')
1602
                ->will($this->returnValue($this->createMock(MemberMetadata::class)));
1603
        $modelAdmin->setValidator($validator);
1604
1605
        $modelManager = $this->createMock(ModelManagerInterface::class);
1606
        $modelManager->expects($this->any())
1607
            ->method('getNewFieldDescriptionInstance')
1608
            ->will($this->returnValue(new FieldDescription()));
1609
        $modelAdmin->setModelManager($modelManager);
1610
1611
        // a Admin class to test that preValidate is called
1612
        $testAdminPreValidate = $this->createMock(AbstractAdmin::class, ['preValidate']);
1613
        $testAdminPreValidate->expects($this->once())
1614
                ->method('preValidate')
1615
                ->with($this->identicalTo($object));
1616
1617
        $event = $this->createMock(FormEvent::class);
1618
        $event->expects($this->any())
1619
                ->method('getData')
1620
                ->will($this->returnValue($object));
1621
1622
        $formBuild = $this->createMock(FormBuilder::class, ['addEventListener']);
1623
        $formBuild->expects($this->once())
1624
                ->method('addEventListener')
1625
                ->with($this->identicalTo(FormEvents::POST_SUBMIT),
1626
                        $this->callback(function ($callback) use ($testAdminPreValidate, $event) {
1627
                            if (is_callable($callback)) {
1628
                                $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...
1629
                                $closure($event);
1630
1631
                                return true;
1632
                            }
1633
1634
                            return false;
1635
                        }),
1636
                        $this->greaterThan(0)
1637
                    );
1638
1639
        $formContractor = $this->createMock(FormContractorInterface::class, ['getDefaultOptions', 'getFormBuilder']);
1640
        $formContractor->expects($this->any())
1641
                ->method('getDefaultOptions')
1642
                ->will($this->returnValue([]));
1643
        $formContractor->expects($this->any())
1644
                ->method('getFormBuilder')
1645
                ->will($this->returnValue($formBuild));
1646
1647
        $modelAdmin->setFormContractor($formContractor);
1648
        $modelAdmin->defineFormBuilder($formBuild);
1649
        $modelAdmin->getForm();
1650
    }
1651
1652
    public function testRemoveFieldFromFormGroup()
1653
    {
1654
        $formGroups = [
1655
            'foobar' => [
1656
                'fields' => [
1657
                    'foo' => 'foo',
1658
                    'bar' => 'bar',
1659
                ],
1660
            ],
1661
        ];
1662
1663
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1664
        $admin->setFormGroups($formGroups);
1665
1666
        $admin->removeFieldFromFormGroup('foo');
1667
        $this->assertSame($admin->getFormGroups(), [
1668
            'foobar' => [
1669
                'fields' => [
1670
                    'bar' => 'bar',
1671
                ],
1672
            ],
1673
        ]);
1674
1675
        $admin->removeFieldFromFormGroup('bar');
1676
        $this->assertSame($admin->getFormGroups(), []);
1677
    }
1678
1679
    public function testGetFilterParameters()
1680
    {
1681
        $authorId = uniqid();
1682
1683
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1684
1685
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1686
        $commentAdmin->setParentAssociationMapping('post.author');
1687
        $commentAdmin->setParent($postAdmin);
1688
1689
        $request = $this->createMock(Request::class, ['get']);
1690
        $query = $this->createMock(ParameterBag::class, ['get']);
1691
        $query->expects($this->any())
1692
            ->method('get')
1693
            ->will($this->returnValue([]));
1694
        $request->query = $query;
1695
        $request->expects($this->any())
1696
            ->method('get')
1697
            ->will($this->returnValue($authorId));
1698
1699
        $commentAdmin->setRequest($request);
1700
1701
        $modelManager = $this->createMock(ModelManagerInterface::class);
1702
        $modelManager->expects($this->any())
1703
            ->method('getDefaultSortValues')
1704
            ->will($this->returnValue([]));
1705
1706
        $commentAdmin->setModelManager($modelManager);
1707
1708
        $parameters = $commentAdmin->getFilterParameters();
1709
1710
        $this->assertTrue(isset($parameters['post__author']));
1711
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1712
    }
1713
1714
    public function testGetFilterFieldDescription()
1715
    {
1716
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1717
1718
        $fooFieldDescription = new FieldDescription();
1719
        $barFieldDescription = new FieldDescription();
1720
        $bazFieldDescription = new FieldDescription();
1721
1722
        $modelManager = $this->createMock(ModelManagerInterface::class);
1723
        $modelManager->expects($this->exactly(3))
1724
            ->method('getNewFieldDescriptionInstance')
1725
            ->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...
1726
                switch ($name) {
1727
                    case 'foo':
1728
                        $fieldDescription = $fooFieldDescription;
1729
1730
                        break;
1731
1732
                    case 'bar':
1733
                        $fieldDescription = $barFieldDescription;
1734
1735
                        break;
1736
1737
                    case 'baz':
1738
                        $fieldDescription = $bazFieldDescription;
1739
1740
                        break;
1741
1742
                    default:
1743
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1744
                        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...
1745
                }
1746
1747
                $fieldDescription->setName($name);
1748
1749
                return $fieldDescription;
1750
            }));
1751
1752
        $modelAdmin->setModelManager($modelManager);
1753
1754
        $pager = $this->createMock(PagerInterface::class);
1755
1756
        $datagrid = $this->createMock(DatagridInterface::class);
1757
        $datagrid->expects($this->once())
1758
            ->method('getPager')
1759
            ->will($this->returnValue($pager));
1760
1761
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1762
        $datagridBuilder->expects($this->once())
1763
            ->method('getBaseDatagrid')
1764
            ->with($this->identicalTo($modelAdmin), [])
1765
            ->will($this->returnValue($datagrid));
1766
1767
        $datagridBuilder->expects($this->exactly(3))
1768
            ->method('addFilter')
1769
            ->will($this->returnCallback(function ($datagrid, $type, $fieldDescription, AdminInterface $admin) {
1770
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1771
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1772
            }));
1773
1774
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1775
1776
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1777
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1778
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1779
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1780
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1781
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1782
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1783
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1784
    }
1785
1786
    public function testGetSubjectNoRequest()
1787
    {
1788
        $modelManager = $this->createMock(ModelManagerInterface::class);
1789
        $modelManager
1790
            ->expects($this->never())
1791
            ->method('find');
1792
1793
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1794
        $admin->setModelManager($modelManager);
1795
1796
        $this->assertNull($admin->getSubject());
1797
    }
1798
1799
    public function testGetSideMenu()
1800
    {
1801
        $item = $this->createMock(ItemInterface::class);
1802
        $item
1803
            ->expects($this->once())
1804
            ->method('setChildrenAttribute')
1805
            ->with('class', 'nav navbar-nav');
1806
        $item
1807
            ->expects($this->once())
1808
            ->method('setExtra')
1809
            ->with('translation_domain', 'foo_bar_baz');
1810
1811
        $menuFactory = $this->createMock(FactoryInterface::class);
1812
        $menuFactory
1813
            ->expects($this->once())
1814
            ->method('createItem')
1815
            ->will($this->returnValue($item));
1816
1817
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1818
        $modelAdmin->setMenuFactory($menuFactory);
1819
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1820
1821
        $modelAdmin->getSideMenu('foo');
1822
    }
1823
1824
    /**
1825
     * @return array
1826
     */
1827
    public function provideGetSubject()
1828
    {
1829
        return [
1830
            [23],
1831
            ['azerty'],
1832
            ['4f69bbb5f14a13347f000092'],
1833
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1834
            ['123'.AdapterInterface::ID_SEPARATOR.'my_type'], // composite keys are supported
1835
        ];
1836
    }
1837
1838
    /**
1839
     * @dataProvider provideGetSubject
1840
     */
1841
    public function testGetSubjectFailed($id)
1842
    {
1843
        $modelManager = $this->createMock(ModelManagerInterface::class);
1844
        $modelManager
1845
            ->expects($this->once())
1846
            ->method('find')
1847
            ->with('NewsBundle\Entity\Post', $id)
1848
            ->will($this->returnValue(null)); // entity not found
1849
1850
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1851
        $admin->setModelManager($modelManager);
1852
1853
        $admin->setRequest(new Request(['id' => $id]));
1854
        $this->assertNull($admin->getSubject());
1855
    }
1856
1857
    /**
1858
     * @dataProvider provideGetSubject
1859
     */
1860
    public function testGetSubject($id)
1861
    {
1862
        $entity = new Post();
1863
1864
        $modelManager = $this->createMock(ModelManagerInterface::class);
1865
        $modelManager
1866
            ->expects($this->once())
1867
            ->method('find')
1868
            ->with('NewsBundle\Entity\Post', $id)
1869
            ->will($this->returnValue($entity));
1870
1871
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1872
        $admin->setModelManager($modelManager);
1873
1874
        $admin->setRequest(new Request(['id' => $id]));
1875
        $this->assertSame($entity, $admin->getSubject());
1876
        $this->assertSame($entity, $admin->getSubject()); // model manager must be used only once
1877
    }
1878
1879
    public function testGetSubjectWithParentDescription()
1880
    {
1881
        $adminId = 1;
1882
1883
        $comment = new Comment();
1884
1885
        $modelManager = $this->createMock(ModelManagerInterface::class);
1886
        $modelManager
1887
            ->expects($this->any())
1888
            ->method('find')
1889
            ->with('NewsBundle\Entity\Comment', $adminId)
1890
            ->will($this->returnValue($comment));
1891
1892
        $request = new Request(['id' => $adminId]);
1893
1894
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1895
        $postAdmin->setRequest($request);
1896
1897
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1898
        $commentAdmin->setRequest($request);
1899
        $commentAdmin->setModelManager($modelManager);
1900
1901
        $this->assertEquals($comment, $commentAdmin->getSubject());
1902
1903
        $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...
1904
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1905
1906
        $this->assertNull($commentAdmin->getSubject());
1907
    }
1908
1909
    /**
1910
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1911
     */
1912
    public function testGetActionButtonsList()
1913
    {
1914
        $expected = [
1915
            'create' => [
1916
                'template' => 'Foo.html.twig',
1917
            ],
1918
        ];
1919
1920
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1921
1922
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1923
        $templateRegistry->getTemplate('button_create')->willReturn('Foo.html.twig');
1924
1925
        $admin->setTemplateRegistry($templateRegistry->reveal());
1926
1927
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1928
        $securityHandler
1929
            ->expects($this->once())
1930
            ->method('isGranted')
1931
            ->with($admin, 'CREATE', $admin)
1932
            ->will($this->returnValue(true));
1933
        $admin->setSecurityHandler($securityHandler);
1934
1935
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1936
        $routeGenerator
1937
            ->expects($this->once())
1938
            ->method('hasAdminRoute')
1939
            ->with($admin, 'create')
1940
            ->will($this->returnValue(true));
1941
        $admin->setRouteGenerator($routeGenerator);
1942
1943
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1944
    }
1945
1946
    /**
1947
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1948
     */
1949
    public function testGetActionButtonsListCreateDisabled()
1950
    {
1951
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1952
1953
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1954
        $securityHandler
1955
            ->expects($this->once())
1956
            ->method('isGranted')
1957
            ->with($admin, 'CREATE', $admin)
1958
            ->will($this->returnValue(false));
1959
        $admin->setSecurityHandler($securityHandler);
1960
1961
        $this->assertSame([], $admin->getActionButtons('list', null));
1962
    }
1963
1964
    /**
1965
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1966
     */
1967
    public function testGetBatchActions()
1968
    {
1969
        $expected = [
1970
            'delete' => [
1971
                'label' => 'action_delete',
1972
                'translation_domain' => 'SonataAdminBundle',
1973
                'ask_confirmation' => true, // by default always true
1974
            ],
1975
            'foo' => [
1976
                'label' => 'action_foo',
1977
                'translation_domain' => 'SonataAdminBundle',
1978
            ],
1979
            'bar' => [
1980
                'label' => 'batch.label_bar',
1981
                'translation_domain' => 'SonataAdminBundle',
1982
            ],
1983
            'baz' => [
1984
                'label' => 'action_baz',
1985
                'translation_domain' => 'AcmeAdminBundle',
1986
            ],
1987
        ];
1988
1989
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1990
1991
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1992
        $labelTranslatorStrategy->expects($this->any())
1993
            ->method('getLabel')
1994
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
1995
                return $context.'.'.$type.'_'.$label;
1996
            }));
1997
1998
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1999
        $admin->setRouteBuilder($pathInfo);
2000
        $admin->setTranslationDomain('SonataAdminBundle');
2001
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
2002
2003
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
2004
        $routeGenerator
2005
            ->expects($this->once())
2006
            ->method('hasAdminRoute')
2007
            ->with($admin, 'delete')
2008
            ->will($this->returnValue(true));
2009
        $admin->setRouteGenerator($routeGenerator);
2010
2011
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
2012
        $securityHandler->expects($this->any())
2013
            ->method('isGranted')
2014
            ->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...
2015
                if ($admin == $adminIn && 'DELETE' == $attributes) {
2016
                    return true;
2017
                }
2018
2019
                return false;
2020
            }));
2021
        $admin->setSecurityHandler($securityHandler);
2022
2023
        $this->assertSame($expected, $admin->getBatchActions());
2024
    }
2025
2026
    /**
2027
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
2028
     */
2029
    public function testShowMosaicButton()
2030
    {
2031
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
2032
        $listModes = $admin->getListModes();
2033
2034
        $admin->showMosaicButton(true);
2035
2036
        $this->assertSame($listModes, $admin->getListModes());
2037
    }
2038
2039
    /**
2040
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
2041
     */
2042
    public function testShowMosaicButtonHideMosaic()
2043
    {
2044
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
2045
        $listModes = $admin->getListModes();
2046
        $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...
2047
2048
        $admin->showMosaicButton(false);
2049
2050
        $this->assertSame($expected, $admin->getListModes());
2051
    }
2052
2053
    /**
2054
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
2055
     * @dataProvider provideGetBaseRouteName
2056
     */
2057
    public function testDefaultDashboardActionsArePresent($objFqn, $expected)
2058
    {
2059
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
2060
2061
        $routeGenerator = new DefaultRouteGenerator(
2062
            $this->createMock(RouterInterface::class),
2063
            new RoutesCache($this->cacheTempFolder, true)
2064
        );
2065
2066
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
2067
        $admin->setRouteBuilder($pathInfo);
2068
        $admin->setRouteGenerator($routeGenerator);
2069
        $admin->initialize();
2070
2071
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
2072
        $templateRegistry->getTemplate('action_create')->willReturn('Foo.html.twig');
2073
2074
        $admin->setTemplateRegistry($templateRegistry->reveal());
2075
2076
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
2077
        $securityHandler->expects($this->any())
2078
            ->method('isGranted')
2079
            ->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...
2080
                if ($admin == $adminIn && ('CREATE' == $attributes || 'LIST' == $attributes)) {
2081
                    return true;
2082
                }
2083
2084
                return false;
2085
            }));
2086
2087
        $admin->setSecurityHandler($securityHandler);
2088
2089
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
2090
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
2091
    }
2092
2093
    public function testDefaultFilters()
2094
    {
2095
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
2096
2097
        $subjectId = uniqid();
2098
2099
        $request = $this->createMock(Request::class, ['get']);
2100
        $query = $this->createMock(ParameterBag::class, ['set', 'get']);
2101
        $query->expects($this->any())
2102
            ->method('get')
2103
            ->with($this->equalTo('filter'))
2104
            ->will($this->returnValue([
2105
                'a' => [
2106
                    'value' => 'b',
2107
                ],
2108
                'foo' => [
2109
                    'type' => '1',
2110
                    'value' => 'bar',
2111
                ],
2112
                'baz' => [
2113
                    'type' => '5',
2114
                    'value' => 'test',
2115
                ],
2116
            ]));
2117
        $request->query = $query;
2118
2119
        $request->expects($this->any())
2120
            ->method('get')
2121
            ->will($this->returnValue($subjectId));
2122
2123
        $admin->setRequest($request);
2124
2125
        $modelManager = $this->createMock(ModelManagerInterface::class);
2126
        $modelManager->expects($this->any())
2127
            ->method('getDefaultSortValues')
2128
            ->will($this->returnValue([]));
2129
2130
        $admin->setModelManager($modelManager);
2131
2132
        $this->assertEquals([
2133
            'foo' => [
2134
                'type' => '1',
2135
                'value' => 'bar',
2136
            ],
2137
            'baz' => [
2138
                'type' => '5',
2139
                'value' => 'test',
2140
            ],
2141
            '_page' => 1,
2142
            '_per_page' => 32,
2143
            'a' => [
2144
                'value' => 'b',
2145
            ],
2146
        ], $admin->getFilterParameters());
2147
2148
        $this->assertTrue($admin->isDefaultFilter('foo'));
2149
        $this->assertFalse($admin->isDefaultFilter('bar'));
2150
        $this->assertFalse($admin->isDefaultFilter('a'));
2151
    }
2152
2153
    /**
2154
     * @group legacy
2155
     */
2156
    public function testDefaultBreadcrumbsBuilder()
2157
    {
2158
        $container = $this->createMock(ContainerInterface::class);
2159
        $container->expects($this->once())
2160
            ->method('getParameter')
2161
            ->with('sonata.admin.configuration.breadcrumbs')
2162
            ->will($this->returnValue([]));
2163
2164
        $pool = $this->getMockBuilder(Pool::class)
2165
            ->disableOriginalConstructor()
2166
            ->getMock();
2167
        $pool->expects($this->once())
2168
            ->method('getContainer')
2169
            ->will($this->returnValue($container));
2170
2171
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2172
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2173
        ], '', true, true, true, ['getConfigurationPool']);
2174
        $admin->expects($this->once())
2175
            ->method('getConfigurationPool')
2176
            ->will($this->returnValue($pool));
2177
2178
        $this->assertInstanceOf(BreadcrumbsBuilder::class, $admin->getBreadcrumbsBuilder());
2179
    }
2180
2181
    /**
2182
     * @group legacy
2183
     */
2184
    public function testBreadcrumbsBuilderSetter()
2185
    {
2186
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2187
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2188
        ]);
2189
        $this->assertSame($admin, $admin->setBreadcrumbsBuilder($builder = $this->createMock(
2190
            BreadcrumbsBuilderInterface::class
2191
        )));
2192
        $this->assertSame($builder, $admin->getBreadcrumbsBuilder());
2193
    }
2194
2195
    /**
2196
     * @group legacy
2197
     */
2198
    public function testGetBreadcrumbs()
2199
    {
2200
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2201
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2202
        ]);
2203
        $builder = $this->prophesize(BreadcrumbsBuilderInterface::class);
2204
        $action = 'myaction';
2205
        $builder->getBreadcrumbs($admin, $action)->shouldBeCalled();
2206
        $admin->setBreadcrumbsBuilder($builder->reveal())->getBreadcrumbs($action);
2207
    }
2208
2209
    /**
2210
     * @group legacy
2211
     */
2212
    public function testBuildBreadcrumbs()
2213
    {
2214
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2215
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2216
        ]);
2217
        $builder = $this->prophesize(BreadcrumbsBuilderInterface::class);
2218
        $action = 'myaction';
2219
        $menu = $this->createMock(ItemInterface::class);
2220
        $builder->buildBreadcrumbs($admin, $action, $menu)
2221
            ->shouldBeCalledTimes(1)
2222
            ->willReturn($menu);
2223
        $admin->setBreadcrumbsBuilder($builder->reveal());
2224
2225
        /* check the called is proxied only once */
2226
        $this->assertSame($menu, $admin->buildBreadcrumbs($action, $menu));
2227
        $this->assertSame($menu, $admin->buildBreadcrumbs($action, $menu));
2228
    }
2229
2230
    /**
2231
     * NEXT_MAJOR: remove this method.
2232
     *
2233
     * @group legacy
2234
     */
2235
    public function testCreateQueryLegacyCallWorks()
2236
    {
2237
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2238
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2239
        ]);
2240
        $modelManager = $this->createMock(ModelManagerInterface::class);
2241
        $modelManager->expects($this->once())
2242
            ->method('createQuery')
2243
            ->with('My\Class')
2244
            ->willReturn('a query');
2245
2246
        $admin->setModelManager($modelManager);
2247
        $this->assertSame('a query', $admin->createQuery('list'));
2248
    }
2249
2250
    public function testGetDataSourceIterator()
2251
    {
2252
        $datagrid = $this->createMock(DatagridInterface::class);
2253
        $datagrid->method('buildPager');
2254
2255
        $modelManager = $this->createMock(ModelManagerInterface::class);
2256
        $modelManager->method('getExportFields')->will($this->returnValue([
2257
            'field',
2258
            'foo',
2259
            'bar',
2260
        ]));
2261
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2262
            ->with($this->equalTo($datagrid), $this->equalTo([
2263
                'Feld' => 'field',
2264
                1 => 'foo',
2265
                2 => 'bar',
2266
            ]));
2267
2268
        $admin = $this->getMockBuilder(AbstractAdmin::class)
2269
            ->disableOriginalConstructor()
2270
            ->setMethods(['getDatagrid', 'getTranslationLabel', 'trans'])
2271
            ->getMockForAbstractClass();
2272
        $admin->method('getDatagrid')->will($this->returnValue($datagrid));
2273
        $admin->setModelManager($modelManager);
2274
2275
        $admin->expects($this->any())
2276
            ->method('getTranslationLabel')
2277
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
2278
                return $context.'.'.$type.'_'.$label;
2279
            }));
2280
        $admin->expects($this->any())
2281
            ->method('trans')
2282
            ->will($this->returnCallback(function ($label) {
2283
                if ('export.label_field' == $label) {
2284
                    return 'Feld';
2285
                }
2286
2287
                return $label;
2288
            }));
2289
2290
        $admin->getDataSourceIterator();
2291
    }
2292
2293
    public function testCircularChildAdmin()
2294
    {
2295
        $this->expectException(
2296
            \RuntimeException::class,
2297
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2298
        );
2299
2300
        $postAdmin = new PostAdmin(
2301
            'sonata.post.admin.post',
2302
            'Application\Sonata\NewsBundle\Entity\Post',
2303
            'SonataNewsBundle:PostAdmin'
2304
        );
2305
        $commentAdmin = new CommentAdmin(
2306
            'sonata.post.admin.comment',
2307
            'Application\Sonata\NewsBundle\Entity\Comment',
2308
            'SonataNewsBundle:CommentAdmin'
2309
        );
2310
        $postAdmin->addChild($commentAdmin, 'post');
2311
        $commentAdmin->addChild($postAdmin, 'comment');
2312
    }
2313
2314
    public function testCircularChildAdminTripleLevel()
2315
    {
2316
        $this->expectException(
2317
            \RuntimeException::class,
2318
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2319
        );
2320
2321
        $postAdmin = new PostAdmin(
2322
            'sonata.post.admin.post',
2323
            'Application\Sonata\NewsBundle\Entity\Post',
2324
            'SonataNewsBundle:PostAdmin'
2325
        );
2326
        $commentAdmin = new CommentAdmin(
2327
            'sonata.post.admin.comment',
2328
            'Application\Sonata\NewsBundle\Entity\Comment',
2329
            'SonataNewsBundle:CommentAdmin'
2330
        );
2331
        $commentVoteAdmin = new CommentVoteAdmin(
2332
            'sonata.post.admin.comment_vote',
2333
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2334
            'SonataNewsBundle:CommentVoteAdmin'
2335
        );
2336
        $postAdmin->addChild($commentAdmin, 'post');
2337
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2338
        $commentVoteAdmin->addChild($postAdmin, 'post');
2339
    }
2340
2341
    public function testCircularChildAdminWithItself()
2342
    {
2343
        $this->expectException(
2344
            \RuntimeException::class,
2345
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2346
        );
2347
2348
        $postAdmin = new PostAdmin(
2349
            'sonata.post.admin.post',
2350
            'Application\Sonata\NewsBundle\Entity\Post',
2351
            'SonataNewsBundle:PostAdmin'
2352
        );
2353
        $postAdmin->addChild($postAdmin);
2354
    }
2355
2356
    public function testGetRootAncestor()
2357
    {
2358
        $postAdmin = new PostAdmin(
2359
            'sonata.post.admin.post',
2360
            'Application\Sonata\NewsBundle\Entity\Post',
2361
            'SonataNewsBundle:PostAdmin'
2362
        );
2363
        $commentAdmin = new CommentAdmin(
2364
            'sonata.post.admin.comment',
2365
            'Application\Sonata\NewsBundle\Entity\Comment',
2366
            'SonataNewsBundle:CommentAdmin'
2367
        );
2368
        $commentVoteAdmin = new CommentVoteAdmin(
2369
            'sonata.post.admin.comment_vote',
2370
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2371
            'SonataNewsBundle:CommentVoteAdmin'
2372
        );
2373
2374
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2375
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2376
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2377
2378
        $postAdmin->addChild($commentAdmin, 'post');
2379
2380
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2381
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2382
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2383
2384
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2385
2386
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2387
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2388
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2389
    }
2390
2391
    public function testGetChildDepth()
2392
    {
2393
        $postAdmin = new PostAdmin(
2394
            'sonata.post.admin.post',
2395
            'Application\Sonata\NewsBundle\Entity\Post',
2396
            'SonataNewsBundle:PostAdmin'
2397
        );
2398
        $commentAdmin = new CommentAdmin(
2399
            'sonata.post.admin.comment',
2400
            'Application\Sonata\NewsBundle\Entity\Comment',
2401
            'SonataNewsBundle:CommentAdmin'
2402
        );
2403
        $commentVoteAdmin = new CommentVoteAdmin(
2404
            'sonata.post.admin.comment_vote',
2405
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2406
            'SonataNewsBundle:CommentVoteAdmin'
2407
        );
2408
2409
        $this->assertSame(0, $postAdmin->getChildDepth());
2410
        $this->assertSame(0, $commentAdmin->getChildDepth());
2411
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2412
2413
        $postAdmin->addChild($commentAdmin, 'post');
2414
2415
        $this->assertSame(0, $postAdmin->getChildDepth());
2416
        $this->assertSame(1, $commentAdmin->getChildDepth());
2417
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2418
2419
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2420
2421
        $this->assertSame(0, $postAdmin->getChildDepth());
2422
        $this->assertSame(1, $commentAdmin->getChildDepth());
2423
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2424
    }
2425
2426
    public function testGetCurrentLeafChildAdmin()
2427
    {
2428
        $postAdmin = new PostAdmin(
2429
            'sonata.post.admin.post',
2430
            'Application\Sonata\NewsBundle\Entity\Post',
2431
            'SonataNewsBundle:PostAdmin'
2432
        );
2433
        $commentAdmin = new CommentAdmin(
2434
            'sonata.post.admin.comment',
2435
            'Application\Sonata\NewsBundle\Entity\Comment',
2436
            'SonataNewsBundle:CommentAdmin'
2437
        );
2438
        $commentVoteAdmin = new CommentVoteAdmin(
2439
            'sonata.post.admin.comment_vote',
2440
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2441
            'SonataNewsBundle:CommentVoteAdmin'
2442
        );
2443
2444
        $postAdmin->addChild($commentAdmin, 'post');
2445
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2446
2447
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2448
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2449
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2450
2451
        $commentAdmin->setCurrentChild(true);
2452
2453
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2454
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2455
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2456
2457
        $commentVoteAdmin->setCurrentChild(true);
2458
2459
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2460
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2461
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2462
    }
2463
2464
    private function createTagAdmin(Post $post)
2465
    {
2466
        $postAdmin = $this->getMockBuilder(PostAdmin::class)
2467
            ->disableOriginalConstructor()
2468
            ->getMock();
2469
2470
        $postAdmin->expects($this->any())->method('getObject')->will($this->returnValue($post));
2471
2472
        $formBuilder = $this->createMock(FormBuilderInterface::class);
2473
        $formBuilder->expects($this->any())->method('getForm')->will($this->returnValue(null));
2474
2475
        $tagAdmin = $this->getMockBuilder(TagAdmin::class)
2476
            ->setConstructorArgs([
2477
                'admin.tag',
2478
                Tag::class,
2479
                'MyBundle:MyController',
2480
            ])
2481
            ->setMethods(['getFormBuilder'])
2482
            ->getMock();
2483
2484
        $tagAdmin->expects($this->any())->method('getFormBuilder')->will($this->returnValue($formBuilder));
2485
        $tagAdmin->setParent($postAdmin);
2486
2487
        $tag = new Tag();
2488
        $tagAdmin->setSubject($tag);
2489
2490
        $request = $this->createMock(Request::class);
2491
        $tagAdmin->setRequest($request);
2492
2493
        $configurationPool = $this->getMockBuilder(Pool::class)
2494
            ->disableOriginalConstructor()
2495
            ->getMock();
2496
2497
        $configurationPool->expects($this->any())->method('getPropertyAccessor')->will($this->returnValue(PropertyAccess::createPropertyAccessor()));
2498
2499
        $tagAdmin->setConfigurationPool($configurationPool);
2500
2501
        return $tagAdmin;
2502
    }
2503
}
2504