Completed
Push — 3.x ( 6b78b0...2579fc )
by Grégoire
04:21
created

AdminTest::testSetFilterPersister()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\AdminBundle\Tests\Admin;
13
14
use Doctrine\Common\Collections\Collection;
15
use Knp\Menu\FactoryInterface;
16
use Knp\Menu\ItemInterface;
17
use PHPUnit\Framework\TestCase;
18
use Sonata\AdminBundle\Admin\AbstractAdmin;
19
use Sonata\AdminBundle\Admin\AbstractAdminExtension;
20
use Sonata\AdminBundle\Admin\AdminExtensionInterface;
21
use Sonata\AdminBundle\Admin\AdminInterface;
22
use Sonata\AdminBundle\Admin\BreadcrumbsBuilder;
23
use Sonata\AdminBundle\Admin\BreadcrumbsBuilderInterface;
24
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
25
use Sonata\AdminBundle\Admin\Pool;
26
use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
27
use Sonata\AdminBundle\Builder\FormContractorInterface;
28
use Sonata\AdminBundle\Builder\ListBuilderInterface;
29
use Sonata\AdminBundle\Builder\RouteBuilderInterface;
30
use Sonata\AdminBundle\Builder\ShowBuilderInterface;
31
use Sonata\AdminBundle\Datagrid\DatagridInterface;
32
use Sonata\AdminBundle\Datagrid\PagerInterface;
33
use Sonata\AdminBundle\Model\AuditManagerInterface;
34
use Sonata\AdminBundle\Model\ModelManagerInterface;
35
use Sonata\AdminBundle\Route\DefaultRouteGenerator;
36
use Sonata\AdminBundle\Route\PathInfoBuilder;
37
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
38
use Sonata\AdminBundle\Route\RoutesCache;
39
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
40
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
41
use Sonata\AdminBundle\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\FormBuilder;
61
use Symfony\Component\Form\FormBuilderInterface;
62
use Symfony\Component\Form\FormEvent;
63
use Symfony\Component\Form\FormEvents;
64
use Symfony\Component\HttpFoundation\ParameterBag;
65
use Symfony\Component\HttpFoundation\Request;
66
use Symfony\Component\PropertyAccess\PropertyAccess;
67
use Symfony\Component\Routing\RouterInterface;
68
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
69
use Symfony\Component\Translation\TranslatorInterface;
70
use Symfony\Component\Validator\Mapping\MemberMetadata;
71
use Symfony\Component\Validator\Validator\ValidatorInterface;
72
73
class AdminTest extends TestCase
74
{
75
    protected $cacheTempFolder;
76
77
    public function setUp()
78
    {
79
        $this->cacheTempFolder = sys_get_temp_dir().'/sonata_test_route';
80
81
        exec('rm -rf '.$this->cacheTempFolder);
82
    }
83
84
    /**
85
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
86
     */
87
    public function testConstructor()
88
    {
89
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
90
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
91
92
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
93
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
94
        $this->assertSame($class, $admin->getClass());
95
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
96
    }
97
98
    public function testGetClass()
99
    {
100
        $class = Post::class;
101
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
102
103
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
104
105
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
106
107
        $admin->setSubject(new BlogPost());
108
        $this->assertSame(BlogPost::class, $admin->getClass());
109
110
        $admin->setSubClasses(['foo']);
111
        $this->assertSame(BlogPost::class, $admin->getClass());
112
113
        $admin->setSubject(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
114
        $admin->setSubClasses([]);
115
        $this->assertSame($class, $admin->getClass());
116
117
        $admin->setSubClasses(['foo' => 'bar']);
118
        $admin->setRequest(new Request(['subclass' => 'foo']));
119
        $this->assertSame('bar', $admin->getClass());
120
    }
121
122
    public function testGetClassException()
123
    {
124
        $this->expectException(\RuntimeException::class);
125
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
126
127
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
128
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
129
130
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
131
        $admin->setParentFieldDescription(new FieldDescription());
132
        $admin->setSubClasses(['foo' => 'bar']);
133
        $admin->setRequest(new Request(['subclass' => 'foo']));
134
        $admin->getClass();
135
    }
136
137
    public function testCheckAccessThrowsExceptionOnMadeUpAction()
138
    {
139
        $admin = new PostAdmin(
140
            'sonata.post.admin.post',
141
            'Application\Sonata\NewsBundle\Entity\Post',
142
            'SonataNewsBundle:PostAdmin'
143
        );
144
        $this->expectException(
145
            \InvalidArgumentException::class
146
        );
147
        $this->expectExceptionMessage(
148
            'Action "made-up" could not be found'
149
        );
150
        $admin->checkAccess('made-up');
151
    }
152
153
    public function testCheckAccessThrowsAccessDeniedException()
154
    {
155
        $admin = new PostAdmin(
156
            'sonata.post.admin.post',
157
            'Application\Sonata\NewsBundle\Entity\Post',
158
            'SonataNewsBundle:PostAdmin'
159
        );
160
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
161
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
162
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
163
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
164
        $customExtension->getAccessMapping($admin)->willReturn(
165
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
166
        );
167
        $admin->addExtension($customExtension->reveal());
168
        $admin->setSecurityHandler($securityHandler->reveal());
169
        $this->expectException(
170
            AccessDeniedException::class
171
        );
172
        $this->expectExceptionMessage(
173
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
174
        );
175
        $admin->checkAccess('custom_action');
176
    }
177
178
    public function testHasAccessOnMadeUpAction()
179
    {
180
        $admin = new PostAdmin(
181
            'sonata.post.admin.post',
182
            'Application\Sonata\NewsBundle\Entity\Post',
183
            'SonataNewsBundle:PostAdmin'
184
        );
185
186
        $this->assertFalse($admin->hasAccess('made-up'));
187
    }
188
189
    public function testHasAccess()
190
    {
191
        $admin = new PostAdmin(
192
            'sonata.post.admin.post',
193
            'Application\Sonata\NewsBundle\Entity\Post',
194
            'SonataNewsBundle:PostAdmin'
195
        );
196
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
197
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
198
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
199
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
200
        $customExtension->getAccessMapping($admin)->willReturn(
201
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
202
        );
203
        $admin->addExtension($customExtension->reveal());
204
        $admin->setSecurityHandler($securityHandler->reveal());
205
206
        $this->assertFalse($admin->hasAccess('custom_action'));
207
    }
208
209
    public function testHasAccessAllowsAccess()
210
    {
211
        $admin = new PostAdmin(
212
            'sonata.post.admin.post',
213
            'Application\Sonata\NewsBundle\Entity\Post',
214
            'SonataNewsBundle:PostAdmin'
215
        );
216
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
217
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
218
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
219
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
220
        $customExtension->getAccessMapping($admin)->willReturn(
221
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
222
        );
223
        $admin->addExtension($customExtension->reveal());
224
        $admin->setSecurityHandler($securityHandler->reveal());
225
226
        $this->assertTrue($admin->hasAccess('custom_action'));
227
    }
228
229
    public function testHasAccessAllowsAccessEditAction()
230
    {
231
        $admin = new PostAdmin(
232
            'sonata.post.admin.post',
233
            'Application\Sonata\NewsBundle\Entity\Post',
234
            'SonataNewsBundle:PostAdmin'
235
        );
236
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
237
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
238
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
239
        $customExtension->getAccessMapping($admin)->willReturn(
240
            ['edit_action' => ['EDIT_ROLE']]
241
        );
242
        $admin->addExtension($customExtension->reveal());
243
        $admin->setSecurityHandler($securityHandler->reveal());
244
245
        $this->assertTrue($admin->hasAccess('edit_action'));
246
    }
247
248
    /**
249
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
250
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
251
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
252
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
253
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
254
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
255
     */
256
    public function testChildren()
257
    {
258
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
259
        $this->assertFalse($postAdmin->hasChildren());
260
        $this->assertFalse($postAdmin->hasChild('comment'));
261
262
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
263
        $postAdmin->addChild($commentAdmin);
264
        $this->assertTrue($postAdmin->hasChildren());
265
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
266
267
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
268
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
269
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
270
271
        $this->assertFalse($postAdmin->isChild());
272
        $this->assertTrue($commentAdmin->isChild());
273
274
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
275
    }
276
277
    /**
278
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
279
     */
280
    public function testConfigure()
281
    {
282
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
283
        $this->assertNotNull($admin->getUniqid());
284
285
        $admin->initialize();
286
        $this->assertNotNull($admin->getUniqid());
287
        $this->assertSame('Post', $admin->getClassnameLabel());
288
289
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
290
        $admin->setClassnameLabel('postcomment');
291
292
        $admin->initialize();
293
        $this->assertSame('postcomment', $admin->getClassnameLabel());
294
    }
295
296
    public function testConfigureWithValidParentAssociationMapping()
297
    {
298
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
299
        $admin->setParentAssociationMapping('Category');
300
301
        $admin->initialize();
302
        $this->assertSame('Category', $admin->getParentAssociationMapping());
303
    }
304
305
    public function provideGetBaseRoutePattern()
306
    {
307
        return [
308
            [
309
                'Application\Sonata\NewsBundle\Entity\Post',
310
                '/sonata/news/post',
311
            ],
312
            [
313
                'Application\Sonata\NewsBundle\Document\Post',
314
                '/sonata/news/post',
315
            ],
316
            [
317
                'MyApplication\MyBundle\Entity\Post',
318
                '/myapplication/my/post',
319
            ],
320
            [
321
                'MyApplication\MyBundle\Entity\Post\Category',
322
                '/myapplication/my/post-category',
323
            ],
324
            [
325
                'MyApplication\MyBundle\Entity\Product\Category',
326
                '/myapplication/my/product-category',
327
            ],
328
            [
329
                'MyApplication\MyBundle\Entity\Other\Product\Category',
330
                '/myapplication/my/other-product-category',
331
            ],
332
            [
333
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
334
                '/cmf/foo/menu',
335
            ],
336
            [
337
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
338
                '/cmf/foo/menu',
339
            ],
340
            [
341
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
342
                '/symfony/barbar/menu',
343
            ],
344
            [
345
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
346
                '/symfony/barbar/menu-item',
347
            ],
348
            [
349
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
350
                '/cmf/foo/menu',
351
            ],
352
            [
353
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
354
                '/cmf/foo/menu',
355
            ],
356
            [
357
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
358
                '/cmf/foo/menu',
359
            ],
360
            [
361
                'AppBundle\Entity\User',
362
                '/app/user',
363
            ],
364
            [
365
                'App\Entity\User',
366
                '/app/user',
367
            ],
368
        ];
369
    }
370
371
    /**
372
     * @dataProvider provideGetBaseRoutePattern
373
     */
374
    public function testGetBaseRoutePattern($objFqn, $expected)
375
    {
376
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
377
        $this->assertSame($expected, $admin->getBaseRoutePattern());
378
    }
379
380
    /**
381
     * @dataProvider provideGetBaseRoutePattern
382
     */
383
    public function testGetBaseRoutePatternWithChildAdmin($objFqn, $expected)
384
    {
385
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
386
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
387
        $commentAdmin->setParent($postAdmin);
388
389
        $this->assertSame($expected.'/{id}/comment', $commentAdmin->getBaseRoutePattern());
390
    }
391
392
    /**
393
     * @dataProvider provideGetBaseRoutePattern
394
     */
395
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin($objFqn, $expected)
396
    {
397
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
398
        $commentAdmin = new CommentAdmin(
399
            'sonata.post.admin.comment',
400
            'Application\Sonata\NewsBundle\Entity\Comment',
401
            'SonataNewsBundle:CommentAdmin'
402
        );
403
        $commentVoteAdmin = new CommentVoteAdmin(
404
            'sonata.post.admin.comment_vote',
405
            'Application\Sonata\NewsBundle\Entity\CommentVote',
406
            'SonataNewsBundle:CommentVoteAdmin'
407
        );
408
        $commentAdmin->setParent($postAdmin);
409
        $commentVoteAdmin->setParent($commentAdmin);
410
411
        $this->assertSame($expected.'/{id}/comment/{childId}/commentvote', $commentVoteAdmin->getBaseRoutePattern());
412
    }
413
414
    public function testGetBaseRoutePatternWithSpecifedPattern()
415
    {
416
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostWithCustomRouteAdmin');
417
418
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
419
    }
420
421
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern()
422
    {
423
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
424
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
425
        $commentAdmin->setParent($postAdmin);
426
427
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
428
    }
429
430
    public function testGetBaseRoutePatternWithUnreconizedClassname()
431
    {
432
        $this->expectException(\RuntimeException::class);
433
434
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
435
        $admin->getBaseRoutePattern();
436
    }
437
438
    public function provideGetBaseRouteName()
439
    {
440
        return [
441
            [
442
                'Application\Sonata\NewsBundle\Entity\Post',
443
                'admin_sonata_news_post',
444
            ],
445
            [
446
                'Application\Sonata\NewsBundle\Document\Post',
447
                'admin_sonata_news_post',
448
            ],
449
            [
450
                'MyApplication\MyBundle\Entity\Post',
451
                'admin_myapplication_my_post',
452
            ],
453
            [
454
                'MyApplication\MyBundle\Entity\Post\Category',
455
                'admin_myapplication_my_post_category',
456
            ],
457
            [
458
                'MyApplication\MyBundle\Entity\Product\Category',
459
                'admin_myapplication_my_product_category',
460
            ],
461
            [
462
                'MyApplication\MyBundle\Entity\Other\Product\Category',
463
                'admin_myapplication_my_other_product_category',
464
            ],
465
            [
466
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
467
                'admin_cmf_foo_menu',
468
            ],
469
            [
470
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
471
                'admin_cmf_foo_menu',
472
            ],
473
            [
474
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
475
                'admin_symfony_barbar_menu',
476
            ],
477
            [
478
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
479
                'admin_symfony_barbar_menu_item',
480
            ],
481
            [
482
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
483
                'admin_cmf_foo_menu',
484
            ],
485
            [
486
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
487
                'admin_cmf_foo_menu',
488
            ],
489
            [
490
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
491
                'admin_cmf_foo_menu',
492
            ],
493
            [
494
                'AppBundle\Entity\User',
495
                'admin_app_user',
496
            ],
497
            [
498
                'App\Entity\User',
499
                'admin_app_user',
500
            ],
501
        ];
502
    }
503
504
    /**
505
     * @dataProvider provideGetBaseRouteName
506
     */
507
    public function testGetBaseRouteName($objFqn, $expected)
508
    {
509
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
510
511
        $this->assertSame($expected, $admin->getBaseRouteName());
512
    }
513
514
    /**
515
     * @dataProvider provideGetBaseRouteName
516
     */
517
    public function testGetBaseRouteNameWithChildAdmin($objFqn, $expected)
518
    {
519
        $routeGenerator = new DefaultRouteGenerator(
520
            $this->createMock(RouterInterface::class),
521
            new RoutesCache($this->cacheTempFolder, true)
522
        );
523
524
        $container = new Container();
525
        $pool = new Pool($container, 'Sonata Admin', '/path/to/pic.png');
526
527
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
528
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
529
        $container->set('sonata.post.admin.post', $postAdmin);
530
        $postAdmin->setConfigurationPool($pool);
531
        $postAdmin->setRouteBuilder($pathInfo);
532
        $postAdmin->setRouteGenerator($routeGenerator);
533
        $postAdmin->initialize();
534
535
        $commentAdmin = new CommentAdmin(
536
            'sonata.post.admin.comment',
537
            'Application\Sonata\NewsBundle\Entity\Comment',
538
            'SonataNewsBundle:CommentAdmin'
539
        );
540
        $container->set('sonata.post.admin.comment', $commentAdmin);
541
        $commentAdmin->setConfigurationPool($pool);
542
        $commentAdmin->setRouteBuilder($pathInfo);
543
        $commentAdmin->setRouteGenerator($routeGenerator);
544
        $commentAdmin->initialize();
545
546
        $postAdmin->addChild($commentAdmin);
547
548
        $commentVoteAdmin = new CommentVoteAdmin(
549
            'sonata.post.admin.comment_vote',
550
            'Application\Sonata\NewsBundle\Entity\CommentVote',
551
            'SonataNewsBundle:CommentVoteAdmin'
552
        );
553
        $container->set('sonata.post.admin.comment_vote', $commentVoteAdmin);
554
        $commentVoteAdmin->setConfigurationPool($pool);
555
        $commentVoteAdmin->setRouteBuilder($pathInfo);
556
        $commentVoteAdmin->setRouteGenerator($routeGenerator);
557
        $commentVoteAdmin->initialize();
558
559
        $commentAdmin->addChild($commentVoteAdmin);
560
        $pool->setAdminServiceIds([
561
            'sonata.post.admin.post',
562
            'sonata.post.admin.comment',
563
            'sonata.post.admin.comment_vote',
564
        ]);
565
566
        $this->assertSame($expected.'_comment', $commentAdmin->getBaseRouteName());
567
568
        $this->assertTrue($postAdmin->hasRoute('show'));
569
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show'));
570
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.show'));
571
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment|sonata.post.admin.comment_vote.show'));
572
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment.list'));
573
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment|sonata.post.admin.comment_vote.list'));
574
        $this->assertFalse($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.edit'));
575
        $this->assertFalse($commentAdmin->hasRoute('edit'));
576
577
        /*
578
         * Test the route name from request
579
         */
580
        $postListRequest = new Request(
581
            [],
582
            [],
583
            [
584
                '_route' => $postAdmin->getBaseRouteName().'_list',
585
            ]
586
        );
587
588
        $postAdmin->setRequest($postListRequest);
589
        $commentAdmin->setRequest($postListRequest);
590
591
        $this->assertTrue($postAdmin->isCurrentRoute('list'));
592
        $this->assertFalse($postAdmin->isCurrentRoute('create'));
593
        $this->assertFalse($commentAdmin->isCurrentRoute('list'));
594
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('list'));
595
        $this->assertTrue($commentAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
596
        $this->assertFalse($commentAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
597
        $this->assertTrue($commentVoteAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
598
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
599
    }
600
601
    public function testGetBaseRouteNameWithUnreconizedClassname()
602
    {
603
        $this->expectException(\RuntimeException::class);
604
605
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
606
        $admin->getBaseRouteName();
607
    }
608
609
    public function testGetBaseRouteNameWithSpecifiedName()
610
    {
611
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
612
613
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
614
    }
615
616
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName()
617
    {
618
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
619
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
620
        $commentAdmin->setParent($postAdmin);
621
622
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
623
    }
624
625
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName()
626
    {
627
        $postAdmin = new PostAdmin(
628
            'sonata.post.admin.post',
629
            'Application\Sonata\NewsBundle\Entity\Post',
630
            'SonataNewsBundle:PostAdmin'
631
        );
632
        $commentAdmin = new CommentWithCustomRouteAdmin(
633
            'sonata.post.admin.comment_with_custom_route',
634
            'Application\Sonata\NewsBundle\Entity\Comment',
635
            'SonataNewsBundle:CommentWithCustomRouteAdmin'
636
        );
637
        $commentVoteAdmin = new CommentVoteAdmin(
638
            'sonata.post.admin.comment_vote',
639
            'Application\Sonata\NewsBundle\Entity\CommentVote',
640
            'SonataNewsBundle:CommentVoteAdmin'
641
        );
642
        $commentAdmin->setParent($postAdmin);
643
        $commentVoteAdmin->setParent($commentAdmin);
644
645
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
646
    }
647
648
    /**
649
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
650
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
651
     */
652
    public function testUniqid()
653
    {
654
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
655
656
        $uniqid = uniqid();
657
        $admin->setUniqid($uniqid);
658
659
        $this->assertSame($uniqid, $admin->getUniqid());
660
    }
661
662
    public function testToString()
663
    {
664
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
665
666
        $s = new \stdClass();
667
668
        $this->assertNotEmpty($admin->toString($s));
669
670
        $s = new FooToString();
671
        $this->assertSame('salut', $admin->toString($s));
672
673
        // To string method is implemented, but returns null
674
        $s = new FooToStringNull();
675
        $this->assertNotEmpty($admin->toString($s));
676
677
        $this->assertSame('', $admin->toString(false));
678
    }
679
680
    public function testIsAclEnabled()
681
    {
682
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
683
684
        $this->assertFalse($postAdmin->isAclEnabled());
685
686
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
687
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
688
        $this->assertTrue($commentAdmin->isAclEnabled());
689
    }
690
691
    /**
692
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
693
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
694
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
695
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
696
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
697
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
698
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
699
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
700
     */
701
    public function testSubClass()
702
    {
703
        $admin = new PostAdmin(
704
            'sonata.post.admin.post',
705
            Post::class,
706
            'SonataNewsBundle:PostAdmin'
707
        );
708
        $this->assertFalse($admin->hasSubClass('test'));
709
        $this->assertFalse($admin->hasActiveSubClass());
710
        $this->assertCount(0, $admin->getSubClasses());
711
        $this->assertNull($admin->getActiveSubClass());
712
        $this->assertNull($admin->getActiveSubclassCode());
713
        $this->assertSame(Post::class, $admin->getClass());
714
715
        // Just for the record, if there is no inheritance set, the getSubject is not used
716
        // the getSubject can also lead to some issue
717
        $admin->setSubject(new BlogPost());
718
        $this->assertSame(BlogPost::class, $admin->getClass());
719
720
        $admin->setSubClasses([
721
            'extended1' => 'NewsBundle\Entity\PostExtended1',
722
            'extended2' => 'NewsBundle\Entity\PostExtended2',
723
        ]);
724
        $this->assertFalse($admin->hasSubClass('test'));
725
        $this->assertTrue($admin->hasSubClass('extended1'));
726
        $this->assertFalse($admin->hasActiveSubClass());
727
        $this->assertCount(2, $admin->getSubClasses());
728
        $this->assertNull($admin->getActiveSubClass());
729
        $this->assertNull($admin->getActiveSubclassCode());
730
        $this->assertSame(
731
            BlogPost::class,
732
            $admin->getClass(),
733
            'When there is no subclass in the query the class parameter should be returned'
734
        );
735
736
        $request = new Request(['subclass' => 'extended1']);
737
        $admin->setRequest($request);
738
        $this->assertFalse($admin->hasSubClass('test'));
739
        $this->assertTrue($admin->hasSubClass('extended1'));
740
        $this->assertTrue($admin->hasActiveSubClass());
741
        $this->assertCount(2, $admin->getSubClasses());
742
        $this->assertSame(
743
            'NewsBundle\Entity\PostExtended1',
744
            $admin->getActiveSubClass(),
745
            'It should return the curently active sub class.'
746
        );
747
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
748
        $this->assertSame(
749
            'NewsBundle\Entity\PostExtended1',
750
            $admin->getClass(),
751
            'getClass() should return the name of the sub class when passed through a request query parameter.'
752
        );
753
754
        $request->query->set('subclass', 'inject');
755
        $this->assertNull($admin->getActiveSubclassCode());
756
    }
757
758
    public function testNonExistantSubclass()
759
    {
760
        $this->expectException(\RuntimeException::class);
761
762
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
763
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
764
765
        $admin->setRequest(new Request(['subclass' => 'inject']));
766
767
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
768
769
        $this->assertTrue($admin->hasActiveSubClass());
770
771
        $admin->getActiveSubClass();
772
    }
773
774
    /**
775
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
776
     */
777
    public function testOnlyOneSubclassNeededToBeActive()
778
    {
779
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
780
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
781
        $request = new Request(['subclass' => 'extended1']);
782
        $admin->setRequest($request);
783
        $this->assertTrue($admin->hasActiveSubClass());
784
    }
785
786
    /**
787
     * @group legacy
788
     * @expectedDeprecation Method "Sonata\AdminBundle\Admin\AbstractAdmin::addSubClass" is deprecated since 3.30 and will be removed in 4.0.
789
     */
790
    public function testAddSubClassIsDeprecated()
791
    {
792
        $admin = new PostAdmin(
793
            'sonata.post.admin.post',
794
            Post::class,
795
            'SonataNewsBundle:PostAdmin'
796
        );
797
        $admin->addSubClass('whatever');
798
    }
799
800
    public function testGetPerPageOptions()
801
    {
802
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
803
804
        $this->assertSame([16, 32, 64, 128, 192], $admin->getPerPageOptions());
805
        $admin->setPerPageOptions([500, 1000]);
806
        $this->assertSame([500, 1000], $admin->getPerPageOptions());
807
    }
808
809
    public function testGetLabelTranslatorStrategy()
810
    {
811
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
812
813
        $this->assertNull($admin->getLabelTranslatorStrategy());
814
815
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
816
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
817
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
818
    }
819
820
    public function testGetRouteBuilder()
821
    {
822
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
823
824
        $this->assertNull($admin->getRouteBuilder());
825
826
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
827
        $admin->setRouteBuilder($routeBuilder);
828
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
829
    }
830
831
    public function testGetMenuFactory()
832
    {
833
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
834
835
        $this->assertNull($admin->getMenuFactory());
836
837
        $menuFactory = $this->createMock(FactoryInterface::class);
838
        $admin->setMenuFactory($menuFactory);
839
        $this->assertSame($menuFactory, $admin->getMenuFactory());
840
    }
841
842
    public function testGetExtensions()
843
    {
844
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
845
846
        $this->assertSame([], $admin->getExtensions());
847
848
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
849
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
850
851
        $admin->addExtension($adminExtension1);
852
        $admin->addExtension($adminExtension2);
853
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
854
    }
855
856
    public function testGetFilterTheme()
857
    {
858
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
859
860
        $this->assertSame([], $admin->getFilterTheme());
861
862
        $admin->setFilterTheme(['FooTheme']);
863
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
864
    }
865
866
    public function testGetFormTheme()
867
    {
868
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
869
870
        $this->assertSame([], $admin->getFormTheme());
871
872
        $admin->setFormTheme(['FooTheme']);
873
874
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
875
    }
876
877
    public function testGetValidator()
878
    {
879
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
880
881
        $this->assertNull($admin->getValidator());
882
883
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
884
885
        $admin->setValidator($validator);
886
        $this->assertSame($validator, $admin->getValidator());
887
    }
888
889
    public function testGetSecurityHandler()
890
    {
891
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
892
893
        $this->assertNull($admin->getSecurityHandler());
894
895
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
896
        $admin->setSecurityHandler($securityHandler);
897
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
898
    }
899
900
    public function testGetSecurityInformation()
901
    {
902
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
903
904
        $this->assertSame([], $admin->getSecurityInformation());
905
906
        $securityInformation = [
907
            'GUEST' => ['VIEW', 'LIST'],
908
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
909
        ];
910
911
        $admin->setSecurityInformation($securityInformation);
912
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
913
    }
914
915
    public function testGetManagerType()
916
    {
917
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
918
919
        $this->assertNull($admin->getManagerType());
920
921
        $admin->setManagerType('foo_orm');
922
        $this->assertSame('foo_orm', $admin->getManagerType());
923
    }
924
925
    public function testGetModelManager()
926
    {
927
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
928
929
        $this->assertNull($admin->getModelManager());
930
931
        $modelManager = $this->createMock(ModelManagerInterface::class);
932
933
        $admin->setModelManager($modelManager);
934
        $this->assertSame($modelManager, $admin->getModelManager());
935
    }
936
937
    /**
938
     * NEXT_MAJOR: remove this method.
939
     *
940
     * @group legacy
941
     */
942
    public function testGetBaseCodeRoute()
943
    {
944
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
945
946
        $this->assertSame('', $admin->getBaseCodeRoute());
947
948
        $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...
949
        $this->assertSame('foo', $admin->getBaseCodeRoute());
950
    }
951
952
    // NEXT_MAJOR: uncomment this method.
953
    // public function testGetBaseCodeRoute()
954
    // {
955
    //     $postAdmin = new PostAdmin(
956
    //         'sonata.post.admin.post',
957
    //         'NewsBundle\Entity\Post',
958
    //         'SonataNewsBundle:PostAdmin'
959
    //     );
960
    //     $commentAdmin = new CommentAdmin(
961
    //         'sonata.post.admin.comment',
962
    //         'Application\Sonata\NewsBundle\Entity\Comment',
963
    //         'SonataNewsBundle:CommentAdmin'
964
    //     );
965
    //
966
    //     $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
967
    //
968
    //     $postAdmin->addChild($commentAdmin);
969
    //
970
    //     $this->assertSame(
971
    //         'sonata.post.admin.post|sonata.post.admin.comment',
972
    //         $commentAdmin->getBaseCodeRoute()
973
    //     );
974
    // }
975
976
    public function testGetRouteGenerator()
977
    {
978
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
979
980
        $this->assertNull($admin->getRouteGenerator());
981
982
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
983
984
        $admin->setRouteGenerator($routeGenerator);
985
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
986
    }
987
988
    public function testGetConfigurationPool()
989
    {
990
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
991
992
        $this->assertNull($admin->getConfigurationPool());
993
994
        $pool = $this->getMockBuilder(Pool::class)
995
            ->disableOriginalConstructor()
996
            ->getMock();
997
998
        $admin->setConfigurationPool($pool);
999
        $this->assertSame($pool, $admin->getConfigurationPool());
1000
    }
1001
1002
    public function testGetShowBuilder()
1003
    {
1004
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1005
1006
        $this->assertNull($admin->getShowBuilder());
1007
1008
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
1009
1010
        $admin->setShowBuilder($showBuilder);
1011
        $this->assertSame($showBuilder, $admin->getShowBuilder());
1012
    }
1013
1014
    public function testGetListBuilder()
1015
    {
1016
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1017
1018
        $this->assertNull($admin->getListBuilder());
1019
1020
        $listBuilder = $this->createMock(ListBuilderInterface::class);
1021
1022
        $admin->setListBuilder($listBuilder);
1023
        $this->assertSame($listBuilder, $admin->getListBuilder());
1024
    }
1025
1026
    public function testGetDatagridBuilder()
1027
    {
1028
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1029
1030
        $this->assertNull($admin->getDatagridBuilder());
1031
1032
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1033
1034
        $admin->setDatagridBuilder($datagridBuilder);
1035
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
1036
    }
1037
1038
    public function testGetFormContractor()
1039
    {
1040
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1041
1042
        $this->assertNull($admin->getFormContractor());
1043
1044
        $formContractor = $this->createMock(FormContractorInterface::class);
1045
1046
        $admin->setFormContractor($formContractor);
1047
        $this->assertSame($formContractor, $admin->getFormContractor());
1048
    }
1049
1050
    public function testGetRequest()
1051
    {
1052
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1053
1054
        $this->assertFalse($admin->hasRequest());
1055
1056
        $request = new Request();
1057
1058
        $admin->setRequest($request);
1059
        $this->assertSame($request, $admin->getRequest());
1060
        $this->assertTrue($admin->hasRequest());
1061
    }
1062
1063
    public function testGetRequestWithException()
1064
    {
1065
        $this->expectException(\RuntimeException::class);
1066
        $this->expectExceptionMessage('The Request object has not been set');
1067
1068
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1069
        $admin->getRequest();
1070
    }
1071
1072
    public function testGetTranslationDomain()
1073
    {
1074
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1075
1076
        $this->assertSame('messages', $admin->getTranslationDomain());
1077
1078
        $admin->setTranslationDomain('foo');
1079
        $this->assertSame('foo', $admin->getTranslationDomain());
1080
    }
1081
1082
    /**
1083
     * @group legacy
1084
     */
1085
    public function testGetTranslator()
1086
    {
1087
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1088
1089
        $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...
1090
1091
        $translator = $this->createMock(TranslatorInterface::class);
1092
1093
        $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...
1094
        $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...
1095
    }
1096
1097
    public function testGetShowGroups()
1098
    {
1099
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1100
1101
        $this->assertFalse($admin->getShowGroups());
1102
1103
        $groups = ['foo', 'bar', 'baz'];
1104
1105
        $admin->setShowGroups($groups);
1106
        $this->assertSame($groups, $admin->getShowGroups());
1107
    }
1108
1109
    public function testGetFormGroups()
1110
    {
1111
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1112
1113
        $this->assertFalse($admin->getFormGroups());
1114
1115
        $groups = ['foo', 'bar', 'baz'];
1116
1117
        $admin->setFormGroups($groups);
1118
        $this->assertSame($groups, $admin->getFormGroups());
1119
    }
1120
1121
    public function testGetMaxPageLinks()
1122
    {
1123
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1124
1125
        $this->assertSame(25, $admin->getMaxPageLinks());
1126
1127
        $admin->setMaxPageLinks(14);
1128
        $this->assertSame(14, $admin->getMaxPageLinks());
1129
    }
1130
1131
    public function testGetMaxPerPage()
1132
    {
1133
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1134
1135
        $this->assertSame(32, $admin->getMaxPerPage());
1136
1137
        $admin->setMaxPerPage(94);
1138
        $this->assertSame(94, $admin->getMaxPerPage());
1139
    }
1140
1141
    public function testGetLabel()
1142
    {
1143
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1144
1145
        $this->assertNull($admin->getLabel());
1146
1147
        $admin->setLabel('FooLabel');
1148
        $this->assertSame('FooLabel', $admin->getLabel());
1149
    }
1150
1151
    public function testGetBaseController()
1152
    {
1153
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1154
1155
        $this->assertSame('SonataNewsBundle:PostAdmin', $admin->getBaseControllerName());
1156
1157
        $admin->setBaseControllerName('SonataNewsBundle:FooAdmin');
1158
        $this->assertSame('SonataNewsBundle:FooAdmin', $admin->getBaseControllerName());
1159
    }
1160
1161
    public function testGetTemplates()
1162
    {
1163
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1164
1165
        $this->assertSame([], $admin->getTemplates());
1166
1167
        $templates = [
1168
            'list' => '@FooAdmin/CRUD/list.html.twig',
1169
            'show' => '@FooAdmin/CRUD/show.html.twig',
1170
            'edit' => '@FooAdmin/CRUD/edit.html.twig',
1171
        ];
1172
1173
        $admin->setTemplates($templates);
1174
        $this->assertSame($templates, $admin->getTemplates());
1175
    }
1176
1177
    public function testGetTemplate1()
1178
    {
1179
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1180
1181
        $this->assertNull($admin->getTemplate('edit'));
1182
1183
        $admin->setTemplate('edit', '@FooAdmin/CRUD/edit.html.twig');
1184
        $admin->setTemplate('show', '@FooAdmin/CRUD/show.html.twig');
1185
1186
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
1187
        $this->assertSame('@FooAdmin/CRUD/show.html.twig', $admin->getTemplate('show'));
1188
    }
1189
1190
    public function testGetTemplate2()
1191
    {
1192
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1193
1194
        $this->assertNull($admin->getTemplate('edit'));
1195
1196
        $templates = [
1197
            'list' => '@FooAdmin/CRUD/list.html.twig',
1198
            'show' => '@FooAdmin/CRUD/show.html.twig',
1199
            'edit' => '@FooAdmin/CRUD/edit.html.twig',
1200
        ];
1201
1202
        $admin->setTemplates($templates);
1203
1204
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
1205
        $this->assertSame('@FooAdmin/CRUD/show.html.twig', $admin->getTemplate('show'));
1206
    }
1207
1208
    public function testGetIdParameter()
1209
    {
1210
        $postAdmin = new PostAdmin(
1211
            'sonata.post.admin.post',
1212
            'NewsBundle\Entity\Post',
1213
            'SonataNewsBundle:PostAdmin'
1214
        );
1215
1216
        $this->assertSame('id', $postAdmin->getIdParameter());
1217
        $this->assertFalse($postAdmin->isChild());
1218
1219
        $commentAdmin = new CommentAdmin(
1220
            'sonata.post.admin.comment',
1221
            'Application\Sonata\NewsBundle\Entity\Comment',
1222
            'SonataNewsBundle:CommentAdmin'
1223
        );
1224
        $commentAdmin->setParent($postAdmin);
1225
1226
        $this->assertTrue($commentAdmin->isChild());
1227
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1228
1229
        $commentVoteAdmin = new CommentVoteAdmin(
1230
            'sonata.post.admin.comment_vote',
1231
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1232
            'SonataNewsBundle:CommentVoteAdmin'
1233
        );
1234
        $commentVoteAdmin->setParent($commentAdmin);
1235
1236
        $this->assertTrue($commentVoteAdmin->isChild());
1237
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1238
    }
1239
1240
    public function testGetExportFormats()
1241
    {
1242
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1243
1244
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1245
    }
1246
1247
    public function testGetUrlsafeIdentifier()
1248
    {
1249
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1250
1251
        $entity = new \stdClass();
1252
1253
        $modelManager = $this->createMock(ModelManagerInterface::class);
1254
        $modelManager->expects($this->once())
1255
            ->method('getUrlsafeIdentifier')
1256
            ->with($this->equalTo($entity))
1257
            ->will($this->returnValue('foo'));
1258
        $admin->setModelManager($modelManager);
1259
1260
        $this->assertSame('foo', $admin->getUrlsafeIdentifier($entity));
1261
    }
1262
1263
    public function testDeterminedPerPageValue()
1264
    {
1265
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1266
1267
        $this->assertFalse($admin->determinedPerPageValue('foo'));
1268
        $this->assertFalse($admin->determinedPerPageValue(123));
1269
        $this->assertTrue($admin->determinedPerPageValue(16));
1270
        $this->assertTrue($admin->determinedPerPageValue(32));
1271
        $this->assertTrue($admin->determinedPerPageValue(64));
1272
        $this->assertTrue($admin->determinedPerPageValue(128));
1273
        $this->assertTrue($admin->determinedPerPageValue(192));
1274
1275
        $admin->setPerPageOptions([101, 102, 103]);
1276
        $this->assertFalse($admin->determinedPerPageValue(15));
1277
        $this->assertFalse($admin->determinedPerPageValue(25));
1278
        $this->assertFalse($admin->determinedPerPageValue(200));
1279
        $this->assertTrue($admin->determinedPerPageValue(101));
1280
        $this->assertTrue($admin->determinedPerPageValue(102));
1281
        $this->assertTrue($admin->determinedPerPageValue(103));
1282
    }
1283
1284
    public function testIsGranted()
1285
    {
1286
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1287
1288
        $entity = new \stdClass();
1289
1290
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1291
        $securityHandler->expects($this->any())
1292
            ->method('isGranted')
1293
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin, $entity) {
1294
                if ($admin == $adminIn && 'FOO' == $attributes) {
1295
                    if (($object == $admin) || ($object == $entity)) {
1296
                        return true;
1297
                    }
1298
                }
1299
1300
                return false;
1301
            }));
1302
1303
        $admin->setSecurityHandler($securityHandler);
1304
1305
        $this->assertTrue($admin->isGranted('FOO'));
1306
        $this->assertTrue($admin->isGranted('FOO', $entity));
1307
        $this->assertFalse($admin->isGranted('BAR'));
1308
        $this->assertFalse($admin->isGranted('BAR', $entity));
1309
    }
1310
1311
    public function testSupportsPreviewMode()
1312
    {
1313
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1314
1315
        $this->assertFalse($admin->supportsPreviewMode());
1316
    }
1317
1318
    public function testGetPermissionsShow()
1319
    {
1320
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1321
1322
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1323
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1324
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1325
    }
1326
1327
    public function testShowIn()
1328
    {
1329
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1330
1331
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1332
        $securityHandler->expects($this->any())
1333
            ->method('isGranted')
1334
            ->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...
1335
                if ($admin == $adminIn && $attributes == ['LIST']) {
1336
                    return true;
1337
                }
1338
1339
                return false;
1340
            }));
1341
1342
        $admin->setSecurityHandler($securityHandler);
1343
1344
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1345
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1346
        $this->assertTrue($admin->showIn('foo'));
1347
    }
1348
1349
    public function testGetObjectIdentifier()
1350
    {
1351
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1352
1353
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1354
    }
1355
1356
    /**
1357
     * @group legacy
1358
     */
1359
    public function testTrans()
1360
    {
1361
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1362
        $admin->setTranslationDomain('fooMessageDomain');
1363
1364
        $translator = $this->createMock(TranslatorInterface::class);
1365
        $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...
1366
1367
        $translator->expects($this->once())
1368
            ->method('trans')
1369
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1370
            ->will($this->returnValue('fooTranslated'));
1371
1372
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1373
    }
1374
1375
    /**
1376
     * @group legacy
1377
     */
1378
    public function testTransWithMessageDomain()
1379
    {
1380
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1381
1382
        $translator = $this->createMock(TranslatorInterface::class);
1383
        $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...
1384
1385
        $translator->expects($this->once())
1386
            ->method('trans')
1387
            ->with($this->equalTo('foo'), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1388
            ->will($this->returnValue('fooTranslated'));
1389
1390
        $this->assertSame('fooTranslated', $admin->trans('foo', ['name' => 'Andrej'], 'fooMessageDomain'));
1391
    }
1392
1393
    /**
1394
     * @group legacy
1395
     */
1396
    public function testTransChoice()
1397
    {
1398
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1399
        $admin->setTranslationDomain('fooMessageDomain');
1400
1401
        $translator = $this->createMock(TranslatorInterface::class);
1402
        $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...
1403
1404
        $translator->expects($this->once())
1405
            ->method('transChoice')
1406
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1407
            ->will($this->returnValue('fooTranslated'));
1408
1409
        $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...
1410
    }
1411
1412
    /**
1413
     * @group legacy
1414
     */
1415
    public function testTransChoiceWithMessageDomain()
1416
    {
1417
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1418
1419
        $translator = $this->createMock(TranslatorInterface::class);
1420
        $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...
1421
1422
        $translator->expects($this->once())
1423
            ->method('transChoice')
1424
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1425
            ->will($this->returnValue('fooTranslated'));
1426
1427
        $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...
1428
    }
1429
1430
    public function testSetFilterPersister()
1431
    {
1432
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1433
1434
        $filterPersister = $this->createMock('Sonata\AdminBundle\Filter\Persister\FilterPersisterInterface');
1435
1436
        $this->assertAttributeSame(null, 'filterPersister', $admin);
1437
        $admin->setFilterPersister($filterPersister);
1438
        $this->assertAttributeSame($filterPersister, 'filterPersister', $admin);
1439
    }
1440
1441
    public function testGetRootCode()
1442
    {
1443
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1444
1445
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1446
1447
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1448
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1449
        $parentFieldDescription->expects($this->once())
1450
            ->method('getAdmin')
1451
            ->will($this->returnValue($parentAdmin));
1452
1453
        $this->assertNull($admin->getParentFieldDescription());
1454
        $admin->setParentFieldDescription($parentFieldDescription);
1455
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1456
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1457
    }
1458
1459
    public function testGetRoot()
1460
    {
1461
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1462
1463
        $this->assertSame($admin, $admin->getRoot());
1464
1465
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1466
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1467
        $parentFieldDescription->expects($this->once())
1468
            ->method('getAdmin')
1469
            ->will($this->returnValue($parentAdmin));
1470
1471
        $this->assertNull($admin->getParentFieldDescription());
1472
        $admin->setParentFieldDescription($parentFieldDescription);
1473
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1474
        $this->assertSame($parentAdmin, $admin->getRoot());
1475
    }
1476
1477
    public function testGetExportFields()
1478
    {
1479
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1480
1481
        $modelManager = $this->createMock(ModelManagerInterface::class);
1482
        $modelManager->expects($this->once())
1483
            ->method('getExportFields')
1484
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1485
            ->will($this->returnValue(['foo', 'bar']));
1486
1487
        $admin->setModelManager($modelManager);
1488
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1489
    }
1490
1491
    public function testGetPersistentParametersWithNoExtension()
1492
    {
1493
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1494
1495
        $this->assertEmpty($admin->getPersistentParameters());
1496
    }
1497
1498
    public function testGetPersistentParametersWithInvalidExtension()
1499
    {
1500
        $this->expectException(\RuntimeException::class);
1501
1502
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1503
1504
        $extension = $this->createMock(AdminExtensionInterface::class);
1505
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue(null));
1506
1507
        $admin->addExtension($extension);
1508
1509
        $admin->getPersistentParameters();
1510
    }
1511
1512
    public function testGetPersistentParametersWithValidExtension()
1513
    {
1514
        $expected = [
1515
            'context' => 'foobar',
1516
        ];
1517
1518
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1519
1520
        $extension = $this->createMock(AdminExtensionInterface::class);
1521
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue($expected));
1522
1523
        $admin->addExtension($extension);
1524
1525
        $this->assertSame($expected, $admin->getPersistentParameters());
1526
    }
1527
1528
    public function testGetFormWithNonCollectionParentValue()
1529
    {
1530
        $post = new Post();
1531
        $tagAdmin = $this->createTagAdmin($post);
1532
        $tag = $tagAdmin->getSubject();
1533
1534
        $tag->setPosts(null);
1535
        $tagAdmin->getForm();
1536
        $this->assertSame($post, $tag->getPosts());
1537
    }
1538
1539
    public function testGetFormWithCollectionParentValue()
1540
    {
1541
        $post = new Post();
1542
        $tagAdmin = $this->createTagAdmin($post);
1543
        $tag = $tagAdmin->getSubject();
1544
1545
        // Case of a doctrine collection
1546
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1547
        $this->assertCount(0, $tag->getPosts());
1548
1549
        $tag->addPost(new Post());
1550
1551
        $this->assertCount(1, $tag->getPosts());
1552
1553
        $tagAdmin->getForm();
1554
1555
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1556
        $this->assertCount(2, $tag->getPosts());
1557
        $this->assertContains($post, $tag->getPosts());
1558
1559
        // Case of an array
1560
        $tag->setPosts([]);
1561
        $this->assertCount(0, $tag->getPosts());
1562
1563
        $tag->addPost(new Post());
1564
1565
        $this->assertCount(1, $tag->getPosts());
1566
1567
        $tagAdmin->getForm();
1568
1569
        $this->assertInternalType('array', $tag->getPosts());
1570
        $this->assertCount(2, $tag->getPosts());
1571
        $this->assertContains($post, $tag->getPosts());
1572
    }
1573
1574
    public function testFormAddPostSubmitEventForPreValidation()
1575
    {
1576
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1577
        $object = new \stdClass();
1578
1579
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1580
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1581
1582
        $validator = $this->createMock(ValidatorInterface::class);
1583
        $validator->expects($this->any())
1584
                ->method('getMetadataFor')
1585
                ->will($this->returnValue($this->createMock(MemberMetadata::class)));
1586
        $modelAdmin->setValidator($validator);
1587
1588
        $modelManager = $this->createMock(ModelManagerInterface::class);
1589
        $modelManager->expects($this->any())
1590
            ->method('getNewFieldDescriptionInstance')
1591
            ->will($this->returnValue(new FieldDescription()));
1592
        $modelAdmin->setModelManager($modelManager);
1593
1594
        // a Admin class to test that preValidate is called
1595
        $testAdminPreValidate = $this->createMock(AbstractAdmin::class, ['preValidate']);
1596
        $testAdminPreValidate->expects($this->once())
1597
                ->method('preValidate')
1598
                ->with($this->identicalTo($object));
1599
1600
        $event = $this->createMock(FormEvent::class);
1601
        $event->expects($this->any())
1602
                ->method('getData')
1603
                ->will($this->returnValue($object));
1604
1605
        $formBuild = $this->createMock(FormBuilder::class, ['addEventListener']);
1606
        $formBuild->expects($this->once())
1607
                ->method('addEventListener')
1608
                ->with($this->identicalTo(FormEvents::POST_SUBMIT),
1609
                        $this->callback(function ($callback) use ($testAdminPreValidate, $event) {
1610
                            if (is_callable($callback)) {
1611
                                $closure = $callback->bindTo($testAdminPreValidate);
0 ignored issues
show
Bug introduced by
The method bindTo cannot be called on $callback (of type callable).

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

Loading history...
1612
                                $closure($event);
1613
1614
                                return true;
1615
                            }
1616
1617
                            return false;
1618
                        }),
1619
                        $this->greaterThan(0)
1620
                    );
1621
1622
        $formContractor = $this->createMock(FormContractorInterface::class, ['getDefaultOptions', 'getFormBuilder']);
1623
        $formContractor->expects($this->any())
1624
                ->method('getDefaultOptions')
1625
                ->will($this->returnValue([]));
1626
        $formContractor->expects($this->any())
1627
                ->method('getFormBuilder')
1628
                ->will($this->returnValue($formBuild));
1629
1630
        $modelAdmin->setFormContractor($formContractor);
1631
        $modelAdmin->defineFormBuilder($formBuild);
1632
        $modelAdmin->getForm();
1633
    }
1634
1635
    public function testRemoveFieldFromFormGroup()
1636
    {
1637
        $formGroups = [
1638
            'foobar' => [
1639
                'fields' => [
1640
                    'foo' => 'foo',
1641
                    'bar' => 'bar',
1642
                ],
1643
            ],
1644
        ];
1645
1646
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1647
        $admin->setFormGroups($formGroups);
1648
1649
        $admin->removeFieldFromFormGroup('foo');
1650
        $this->assertSame($admin->getFormGroups(), [
1651
            'foobar' => [
1652
                'fields' => [
1653
                    'bar' => 'bar',
1654
                ],
1655
            ],
1656
        ]);
1657
1658
        $admin->removeFieldFromFormGroup('bar');
1659
        $this->assertSame($admin->getFormGroups(), []);
1660
    }
1661
1662
    public function testGetFilterParameters()
1663
    {
1664
        $authorId = uniqid();
1665
1666
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1667
1668
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1669
        $commentAdmin->setParentAssociationMapping('post.author');
1670
        $commentAdmin->setParent($postAdmin);
1671
1672
        $request = $this->createMock(Request::class, ['get']);
1673
        $query = $this->createMock(ParameterBag::class, ['get']);
1674
        $query->expects($this->any())
1675
            ->method('get')
1676
            ->will($this->returnValue([]));
1677
        $request->query = $query;
1678
        $request->expects($this->any())
1679
            ->method('get')
1680
            ->will($this->returnValue($authorId));
1681
1682
        $commentAdmin->setRequest($request);
1683
1684
        $modelManager = $this->createMock(ModelManagerInterface::class);
1685
        $modelManager->expects($this->any())
1686
            ->method('getDefaultSortValues')
1687
            ->will($this->returnValue([]));
1688
1689
        $commentAdmin->setModelManager($modelManager);
1690
1691
        $parameters = $commentAdmin->getFilterParameters();
1692
1693
        $this->assertTrue(isset($parameters['post__author']));
1694
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1695
    }
1696
1697
    public function testGetFilterFieldDescription()
1698
    {
1699
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1700
1701
        $fooFieldDescription = new FieldDescription();
1702
        $barFieldDescription = new FieldDescription();
1703
        $bazFieldDescription = new FieldDescription();
1704
1705
        $modelManager = $this->createMock(ModelManagerInterface::class);
1706
        $modelManager->expects($this->exactly(3))
1707
            ->method('getNewFieldDescriptionInstance')
1708
            ->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...
1709
                switch ($name) {
1710
                    case 'foo':
1711
                        $fieldDescription = $fooFieldDescription;
1712
1713
                        break;
1714
1715
                    case 'bar':
1716
                        $fieldDescription = $barFieldDescription;
1717
1718
                        break;
1719
1720
                    case 'baz':
1721
                        $fieldDescription = $bazFieldDescription;
1722
1723
                        break;
1724
1725
                    default:
1726
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1727
                        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...
1728
                }
1729
1730
                $fieldDescription->setName($name);
1731
1732
                return $fieldDescription;
1733
            }));
1734
1735
        $modelAdmin->setModelManager($modelManager);
1736
1737
        $pager = $this->createMock(PagerInterface::class);
1738
1739
        $datagrid = $this->createMock(DatagridInterface::class);
1740
        $datagrid->expects($this->once())
1741
            ->method('getPager')
1742
            ->will($this->returnValue($pager));
1743
1744
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1745
        $datagridBuilder->expects($this->once())
1746
            ->method('getBaseDatagrid')
1747
            ->with($this->identicalTo($modelAdmin), [])
1748
            ->will($this->returnValue($datagrid));
1749
1750
        $datagridBuilder->expects($this->exactly(3))
1751
            ->method('addFilter')
1752
            ->will($this->returnCallback(function ($datagrid, $type, $fieldDescription, AdminInterface $admin) {
1753
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1754
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1755
            }));
1756
1757
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1758
1759
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1760
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1761
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1762
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1763
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1764
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1765
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1766
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1767
    }
1768
1769
    public function testGetSubjectNoRequest()
1770
    {
1771
        $modelManager = $this->createMock(ModelManagerInterface::class);
1772
        $modelManager
1773
            ->expects($this->never())
1774
            ->method('find');
1775
1776
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1777
        $admin->setModelManager($modelManager);
1778
1779
        $this->assertNull($admin->getSubject());
1780
    }
1781
1782
    public function testGetSideMenu()
1783
    {
1784
        $item = $this->createMock(ItemInterface::class);
1785
        $item
1786
            ->expects($this->once())
1787
            ->method('setChildrenAttribute')
1788
            ->with('class', 'nav navbar-nav');
1789
        $item
1790
            ->expects($this->once())
1791
            ->method('setExtra')
1792
            ->with('translation_domain', 'foo_bar_baz');
1793
1794
        $menuFactory = $this->createMock(FactoryInterface::class);
1795
        $menuFactory
1796
            ->expects($this->once())
1797
            ->method('createItem')
1798
            ->will($this->returnValue($item));
1799
1800
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1801
        $modelAdmin->setMenuFactory($menuFactory);
1802
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1803
1804
        $modelAdmin->getSideMenu('foo');
1805
    }
1806
1807
    /**
1808
     * @return array
1809
     */
1810
    public function provideGetSubject()
1811
    {
1812
        return [
1813
            [23],
1814
            ['azerty'],
1815
            ['4f69bbb5f14a13347f000092'],
1816
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1817
            ['123'.AdapterInterface::ID_SEPARATOR.'my_type'], // composite keys are supported
1818
        ];
1819
    }
1820
1821
    /**
1822
     * @dataProvider provideGetSubject
1823
     */
1824
    public function testGetSubjectFailed($id)
1825
    {
1826
        $modelManager = $this->createMock(ModelManagerInterface::class);
1827
        $modelManager
1828
            ->expects($this->once())
1829
            ->method('find')
1830
            ->with('NewsBundle\Entity\Post', $id)
1831
            ->will($this->returnValue(null)); // entity not found
1832
1833
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1834
        $admin->setModelManager($modelManager);
1835
1836
        $admin->setRequest(new Request(['id' => $id]));
1837
        $this->assertNull($admin->getSubject());
1838
    }
1839
1840
    /**
1841
     * @dataProvider provideGetSubject
1842
     */
1843
    public function testGetSubject($id)
1844
    {
1845
        $entity = new Post();
1846
1847
        $modelManager = $this->createMock(ModelManagerInterface::class);
1848
        $modelManager
1849
            ->expects($this->once())
1850
            ->method('find')
1851
            ->with('NewsBundle\Entity\Post', $id)
1852
            ->will($this->returnValue($entity));
1853
1854
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1855
        $admin->setModelManager($modelManager);
1856
1857
        $admin->setRequest(new Request(['id' => $id]));
1858
        $this->assertSame($entity, $admin->getSubject());
1859
        $this->assertSame($entity, $admin->getSubject()); // model manager must be used only once
1860
    }
1861
1862
    public function testGetSubjectWithParentDescription()
1863
    {
1864
        $adminId = 1;
1865
1866
        $comment = new Comment();
1867
1868
        $modelManager = $this->createMock(ModelManagerInterface::class);
1869
        $modelManager
1870
            ->expects($this->any())
1871
            ->method('find')
1872
            ->with('NewsBundle\Entity\Comment', $adminId)
1873
            ->will($this->returnValue($comment));
1874
1875
        $request = new Request(['id' => $adminId]);
1876
1877
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1878
        $postAdmin->setRequest($request);
1879
1880
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1881
        $commentAdmin->setRequest($request);
1882
        $commentAdmin->setModelManager($modelManager);
1883
1884
        $this->assertEquals($comment, $commentAdmin->getSubject());
1885
1886
        $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...
1887
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1888
1889
        $this->assertNull($commentAdmin->getSubject());
1890
    }
1891
1892
    /**
1893
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1894
     */
1895
    public function testGetActionButtonsList()
1896
    {
1897
        $expected = [
1898
            'create' => [
1899
                'template' => 'Foo.html.twig',
1900
            ],
1901
        ];
1902
1903
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1904
1905
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1906
        $securityHandler
1907
            ->expects($this->once())
1908
            ->method('isGranted')
1909
            ->with($admin, 'CREATE', $admin)
1910
            ->will($this->returnValue(true));
1911
        $admin->setSecurityHandler($securityHandler);
1912
1913
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1914
        $routeGenerator
1915
            ->expects($this->once())
1916
            ->method('hasAdminRoute')
1917
            ->with($admin, 'create')
1918
            ->will($this->returnValue(true));
1919
        $admin->setRouteGenerator($routeGenerator);
1920
1921
        $admin->setTemplate('button_create', 'Foo.html.twig');
1922
1923
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1924
    }
1925
1926
    /**
1927
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1928
     */
1929
    public function testGetActionButtonsListCreateDisabled()
1930
    {
1931
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1932
1933
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1934
        $securityHandler
1935
            ->expects($this->once())
1936
            ->method('isGranted')
1937
            ->with($admin, 'CREATE', $admin)
1938
            ->will($this->returnValue(false));
1939
        $admin->setSecurityHandler($securityHandler);
1940
1941
        $this->assertSame([], $admin->getActionButtons('list', null));
1942
    }
1943
1944
    /**
1945
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1946
     */
1947
    public function testGetBatchActions()
1948
    {
1949
        $expected = [
1950
            'delete' => [
1951
                'label' => 'action_delete',
1952
                'translation_domain' => 'SonataAdminBundle',
1953
                'ask_confirmation' => true, // by default always true
1954
            ],
1955
            'foo' => [
1956
                'label' => 'action_foo',
1957
                'translation_domain' => 'SonataAdminBundle',
1958
            ],
1959
            'bar' => [
1960
                'label' => 'batch.label_bar',
1961
                'translation_domain' => 'SonataAdminBundle',
1962
            ],
1963
            'baz' => [
1964
                'label' => 'action_baz',
1965
                'translation_domain' => 'AcmeAdminBundle',
1966
            ],
1967
        ];
1968
1969
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1970
1971
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1972
        $labelTranslatorStrategy->expects($this->any())
1973
            ->method('getLabel')
1974
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
1975
                return $context.'.'.$type.'_'.$label;
1976
            }));
1977
1978
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1979
        $admin->setRouteBuilder($pathInfo);
1980
        $admin->setTranslationDomain('SonataAdminBundle');
1981
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1982
1983
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1984
        $routeGenerator
1985
            ->expects($this->once())
1986
            ->method('hasAdminRoute')
1987
            ->with($admin, 'delete')
1988
            ->will($this->returnValue(true));
1989
        $admin->setRouteGenerator($routeGenerator);
1990
1991
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1992
        $securityHandler->expects($this->any())
1993
            ->method('isGranted')
1994
            ->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...
1995
                if ($admin == $adminIn && 'DELETE' == $attributes) {
1996
                    return true;
1997
                }
1998
1999
                return false;
2000
            }));
2001
        $admin->setSecurityHandler($securityHandler);
2002
2003
        $this->assertSame($expected, $admin->getBatchActions());
2004
    }
2005
2006
    /**
2007
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
2008
     */
2009
    public function testShowMosaicButton()
2010
    {
2011
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
2012
        $listModes = $admin->getListModes();
2013
2014
        $admin->showMosaicButton(true);
2015
2016
        $this->assertSame($listModes, $admin->getListModes());
2017
    }
2018
2019
    /**
2020
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
2021
     */
2022
    public function testShowMosaicButtonHideMosaic()
2023
    {
2024
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
2025
        $listModes = $admin->getListModes();
2026
        $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...
2027
2028
        $admin->showMosaicButton(false);
2029
2030
        $this->assertSame($expected, $admin->getListModes());
2031
    }
2032
2033
    /**
2034
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
2035
     * @dataProvider provideGetBaseRouteName
2036
     */
2037
    public function testDefaultDashboardActionsArePresent($objFqn, $expected)
2038
    {
2039
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
2040
2041
        $routeGenerator = new DefaultRouteGenerator(
2042
            $this->createMock(RouterInterface::class),
2043
            new RoutesCache($this->cacheTempFolder, true)
2044
        );
2045
2046
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
2047
        $admin->setRouteBuilder($pathInfo);
2048
        $admin->setRouteGenerator($routeGenerator);
2049
        $admin->initialize();
2050
2051
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
2052
        $securityHandler->expects($this->any())
2053
            ->method('isGranted')
2054
            ->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...
2055
                if ($admin == $adminIn && ('CREATE' == $attributes || 'LIST' == $attributes)) {
2056
                    return true;
2057
                }
2058
2059
                return false;
2060
            }));
2061
2062
        $admin->setSecurityHandler($securityHandler);
2063
2064
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
2065
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
2066
    }
2067
2068
    public function testDefaultFilters()
2069
    {
2070
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
2071
2072
        $subjectId = uniqid();
2073
2074
        $request = $this->createMock(Request::class, ['get']);
2075
        $query = $this->createMock(ParameterBag::class, ['set', 'get']);
2076
        $query->expects($this->any())
2077
            ->method('get')
2078
            ->with($this->equalTo('filter'))
2079
            ->will($this->returnValue([
2080
                'a' => [
2081
                    'value' => 'b',
2082
                ],
2083
                'foo' => [
2084
                    'type' => '1',
2085
                    'value' => 'bar',
2086
                ],
2087
                'baz' => [
2088
                    'type' => '5',
2089
                    'value' => 'test',
2090
                ],
2091
            ]));
2092
        $request->query = $query;
2093
2094
        $request->expects($this->any())
2095
            ->method('get')
2096
            ->will($this->returnValue($subjectId));
2097
2098
        $admin->setRequest($request);
2099
2100
        $modelManager = $this->createMock(ModelManagerInterface::class);
2101
        $modelManager->expects($this->any())
2102
            ->method('getDefaultSortValues')
2103
            ->will($this->returnValue([]));
2104
2105
        $admin->setModelManager($modelManager);
2106
2107
        $this->assertEquals([
2108
            'foo' => [
2109
                'type' => '1',
2110
                'value' => 'bar',
2111
            ],
2112
            'baz' => [
2113
                'type' => '5',
2114
                'value' => 'test',
2115
            ],
2116
            '_page' => 1,
2117
            '_per_page' => 32,
2118
            'a' => [
2119
                'value' => 'b',
2120
            ],
2121
        ], $admin->getFilterParameters());
2122
2123
        $this->assertTrue($admin->isDefaultFilter('foo'));
2124
        $this->assertFalse($admin->isDefaultFilter('bar'));
2125
        $this->assertFalse($admin->isDefaultFilter('a'));
2126
    }
2127
2128
    /**
2129
     * @group legacy
2130
     */
2131
    public function testDefaultBreadcrumbsBuilder()
2132
    {
2133
        $container = $this->createMock(ContainerInterface::class);
2134
        $container->expects($this->once())
2135
            ->method('getParameter')
2136
            ->with('sonata.admin.configuration.breadcrumbs')
2137
            ->will($this->returnValue([]));
2138
2139
        $pool = $this->getMockBuilder(Pool::class)
2140
            ->disableOriginalConstructor()
2141
            ->getMock();
2142
        $pool->expects($this->once())
2143
            ->method('getContainer')
2144
            ->will($this->returnValue($container));
2145
2146
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2147
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2148
        ], '', true, true, true, ['getConfigurationPool']);
2149
        $admin->expects($this->once())
2150
            ->method('getConfigurationPool')
2151
            ->will($this->returnValue($pool));
2152
2153
        $this->assertInstanceOf(BreadcrumbsBuilder::class, $admin->getBreadcrumbsBuilder());
2154
    }
2155
2156
    /**
2157
     * @group legacy
2158
     */
2159
    public function testBreadcrumbsBuilderSetter()
2160
    {
2161
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2162
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2163
        ]);
2164
        $this->assertSame($admin, $admin->setBreadcrumbsBuilder($builder = $this->createMock(
2165
            BreadcrumbsBuilderInterface::class
2166
        )));
2167
        $this->assertSame($builder, $admin->getBreadcrumbsBuilder());
2168
    }
2169
2170
    /**
2171
     * @group legacy
2172
     */
2173
    public function testGetBreadcrumbs()
2174
    {
2175
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2176
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2177
        ]);
2178
        $builder = $this->prophesize(BreadcrumbsBuilderInterface::class);
2179
        $action = 'myaction';
2180
        $builder->getBreadcrumbs($admin, $action)->shouldBeCalled();
2181
        $admin->setBreadcrumbsBuilder($builder->reveal())->getBreadcrumbs($action);
2182
    }
2183
2184
    /**
2185
     * @group legacy
2186
     */
2187
    public function testBuildBreadcrumbs()
2188
    {
2189
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2190
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2191
        ]);
2192
        $builder = $this->prophesize(BreadcrumbsBuilderInterface::class);
2193
        $action = 'myaction';
2194
        $menu = $this->createMock(ItemInterface::class);
2195
        $builder->buildBreadcrumbs($admin, $action, $menu)
2196
            ->shouldBeCalledTimes(1)
2197
            ->willReturn($menu);
2198
        $admin->setBreadcrumbsBuilder($builder->reveal());
2199
2200
        /* check the called is proxied only once */
2201
        $this->assertSame($menu, $admin->buildBreadcrumbs($action, $menu));
2202
        $this->assertSame($menu, $admin->buildBreadcrumbs($action, $menu));
2203
    }
2204
2205
    /**
2206
     * NEXT_MAJOR: remove this method.
2207
     *
2208
     * @group legacy
2209
     */
2210
    public function testCreateQueryLegacyCallWorks()
2211
    {
2212
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2213
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2214
        ]);
2215
        $modelManager = $this->createMock(ModelManagerInterface::class);
2216
        $modelManager->expects($this->once())
2217
            ->method('createQuery')
2218
            ->with('My\Class')
2219
            ->willReturn('a query');
2220
2221
        $admin->setModelManager($modelManager);
2222
        $this->assertSame('a query', $admin->createQuery('list'));
2223
    }
2224
2225
    public function testGetDataSourceIterator()
2226
    {
2227
        $datagrid = $this->createMock(DatagridInterface::class);
2228
        $datagrid->method('buildPager');
2229
2230
        $modelManager = $this->createMock(ModelManagerInterface::class);
2231
        $modelManager->method('getExportFields')->will($this->returnValue([
2232
            'field',
2233
            'foo',
2234
            'bar',
2235
        ]));
2236
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2237
            ->with($this->equalTo($datagrid), $this->equalTo([
2238
                'Feld' => 'field',
2239
                1 => 'foo',
2240
                2 => 'bar',
2241
            ]));
2242
2243
        $admin = $this->getMockBuilder(AbstractAdmin::class)
2244
            ->disableOriginalConstructor()
2245
            ->setMethods(['getDatagrid', 'getTranslationLabel', 'trans'])
2246
            ->getMockForAbstractClass();
2247
        $admin->method('getDatagrid')->will($this->returnValue($datagrid));
2248
        $admin->setModelManager($modelManager);
2249
2250
        $admin->expects($this->any())
2251
            ->method('getTranslationLabel')
2252
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
2253
                return $context.'.'.$type.'_'.$label;
2254
            }));
2255
        $admin->expects($this->any())
2256
            ->method('trans')
2257
            ->will($this->returnCallback(function ($label) {
2258
                if ('export.label_field' == $label) {
2259
                    return 'Feld';
2260
                }
2261
2262
                return $label;
2263
            }));
2264
2265
        $admin->getDataSourceIterator();
2266
    }
2267
2268
    public function testCircularChildAdmin()
2269
    {
2270
        $this->expectException(
2271
            \RuntimeException::class,
2272
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2273
        );
2274
2275
        $postAdmin = new PostAdmin(
2276
            'sonata.post.admin.post',
2277
            'Application\Sonata\NewsBundle\Entity\Post',
2278
            'SonataNewsBundle:PostAdmin'
2279
        );
2280
        $commentAdmin = new CommentAdmin(
2281
            'sonata.post.admin.comment',
2282
            'Application\Sonata\NewsBundle\Entity\Comment',
2283
            'SonataNewsBundle:CommentAdmin'
2284
        );
2285
        $postAdmin->addChild($commentAdmin);
2286
        $commentAdmin->addChild($postAdmin);
2287
    }
2288
2289
    public function testCircularChildAdminTripleLevel()
2290
    {
2291
        $this->expectException(
2292
            \RuntimeException::class,
2293
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2294
        );
2295
2296
        $postAdmin = new PostAdmin(
2297
            'sonata.post.admin.post',
2298
            'Application\Sonata\NewsBundle\Entity\Post',
2299
            'SonataNewsBundle:PostAdmin'
2300
        );
2301
        $commentAdmin = new CommentAdmin(
2302
            'sonata.post.admin.comment',
2303
            'Application\Sonata\NewsBundle\Entity\Comment',
2304
            'SonataNewsBundle:CommentAdmin'
2305
        );
2306
        $commentVoteAdmin = new CommentVoteAdmin(
2307
            'sonata.post.admin.comment_vote',
2308
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2309
            'SonataNewsBundle:CommentVoteAdmin'
2310
        );
2311
        $postAdmin->addChild($commentAdmin);
2312
        $commentAdmin->addChild($commentVoteAdmin);
2313
        $commentVoteAdmin->addChild($postAdmin);
2314
    }
2315
2316
    public function testCircularChildAdminWithItself()
2317
    {
2318
        $this->expectException(
2319
            \RuntimeException::class,
2320
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2321
        );
2322
2323
        $postAdmin = new PostAdmin(
2324
            'sonata.post.admin.post',
2325
            'Application\Sonata\NewsBundle\Entity\Post',
2326
            'SonataNewsBundle:PostAdmin'
2327
        );
2328
        $postAdmin->addChild($postAdmin);
2329
    }
2330
2331
    public function testGetRootAncestor()
2332
    {
2333
        $postAdmin = new PostAdmin(
2334
            'sonata.post.admin.post',
2335
            'Application\Sonata\NewsBundle\Entity\Post',
2336
            'SonataNewsBundle:PostAdmin'
2337
        );
2338
        $commentAdmin = new CommentAdmin(
2339
            'sonata.post.admin.comment',
2340
            'Application\Sonata\NewsBundle\Entity\Comment',
2341
            'SonataNewsBundle:CommentAdmin'
2342
        );
2343
        $commentVoteAdmin = new CommentVoteAdmin(
2344
            'sonata.post.admin.comment_vote',
2345
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2346
            'SonataNewsBundle:CommentVoteAdmin'
2347
        );
2348
2349
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2350
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2351
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2352
2353
        $postAdmin->addChild($commentAdmin);
2354
2355
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2356
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2357
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2358
2359
        $commentAdmin->addChild($commentVoteAdmin);
2360
2361
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2362
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2363
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2364
    }
2365
2366
    public function testGetChildDepth()
2367
    {
2368
        $postAdmin = new PostAdmin(
2369
            'sonata.post.admin.post',
2370
            'Application\Sonata\NewsBundle\Entity\Post',
2371
            'SonataNewsBundle:PostAdmin'
2372
        );
2373
        $commentAdmin = new CommentAdmin(
2374
            'sonata.post.admin.comment',
2375
            'Application\Sonata\NewsBundle\Entity\Comment',
2376
            'SonataNewsBundle:CommentAdmin'
2377
        );
2378
        $commentVoteAdmin = new CommentVoteAdmin(
2379
            'sonata.post.admin.comment_vote',
2380
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2381
            'SonataNewsBundle:CommentVoteAdmin'
2382
        );
2383
2384
        $this->assertSame(0, $postAdmin->getChildDepth());
2385
        $this->assertSame(0, $commentAdmin->getChildDepth());
2386
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2387
2388
        $postAdmin->addChild($commentAdmin);
2389
2390
        $this->assertSame(0, $postAdmin->getChildDepth());
2391
        $this->assertSame(1, $commentAdmin->getChildDepth());
2392
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2393
2394
        $commentAdmin->addChild($commentVoteAdmin);
2395
2396
        $this->assertSame(0, $postAdmin->getChildDepth());
2397
        $this->assertSame(1, $commentAdmin->getChildDepth());
2398
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2399
    }
2400
2401
    public function testGetCurrentLeafChildAdmin()
2402
    {
2403
        $postAdmin = new PostAdmin(
2404
            'sonata.post.admin.post',
2405
            'Application\Sonata\NewsBundle\Entity\Post',
2406
            'SonataNewsBundle:PostAdmin'
2407
        );
2408
        $commentAdmin = new CommentAdmin(
2409
            'sonata.post.admin.comment',
2410
            'Application\Sonata\NewsBundle\Entity\Comment',
2411
            'SonataNewsBundle:CommentAdmin'
2412
        );
2413
        $commentVoteAdmin = new CommentVoteAdmin(
2414
            'sonata.post.admin.comment_vote',
2415
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2416
            'SonataNewsBundle:CommentVoteAdmin'
2417
        );
2418
2419
        $postAdmin->addChild($commentAdmin);
2420
        $commentAdmin->addChild($commentVoteAdmin);
2421
2422
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2423
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2424
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2425
2426
        $commentAdmin->setCurrentChild(true);
2427
2428
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2429
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2430
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2431
2432
        $commentVoteAdmin->setCurrentChild(true);
2433
2434
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2435
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2436
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2437
    }
2438
2439
    private function createTagAdmin(Post $post)
2440
    {
2441
        $postAdmin = $this->getMockBuilder(PostAdmin::class)
2442
            ->disableOriginalConstructor()
2443
            ->getMock();
2444
2445
        $postAdmin->expects($this->any())->method('getObject')->will($this->returnValue($post));
2446
2447
        $formBuilder = $this->createMock(FormBuilderInterface::class);
2448
        $formBuilder->expects($this->any())->method('getForm')->will($this->returnValue(null));
2449
2450
        $tagAdmin = $this->getMockBuilder(TagAdmin::class)
2451
            ->setConstructorArgs([
2452
                'admin.tag',
2453
                Tag::class,
2454
                'MyBundle:MyController',
2455
            ])
2456
            ->setMethods(['getFormBuilder'])
2457
            ->getMock();
2458
2459
        $tagAdmin->expects($this->any())->method('getFormBuilder')->will($this->returnValue($formBuilder));
2460
        $tagAdmin->setParent($postAdmin);
2461
2462
        $tag = new Tag();
2463
        $tagAdmin->setSubject($tag);
2464
2465
        $request = $this->createMock(Request::class);
2466
        $tagAdmin->setRequest($request);
2467
2468
        $configurationPool = $this->getMockBuilder(Pool::class)
2469
            ->disableOriginalConstructor()
2470
            ->getMock();
2471
2472
        $configurationPool->expects($this->any())->method('getPropertyAccessor')->will($this->returnValue(PropertyAccess::createPropertyAccessor()));
2473
2474
        $tagAdmin->setConfigurationPool($configurationPool);
2475
2476
        return $tagAdmin;
2477
    }
2478
}
2479