Completed
Push — 3.x ( 799626...732596 )
by Grégoire
04:11
created

AdminTest::testGetBaseController()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

Loading history...
1178
    }
1179
1180
    public function testGetTemplate1()
1181
    {
1182
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1183
1184
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1185
        $templateRegistry->getTemplate('edit')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/edit.html.twig');
1186
        $templateRegistry->getTemplate('show')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/show.html.twig');
1187
1188
        $admin->setTemplateRegistry($templateRegistry->reveal());
1189
1190
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since 3.x, will be dropped in 4.0. Use TemplateRegistry services instead

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

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

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

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

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

Loading history...
1192
    }
1193
1194
    public function testGetIdParameter()
1195
    {
1196
        $postAdmin = new PostAdmin(
1197
            'sonata.post.admin.post',
1198
            'NewsBundle\Entity\Post',
1199
            'SonataNewsBundle:PostAdmin'
1200
        );
1201
1202
        $this->assertSame('id', $postAdmin->getIdParameter());
1203
        $this->assertFalse($postAdmin->isChild());
1204
1205
        $commentAdmin = new CommentAdmin(
1206
            'sonata.post.admin.comment',
1207
            'Application\Sonata\NewsBundle\Entity\Comment',
1208
            'SonataNewsBundle:CommentAdmin'
1209
        );
1210
        $commentAdmin->setParent($postAdmin);
1211
1212
        $this->assertTrue($commentAdmin->isChild());
1213
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1214
1215
        $commentVoteAdmin = new CommentVoteAdmin(
1216
            'sonata.post.admin.comment_vote',
1217
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1218
            'SonataNewsBundle:CommentVoteAdmin'
1219
        );
1220
        $commentVoteAdmin->setParent($commentAdmin);
1221
1222
        $this->assertTrue($commentVoteAdmin->isChild());
1223
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1224
    }
1225
1226
    public function testGetExportFormats()
1227
    {
1228
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1229
1230
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1231
    }
1232
1233
    public function testGetUrlsafeIdentifier()
1234
    {
1235
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1236
1237
        $entity = new \stdClass();
1238
1239
        $modelManager = $this->createMock(ModelManagerInterface::class);
1240
        $modelManager->expects($this->once())
1241
            ->method('getUrlsafeIdentifier')
1242
            ->with($this->equalTo($entity))
1243
            ->will($this->returnValue('foo'));
1244
        $admin->setModelManager($modelManager);
1245
1246
        $this->assertSame('foo', $admin->getUrlsafeIdentifier($entity));
1247
    }
1248
1249
    public function testDeterminedPerPageValue()
1250
    {
1251
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1252
1253
        $this->assertFalse($admin->determinedPerPageValue('foo'));
1254
        $this->assertFalse($admin->determinedPerPageValue(123));
1255
        $this->assertTrue($admin->determinedPerPageValue(16));
1256
        $this->assertTrue($admin->determinedPerPageValue(32));
1257
        $this->assertTrue($admin->determinedPerPageValue(64));
1258
        $this->assertTrue($admin->determinedPerPageValue(128));
1259
        $this->assertTrue($admin->determinedPerPageValue(192));
1260
1261
        $admin->setPerPageOptions([101, 102, 103]);
1262
        $this->assertFalse($admin->determinedPerPageValue(15));
1263
        $this->assertFalse($admin->determinedPerPageValue(25));
1264
        $this->assertFalse($admin->determinedPerPageValue(200));
1265
        $this->assertTrue($admin->determinedPerPageValue(101));
1266
        $this->assertTrue($admin->determinedPerPageValue(102));
1267
        $this->assertTrue($admin->determinedPerPageValue(103));
1268
    }
1269
1270
    public function testIsGranted()
1271
    {
1272
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1273
1274
        $entity = new \stdClass();
1275
1276
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1277
        $securityHandler->expects($this->any())
1278
            ->method('isGranted')
1279
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin, $entity) {
1280
                if ($admin == $adminIn && 'FOO' == $attributes) {
1281
                    if (($object == $admin) || ($object == $entity)) {
1282
                        return true;
1283
                    }
1284
                }
1285
1286
                return false;
1287
            }));
1288
1289
        $admin->setSecurityHandler($securityHandler);
1290
1291
        $this->assertTrue($admin->isGranted('FOO'));
1292
        $this->assertTrue($admin->isGranted('FOO', $entity));
1293
        $this->assertFalse($admin->isGranted('BAR'));
1294
        $this->assertFalse($admin->isGranted('BAR', $entity));
1295
    }
1296
1297
    public function testSupportsPreviewMode()
1298
    {
1299
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1300
1301
        $this->assertFalse($admin->supportsPreviewMode());
1302
    }
1303
1304
    public function testGetPermissionsShow()
1305
    {
1306
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1307
1308
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1309
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1310
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1311
    }
1312
1313
    public function testShowIn()
1314
    {
1315
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1316
1317
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1318
        $securityHandler->expects($this->any())
1319
            ->method('isGranted')
1320
            ->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...
1321
                if ($admin == $adminIn && $attributes == ['LIST']) {
1322
                    return true;
1323
                }
1324
1325
                return false;
1326
            }));
1327
1328
        $admin->setSecurityHandler($securityHandler);
1329
1330
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1331
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1332
        $this->assertTrue($admin->showIn('foo'));
1333
    }
1334
1335
    public function testGetObjectIdentifier()
1336
    {
1337
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1338
1339
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1340
    }
1341
1342
    /**
1343
     * @group legacy
1344
     */
1345
    public function testTrans()
1346
    {
1347
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1348
        $admin->setTranslationDomain('fooMessageDomain');
1349
1350
        $translator = $this->createMock(TranslatorInterface::class);
1351
        $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...
1352
1353
        $translator->expects($this->once())
1354
            ->method('trans')
1355
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1356
            ->will($this->returnValue('fooTranslated'));
1357
1358
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1359
    }
1360
1361
    /**
1362
     * @group legacy
1363
     */
1364
    public function testTransWithMessageDomain()
1365
    {
1366
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1367
1368
        $translator = $this->createMock(TranslatorInterface::class);
1369
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

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