Completed
Push — 3.x ( 997b89...552e48 )
by Grégoire
03:48
created

AdminTest::testGetSubjectFailed()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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