Completed
Push — 3.x ( eb4387...163e30 )
by Jordi Sala
04:29
created

testFormAddPostSubmitEventForPreValidation()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 60
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 60
rs 9.5555
cc 2
eloc 44
nc 1
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
114
        $admin->setSubClasses([]);
115
        $this->assertSame($class, $admin->getClass());
116
117
        $admin->setSubClasses(['foo' => 'bar']);
118
        $admin->setRequest(new Request(['subclass' => 'foo']));
119
        $this->assertSame('bar', $admin->getClass());
120
    }
121
122
    public function testGetClassException()
123
    {
124
        $this->expectException(\RuntimeException::class);
125
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
126
127
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
128
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
129
130
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
131
        $admin->setParentFieldDescription(new FieldDescription());
132
        $admin->setSubClasses(['foo' => 'bar']);
133
        $admin->setRequest(new Request(['subclass' => 'foo']));
134
        $admin->getClass();
135
    }
136
137
    public function testCheckAccessThrowsExceptionOnMadeUpAction()
138
    {
139
        $admin = new PostAdmin(
140
            'sonata.post.admin.post',
141
            'Application\Sonata\NewsBundle\Entity\Post',
142
            'SonataNewsBundle:PostAdmin'
143
        );
144
        $this->expectException(
145
            \InvalidArgumentException::class
146
        );
147
        $this->expectExceptionMessage(
148
            'Action "made-up" could not be found'
149
        );
150
        $admin->checkAccess('made-up');
151
    }
152
153
    public function testCheckAccessThrowsAccessDeniedException()
154
    {
155
        $admin = new PostAdmin(
156
            'sonata.post.admin.post',
157
            'Application\Sonata\NewsBundle\Entity\Post',
158
            'SonataNewsBundle:PostAdmin'
159
        );
160
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
161
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
162
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
163
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
164
        $customExtension->getAccessMapping($admin)->willReturn(
165
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
166
        );
167
        $admin->addExtension($customExtension->reveal());
168
        $admin->setSecurityHandler($securityHandler->reveal());
169
        $this->expectException(
170
            AccessDeniedException::class
171
        );
172
        $this->expectExceptionMessage(
173
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
174
        );
175
        $admin->checkAccess('custom_action');
176
    }
177
178
    public function testHasAccessOnMadeUpAction()
179
    {
180
        $admin = new PostAdmin(
181
            'sonata.post.admin.post',
182
            'Application\Sonata\NewsBundle\Entity\Post',
183
            'SonataNewsBundle:PostAdmin'
184
        );
185
186
        $this->assertFalse($admin->hasAccess('made-up'));
187
    }
188
189
    public function testHasAccess()
190
    {
191
        $admin = new PostAdmin(
192
            'sonata.post.admin.post',
193
            'Application\Sonata\NewsBundle\Entity\Post',
194
            'SonataNewsBundle:PostAdmin'
195
        );
196
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
197
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
198
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
199
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
200
        $customExtension->getAccessMapping($admin)->willReturn(
201
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
202
        );
203
        $admin->addExtension($customExtension->reveal());
204
        $admin->setSecurityHandler($securityHandler->reveal());
205
206
        $this->assertFalse($admin->hasAccess('custom_action'));
207
    }
208
209
    public function testHasAccessAllowsAccess()
210
    {
211
        $admin = new PostAdmin(
212
            'sonata.post.admin.post',
213
            'Application\Sonata\NewsBundle\Entity\Post',
214
            'SonataNewsBundle:PostAdmin'
215
        );
216
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
217
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
218
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
219
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
220
        $customExtension->getAccessMapping($admin)->willReturn(
221
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
222
        );
223
        $admin->addExtension($customExtension->reveal());
224
        $admin->setSecurityHandler($securityHandler->reveal());
225
226
        $this->assertTrue($admin->hasAccess('custom_action'));
227
    }
228
229
    public function testHasAccessAllowsAccessEditAction()
230
    {
231
        $admin = new PostAdmin(
232
            'sonata.post.admin.post',
233
            'Application\Sonata\NewsBundle\Entity\Post',
234
            'SonataNewsBundle:PostAdmin'
235
        );
236
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
237
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
238
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
239
        $customExtension->getAccessMapping($admin)->willReturn(
240
            ['edit_action' => ['EDIT_ROLE']]
241
        );
242
        $admin->addExtension($customExtension->reveal());
243
        $admin->setSecurityHandler($securityHandler->reveal());
244
245
        $this->assertTrue($admin->hasAccess('edit_action'));
246
    }
247
248
    /**
249
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
250
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
251
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
252
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
253
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
254
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
255
     */
256
    public function testChildren()
257
    {
258
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
259
        $this->assertFalse($postAdmin->hasChildren());
260
        $this->assertFalse($postAdmin->hasChild('comment'));
261
262
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
263
        $postAdmin->addChild($commentAdmin);
264
        $this->assertTrue($postAdmin->hasChildren());
265
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
266
267
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
268
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
269
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
270
271
        $this->assertFalse($postAdmin->isChild());
272
        $this->assertTrue($commentAdmin->isChild());
273
274
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
275
    }
276
277
    /**
278
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
279
     */
280
    public function testConfigure()
281
    {
282
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
283
        $this->assertNotNull($admin->getUniqid());
284
285
        $admin->initialize();
286
        $this->assertNotNull($admin->getUniqid());
287
        $this->assertSame('Post', $admin->getClassnameLabel());
288
289
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
290
        $admin->setClassnameLabel('postcomment');
291
292
        $admin->initialize();
293
        $this->assertSame('postcomment', $admin->getClassnameLabel());
294
    }
295
296
    public function testConfigureWithValidParentAssociationMapping()
297
    {
298
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
299
        $admin->setParentAssociationMapping('Category');
300
301
        $admin->initialize();
302
        $this->assertSame('Category', $admin->getParentAssociationMapping());
303
    }
304
305
    public function provideGetBaseRoutePattern()
306
    {
307
        return [
308
            [
309
                'Application\Sonata\NewsBundle\Entity\Post',
310
                '/sonata/news/post',
311
            ],
312
            [
313
                'Application\Sonata\NewsBundle\Document\Post',
314
                '/sonata/news/post',
315
            ],
316
            [
317
                'MyApplication\MyBundle\Entity\Post',
318
                '/myapplication/my/post',
319
            ],
320
            [
321
                'MyApplication\MyBundle\Entity\Post\Category',
322
                '/myapplication/my/post-category',
323
            ],
324
            [
325
                'MyApplication\MyBundle\Entity\Product\Category',
326
                '/myapplication/my/product-category',
327
            ],
328
            [
329
                'MyApplication\MyBundle\Entity\Other\Product\Category',
330
                '/myapplication/my/other-product-category',
331
            ],
332
            [
333
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
334
                '/cmf/foo/menu',
335
            ],
336
            [
337
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
338
                '/cmf/foo/menu',
339
            ],
340
            [
341
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
342
                '/symfony/barbar/menu',
343
            ],
344
            [
345
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
346
                '/symfony/barbar/menu-item',
347
            ],
348
            [
349
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
350
                '/cmf/foo/menu',
351
            ],
352
            [
353
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
354
                '/cmf/foo/menu',
355
            ],
356
            [
357
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
358
                '/cmf/foo/menu',
359
            ],
360
            [
361
                'AppBundle\Entity\User',
362
                '/app/user',
363
            ],
364
            [
365
                'App\Entity\User',
366
                '/app/user',
367
            ],
368
        ];
369
    }
370
371
    /**
372
     * @dataProvider provideGetBaseRoutePattern
373
     */
374
    public function testGetBaseRoutePattern($objFqn, $expected)
375
    {
376
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
377
        $this->assertSame($expected, $admin->getBaseRoutePattern());
378
    }
379
380
    /**
381
     * @dataProvider provideGetBaseRoutePattern
382
     */
383
    public function testGetBaseRoutePatternWithChildAdmin($objFqn, $expected)
384
    {
385
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
386
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
387
        $commentAdmin->setParent($postAdmin);
388
389
        $this->assertSame($expected.'/{id}/comment', $commentAdmin->getBaseRoutePattern());
390
    }
391
392
    /**
393
     * @dataProvider provideGetBaseRoutePattern
394
     */
395
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin($objFqn, $expected)
396
    {
397
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
398
        $commentAdmin = new CommentAdmin(
399
            'sonata.post.admin.comment',
400
            'Application\Sonata\NewsBundle\Entity\Comment',
401
            'SonataNewsBundle:CommentAdmin'
402
        );
403
        $commentVoteAdmin = new CommentVoteAdmin(
404
            'sonata.post.admin.comment_vote',
405
            'Application\Sonata\NewsBundle\Entity\CommentVote',
406
            'SonataNewsBundle:CommentVoteAdmin'
407
        );
408
        $commentAdmin->setParent($postAdmin);
409
        $commentVoteAdmin->setParent($commentAdmin);
410
411
        $this->assertSame($expected.'/{id}/comment/{childId}/commentvote', $commentVoteAdmin->getBaseRoutePattern());
412
    }
413
414
    public function testGetBaseRoutePatternWithSpecifedPattern()
415
    {
416
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostWithCustomRouteAdmin');
417
418
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
419
    }
420
421
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern()
422
    {
423
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
424
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
425
        $commentAdmin->setParent($postAdmin);
426
427
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
428
    }
429
430
    public function testGetBaseRoutePatternWithUnreconizedClassname()
431
    {
432
        $this->expectException(\RuntimeException::class);
433
434
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
435
        $admin->getBaseRoutePattern();
436
    }
437
438
    public function provideGetBaseRouteName()
439
    {
440
        return [
441
            [
442
                'Application\Sonata\NewsBundle\Entity\Post',
443
                'admin_sonata_news_post',
444
            ],
445
            [
446
                'Application\Sonata\NewsBundle\Document\Post',
447
                'admin_sonata_news_post',
448
            ],
449
            [
450
                'MyApplication\MyBundle\Entity\Post',
451
                'admin_myapplication_my_post',
452
            ],
453
            [
454
                'MyApplication\MyBundle\Entity\Post\Category',
455
                'admin_myapplication_my_post_category',
456
            ],
457
            [
458
                'MyApplication\MyBundle\Entity\Product\Category',
459
                'admin_myapplication_my_product_category',
460
            ],
461
            [
462
                'MyApplication\MyBundle\Entity\Other\Product\Category',
463
                'admin_myapplication_my_other_product_category',
464
            ],
465
            [
466
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
467
                'admin_cmf_foo_menu',
468
            ],
469
            [
470
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
471
                'admin_cmf_foo_menu',
472
            ],
473
            [
474
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
475
                'admin_symfony_barbar_menu',
476
            ],
477
            [
478
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
479
                'admin_symfony_barbar_menu_item',
480
            ],
481
            [
482
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
483
                'admin_cmf_foo_menu',
484
            ],
485
            [
486
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
487
                'admin_cmf_foo_menu',
488
            ],
489
            [
490
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
491
                'admin_cmf_foo_menu',
492
            ],
493
            [
494
                'AppBundle\Entity\User',
495
                'admin_app_user',
496
            ],
497
            [
498
                'App\Entity\User',
499
                'admin_app_user',
500
            ],
501
        ];
502
    }
503
504
    /**
505
     * @dataProvider provideGetBaseRouteName
506
     */
507
    public function testGetBaseRouteName($objFqn, $expected)
508
    {
509
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
510
511
        $this->assertSame($expected, $admin->getBaseRouteName());
512
    }
513
514
    /**
515
     * @dataProvider provideGetBaseRouteName
516
     */
517
    public function testGetBaseRouteNameWithChildAdmin($objFqn, $expected)
518
    {
519
        $routeGenerator = new DefaultRouteGenerator(
520
            $this->createMock(RouterInterface::class),
521
            new RoutesCache($this->cacheTempFolder, true)
522
        );
523
524
        $container = new Container();
525
        $pool = new Pool($container, 'Sonata Admin', '/path/to/pic.png');
526
527
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
528
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
529
        $container->set('sonata.post.admin.post', $postAdmin);
530
        $postAdmin->setConfigurationPool($pool);
531
        $postAdmin->setRouteBuilder($pathInfo);
532
        $postAdmin->setRouteGenerator($routeGenerator);
533
        $postAdmin->initialize();
534
535
        $commentAdmin = new CommentAdmin(
536
            'sonata.post.admin.comment',
537
            'Application\Sonata\NewsBundle\Entity\Comment',
538
            'SonataNewsBundle:CommentAdmin'
539
        );
540
        $container->set('sonata.post.admin.comment', $commentAdmin);
541
        $commentAdmin->setConfigurationPool($pool);
542
        $commentAdmin->setRouteBuilder($pathInfo);
543
        $commentAdmin->setRouteGenerator($routeGenerator);
544
        $commentAdmin->initialize();
545
546
        $postAdmin->addChild($commentAdmin);
547
548
        $commentVoteAdmin = new CommentVoteAdmin(
549
            'sonata.post.admin.comment_vote',
550
            'Application\Sonata\NewsBundle\Entity\CommentVote',
551
            'SonataNewsBundle:CommentVoteAdmin'
552
        );
553
        $container->set('sonata.post.admin.comment_vote', $commentVoteAdmin);
554
        $commentVoteAdmin->setConfigurationPool($pool);
555
        $commentVoteAdmin->setRouteBuilder($pathInfo);
556
        $commentVoteAdmin->setRouteGenerator($routeGenerator);
557
        $commentVoteAdmin->initialize();
558
559
        $commentAdmin->addChild($commentVoteAdmin);
560
        $pool->setAdminServiceIds([
561
            'sonata.post.admin.post',
562
            'sonata.post.admin.comment',
563
            'sonata.post.admin.comment_vote',
564
        ]);
565
566
        $this->assertSame($expected.'_comment', $commentAdmin->getBaseRouteName());
567
568
        $this->assertTrue($postAdmin->hasRoute('show'));
569
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show'));
570
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.show'));
571
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment|sonata.post.admin.comment_vote.show'));
572
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment.list'));
573
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment|sonata.post.admin.comment_vote.list'));
574
        $this->assertFalse($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.edit'));
575
        $this->assertFalse($commentAdmin->hasRoute('edit'));
576
577
        /*
578
         * Test the route name from request
579
         */
580
        $postListRequest = new Request(
581
            [],
582
            [],
583
            [
584
                '_route' => $postAdmin->getBaseRouteName().'_list',
585
            ]
586
        );
587
588
        $postAdmin->setRequest($postListRequest);
589
        $commentAdmin->setRequest($postListRequest);
590
591
        $this->assertTrue($postAdmin->isCurrentRoute('list'));
592
        $this->assertFalse($postAdmin->isCurrentRoute('create'));
593
        $this->assertFalse($commentAdmin->isCurrentRoute('list'));
594
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('list'));
595
        $this->assertTrue($commentAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
596
        $this->assertFalse($commentAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
597
        $this->assertTrue($commentVoteAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
598
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
599
    }
600
601
    public function testGetBaseRouteNameWithUnreconizedClassname()
602
    {
603
        $this->expectException(\RuntimeException::class);
604
605
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'SonataNewsBundle:PostAdmin');
606
        $admin->getBaseRouteName();
607
    }
608
609
    public function testGetBaseRouteNameWithSpecifiedName()
610
    {
611
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
612
613
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
614
    }
615
616
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName()
617
    {
618
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
619
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentWithCustomRouteAdmin');
620
        $commentAdmin->setParent($postAdmin);
621
622
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
623
    }
624
625
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName()
626
    {
627
        $postAdmin = new PostAdmin(
628
            'sonata.post.admin.post',
629
            'Application\Sonata\NewsBundle\Entity\Post',
630
            'SonataNewsBundle:PostAdmin'
631
        );
632
        $commentAdmin = new CommentWithCustomRouteAdmin(
633
            'sonata.post.admin.comment_with_custom_route',
634
            'Application\Sonata\NewsBundle\Entity\Comment',
635
            'SonataNewsBundle:CommentWithCustomRouteAdmin'
636
        );
637
        $commentVoteAdmin = new CommentVoteAdmin(
638
            'sonata.post.admin.comment_vote',
639
            'Application\Sonata\NewsBundle\Entity\CommentVote',
640
            'SonataNewsBundle:CommentVoteAdmin'
641
        );
642
        $commentAdmin->setParent($postAdmin);
643
        $commentVoteAdmin->setParent($commentAdmin);
644
645
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
646
    }
647
648
    /**
649
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
650
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
651
     */
652
    public function testUniqid()
653
    {
654
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
655
656
        $uniqid = uniqid();
657
        $admin->setUniqid($uniqid);
658
659
        $this->assertSame($uniqid, $admin->getUniqid());
660
    }
661
662
    public function testToString()
663
    {
664
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
665
666
        $s = new \stdClass();
667
668
        $this->assertNotEmpty($admin->toString($s));
669
670
        $s = new FooToString();
671
        $this->assertSame('salut', $admin->toString($s));
672
673
        // To string method is implemented, but returns null
674
        $s = new FooToStringNull();
675
        $this->assertNotEmpty($admin->toString($s));
676
677
        $this->assertSame('', $admin->toString(false));
678
    }
679
680
    public function testIsAclEnabled()
681
    {
682
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
683
684
        $this->assertFalse($postAdmin->isAclEnabled());
685
686
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
687
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
688
        $this->assertTrue($commentAdmin->isAclEnabled());
689
    }
690
691
    /**
692
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
693
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
694
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
695
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
696
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
697
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
698
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
699
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
700
     */
701
    public function testSubClass()
702
    {
703
        $admin = new PostAdmin(
704
            'sonata.post.admin.post',
705
            Post::class,
706
            'SonataNewsBundle:PostAdmin'
707
        );
708
        $this->assertFalse($admin->hasSubClass('test'));
709
        $this->assertFalse($admin->hasActiveSubClass());
710
        $this->assertCount(0, $admin->getSubClasses());
711
        $this->assertNull($admin->getActiveSubClass());
712
        $this->assertNull($admin->getActiveSubclassCode());
713
        $this->assertSame(Post::class, $admin->getClass());
714
715
        // Just for the record, if there is no inheritance set, the getSubject is not used
716
        // the getSubject can also lead to some issue
717
        $admin->setSubject(new BlogPost());
718
        $this->assertSame(BlogPost::class, $admin->getClass());
719
720
        $admin->setSubClasses([
721
            'extended1' => 'NewsBundle\Entity\PostExtended1',
722
            'extended2' => 'NewsBundle\Entity\PostExtended2',
723
        ]);
724
        $this->assertFalse($admin->hasSubClass('test'));
725
        $this->assertTrue($admin->hasSubClass('extended1'));
726
        $this->assertFalse($admin->hasActiveSubClass());
727
        $this->assertCount(2, $admin->getSubClasses());
728
        $this->assertNull($admin->getActiveSubClass());
729
        $this->assertNull($admin->getActiveSubclassCode());
730
        $this->assertSame(
731
            BlogPost::class,
732
            $admin->getClass(),
733
            'When there is no subclass in the query the class parameter should be returned'
734
        );
735
736
        $request = new Request(['subclass' => 'extended1']);
737
        $admin->setRequest($request);
738
        $this->assertFalse($admin->hasSubClass('test'));
739
        $this->assertTrue($admin->hasSubClass('extended1'));
740
        $this->assertTrue($admin->hasActiveSubClass());
741
        $this->assertCount(2, $admin->getSubClasses());
742
        $this->assertSame(
743
            'NewsBundle\Entity\PostExtended1',
744
            $admin->getActiveSubClass(),
745
            'It should return the curently active sub class.'
746
        );
747
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
748
        $this->assertSame(
749
            'NewsBundle\Entity\PostExtended1',
750
            $admin->getClass(),
751
            'getClass() should return the name of the sub class when passed through a request query parameter.'
752
        );
753
754
        $request->query->set('subclass', 'inject');
755
        $this->assertNull($admin->getActiveSubclassCode());
756
    }
757
758
    public function testNonExistantSubclass()
759
    {
760
        $this->expectException(\RuntimeException::class);
761
762
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
763
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
764
765
        $admin->setRequest(new Request(['subclass' => 'inject']));
766
767
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
768
769
        $this->assertTrue($admin->hasActiveSubClass());
770
771
        $admin->getActiveSubClass();
772
    }
773
774
    /**
775
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
776
     */
777
    public function testOnlyOneSubclassNeededToBeActive()
778
    {
779
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
780
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
781
        $request = new Request(['subclass' => 'extended1']);
782
        $admin->setRequest($request);
783
        $this->assertTrue($admin->hasActiveSubClass());
784
    }
785
786
    /**
787
     * @group legacy
788
     * @expectedDeprecation Method "Sonata\AdminBundle\Admin\AbstractAdmin::addSubClass" is deprecated since 3.30 and will be removed in 4.0.
789
     */
790
    public function testAddSubClassIsDeprecated()
791
    {
792
        $admin = new PostAdmin(
793
            'sonata.post.admin.post',
794
            Post::class,
795
            'SonataNewsBundle:PostAdmin'
796
        );
797
        $admin->addSubClass('whatever');
798
    }
799
800
    public function testGetPerPageOptions()
801
    {
802
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
803
804
        $this->assertSame([16, 32, 64, 128, 192], $admin->getPerPageOptions());
805
        $admin->setPerPageOptions([500, 1000]);
806
        $this->assertSame([500, 1000], $admin->getPerPageOptions());
807
    }
808
809
    public function testGetLabelTranslatorStrategy()
810
    {
811
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
812
813
        $this->assertNull($admin->getLabelTranslatorStrategy());
814
815
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
816
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
817
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
818
    }
819
820
    public function testGetRouteBuilder()
821
    {
822
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
823
824
        $this->assertNull($admin->getRouteBuilder());
825
826
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
827
        $admin->setRouteBuilder($routeBuilder);
828
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
829
    }
830
831
    public function testGetMenuFactory()
832
    {
833
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
834
835
        $this->assertNull($admin->getMenuFactory());
836
837
        $menuFactory = $this->createMock(FactoryInterface::class);
838
        $admin->setMenuFactory($menuFactory);
839
        $this->assertSame($menuFactory, $admin->getMenuFactory());
840
    }
841
842
    public function testGetExtensions()
843
    {
844
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
845
846
        $this->assertSame([], $admin->getExtensions());
847
848
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
849
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
850
851
        $admin->addExtension($adminExtension1);
852
        $admin->addExtension($adminExtension2);
853
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
854
    }
855
856
    public function testGetFilterTheme()
857
    {
858
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
859
860
        $this->assertSame([], $admin->getFilterTheme());
861
862
        $admin->setFilterTheme(['FooTheme']);
863
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
864
    }
865
866
    public function testGetFormTheme()
867
    {
868
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
869
870
        $this->assertSame([], $admin->getFormTheme());
871
872
        $admin->setFormTheme(['FooTheme']);
873
874
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
875
    }
876
877
    public function testGetValidator()
878
    {
879
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
880
881
        $this->assertNull($admin->getValidator());
882
883
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
884
885
        $admin->setValidator($validator);
886
        $this->assertSame($validator, $admin->getValidator());
887
    }
888
889
    public function testGetSecurityHandler()
890
    {
891
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
892
893
        $this->assertNull($admin->getSecurityHandler());
894
895
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
896
        $admin->setSecurityHandler($securityHandler);
897
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
898
    }
899
900
    public function testGetSecurityInformation()
901
    {
902
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
903
904
        $this->assertSame([], $admin->getSecurityInformation());
905
906
        $securityInformation = [
907
            'GUEST' => ['VIEW', 'LIST'],
908
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
909
        ];
910
911
        $admin->setSecurityInformation($securityInformation);
912
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
913
    }
914
915
    public function testGetManagerType()
916
    {
917
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
918
919
        $this->assertNull($admin->getManagerType());
920
921
        $admin->setManagerType('foo_orm');
922
        $this->assertSame('foo_orm', $admin->getManagerType());
923
    }
924
925
    public function testGetModelManager()
926
    {
927
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
928
929
        $this->assertNull($admin->getModelManager());
930
931
        $modelManager = $this->createMock(ModelManagerInterface::class);
932
933
        $admin->setModelManager($modelManager);
934
        $this->assertSame($modelManager, $admin->getModelManager());
935
    }
936
937
    /**
938
     * NEXT_MAJOR: remove this method.
939
     *
940
     * @group legacy
941
     */
942
    public function testGetBaseCodeRoute()
943
    {
944
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
945
946
        $this->assertSame('', $admin->getBaseCodeRoute());
947
948
        $admin->setBaseCodeRoute('foo');
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...min::setBaseCodeRoute() has been deprecated with message: This method is deprecated since 3.24 and will be removed in 4.0

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

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

Loading history...
949
        $this->assertSame('foo', $admin->getBaseCodeRoute());
950
    }
951
952
    // NEXT_MAJOR: uncomment this method.
953
    // public function testGetBaseCodeRoute()
954
    // {
955
    //     $postAdmin = new PostAdmin(
956
    //         'sonata.post.admin.post',
957
    //         'NewsBundle\Entity\Post',
958
    //         'SonataNewsBundle:PostAdmin'
959
    //     );
960
    //     $commentAdmin = new CommentAdmin(
961
    //         'sonata.post.admin.comment',
962
    //         'Application\Sonata\NewsBundle\Entity\Comment',
963
    //         'SonataNewsBundle:CommentAdmin'
964
    //     );
965
    //
966
    //     $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
967
    //
968
    //     $postAdmin->addChild($commentAdmin);
969
    //
970
    //     $this->assertSame(
971
    //         'sonata.post.admin.post|sonata.post.admin.comment',
972
    //         $commentAdmin->getBaseCodeRoute()
973
    //     );
974
    // }
975
976
    public function testGetRouteGenerator()
977
    {
978
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
979
980
        $this->assertNull($admin->getRouteGenerator());
981
982
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
983
984
        $admin->setRouteGenerator($routeGenerator);
985
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
986
    }
987
988
    public function testGetConfigurationPool()
989
    {
990
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
991
992
        $this->assertNull($admin->getConfigurationPool());
993
994
        $pool = $this->getMockBuilder(Pool::class)
995
            ->disableOriginalConstructor()
996
            ->getMock();
997
998
        $admin->setConfigurationPool($pool);
999
        $this->assertSame($pool, $admin->getConfigurationPool());
1000
    }
1001
1002
    public function testGetShowBuilder()
1003
    {
1004
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1005
1006
        $this->assertNull($admin->getShowBuilder());
1007
1008
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
1009
1010
        $admin->setShowBuilder($showBuilder);
1011
        $this->assertSame($showBuilder, $admin->getShowBuilder());
1012
    }
1013
1014
    public function testGetListBuilder()
1015
    {
1016
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1017
1018
        $this->assertNull($admin->getListBuilder());
1019
1020
        $listBuilder = $this->createMock(ListBuilderInterface::class);
1021
1022
        $admin->setListBuilder($listBuilder);
1023
        $this->assertSame($listBuilder, $admin->getListBuilder());
1024
    }
1025
1026
    public function testGetDatagridBuilder()
1027
    {
1028
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1029
1030
        $this->assertNull($admin->getDatagridBuilder());
1031
1032
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1033
1034
        $admin->setDatagridBuilder($datagridBuilder);
1035
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
1036
    }
1037
1038
    public function testGetFormContractor()
1039
    {
1040
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1041
1042
        $this->assertNull($admin->getFormContractor());
1043
1044
        $formContractor = $this->createMock(FormContractorInterface::class);
1045
1046
        $admin->setFormContractor($formContractor);
1047
        $this->assertSame($formContractor, $admin->getFormContractor());
1048
    }
1049
1050
    public function testGetRequest()
1051
    {
1052
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1053
1054
        $this->assertFalse($admin->hasRequest());
1055
1056
        $request = new Request();
1057
1058
        $admin->setRequest($request);
1059
        $this->assertSame($request, $admin->getRequest());
1060
        $this->assertTrue($admin->hasRequest());
1061
    }
1062
1063
    public function testGetRequestWithException()
1064
    {
1065
        $this->expectException(\RuntimeException::class);
1066
        $this->expectExceptionMessage('The Request object has not been set');
1067
1068
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1069
        $admin->getRequest();
1070
    }
1071
1072
    public function testGetTranslationDomain()
1073
    {
1074
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1075
1076
        $this->assertSame('messages', $admin->getTranslationDomain());
1077
1078
        $admin->setTranslationDomain('foo');
1079
        $this->assertSame('foo', $admin->getTranslationDomain());
1080
    }
1081
1082
    /**
1083
     * @group legacy
1084
     */
1085
    public function testGetTranslator()
1086
    {
1087
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1088
1089
        $this->assertNull($admin->getTranslator());
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::getTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1090
1091
        $translator = $this->createMock(TranslatorInterface::class);
1092
1093
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1094
        $this->assertSame($translator, $admin->getTranslator());
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::getTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1095
    }
1096
1097
    public function testGetShowGroups()
1098
    {
1099
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1100
1101
        $this->assertFalse($admin->getShowGroups());
1102
1103
        $groups = ['foo', 'bar', 'baz'];
1104
1105
        $admin->setShowGroups($groups);
1106
        $this->assertSame($groups, $admin->getShowGroups());
1107
    }
1108
1109
    public function testGetFormGroups()
1110
    {
1111
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1112
1113
        $this->assertFalse($admin->getFormGroups());
1114
1115
        $groups = ['foo', 'bar', 'baz'];
1116
1117
        $admin->setFormGroups($groups);
1118
        $this->assertSame($groups, $admin->getFormGroups());
1119
    }
1120
1121
    public function testGetMaxPageLinks()
1122
    {
1123
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1124
1125
        $this->assertSame(25, $admin->getMaxPageLinks());
1126
1127
        $admin->setMaxPageLinks(14);
1128
        $this->assertSame(14, $admin->getMaxPageLinks());
1129
    }
1130
1131
    public function testGetMaxPerPage()
1132
    {
1133
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1134
1135
        $this->assertSame(32, $admin->getMaxPerPage());
1136
1137
        $admin->setMaxPerPage(94);
1138
        $this->assertSame(94, $admin->getMaxPerPage());
1139
    }
1140
1141
    public function testGetLabel()
1142
    {
1143
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1144
1145
        $this->assertNull($admin->getLabel());
1146
1147
        $admin->setLabel('FooLabel');
1148
        $this->assertSame('FooLabel', $admin->getLabel());
1149
    }
1150
1151
    public function testGetBaseController()
1152
    {
1153
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1154
1155
        $this->assertSame('SonataNewsBundle:PostAdmin', $admin->getBaseControllerName());
1156
1157
        $admin->setBaseControllerName('SonataNewsBundle:FooAdmin');
1158
        $this->assertSame('SonataNewsBundle:FooAdmin', $admin->getBaseControllerName());
1159
    }
1160
1161
    public function testGetTemplates()
1162
    {
1163
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1164
1165
        $this->assertSame([], $admin->getTemplates());
1166
1167
        $templates = [
1168
            'list' => '@FooAdmin/CRUD/list.html.twig',
1169
            'show' => '@FooAdmin/CRUD/show.html.twig',
1170
            'edit' => '@FooAdmin/CRUD/edit.html.twig',
1171
        ];
1172
1173
        $admin->setTemplates($templates);
1174
        $this->assertSame($templates, $admin->getTemplates());
1175
    }
1176
1177
    public function testGetTemplate1()
1178
    {
1179
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1180
1181
        $this->assertNull($admin->getTemplate('edit'));
1182
1183
        $admin->setTemplate('edit', '@FooAdmin/CRUD/edit.html.twig');
1184
        $admin->setTemplate('show', '@FooAdmin/CRUD/show.html.twig');
1185
1186
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
1187
        $this->assertSame('@FooAdmin/CRUD/show.html.twig', $admin->getTemplate('show'));
1188
    }
1189
1190
    public function testGetTemplate2()
1191
    {
1192
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1193
1194
        $this->assertNull($admin->getTemplate('edit'));
1195
1196
        $templates = [
1197
            'list' => '@FooAdmin/CRUD/list.html.twig',
1198
            'show' => '@FooAdmin/CRUD/show.html.twig',
1199
            'edit' => '@FooAdmin/CRUD/edit.html.twig',
1200
        ];
1201
1202
        $admin->setTemplates($templates);
1203
1204
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
1205
        $this->assertSame('@FooAdmin/CRUD/show.html.twig', $admin->getTemplate('show'));
1206
    }
1207
1208
    public function testGetIdParameter()
1209
    {
1210
        $postAdmin = new PostAdmin(
1211
            'sonata.post.admin.post',
1212
            'NewsBundle\Entity\Post',
1213
            'SonataNewsBundle:PostAdmin'
1214
        );
1215
1216
        $this->assertSame('id', $postAdmin->getIdParameter());
1217
        $this->assertFalse($postAdmin->isChild());
1218
1219
        $commentAdmin = new CommentAdmin(
1220
            'sonata.post.admin.comment',
1221
            'Application\Sonata\NewsBundle\Entity\Comment',
1222
            'SonataNewsBundle:CommentAdmin'
1223
        );
1224
        $commentAdmin->setParent($postAdmin);
1225
1226
        $this->assertTrue($commentAdmin->isChild());
1227
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1228
1229
        $commentVoteAdmin = new CommentVoteAdmin(
1230
            'sonata.post.admin.comment_vote',
1231
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1232
            'SonataNewsBundle:CommentVoteAdmin'
1233
        );
1234
        $commentVoteAdmin->setParent($commentAdmin);
1235
1236
        $this->assertTrue($commentVoteAdmin->isChild());
1237
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1238
    }
1239
1240
    public function testGetExportFormats()
1241
    {
1242
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1243
1244
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1245
    }
1246
1247
    public function testGetUrlsafeIdentifier()
1248
    {
1249
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1250
1251
        $entity = new \stdClass();
1252
1253
        $modelManager = $this->createMock(ModelManagerInterface::class);
1254
        $modelManager->expects($this->once())
1255
            ->method('getUrlsafeIdentifier')
1256
            ->with($this->equalTo($entity))
1257
            ->will($this->returnValue('foo'));
1258
        $admin->setModelManager($modelManager);
1259
1260
        $this->assertSame('foo', $admin->getUrlsafeIdentifier($entity));
1261
    }
1262
1263
    public function testDeterminedPerPageValue()
1264
    {
1265
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1266
1267
        $this->assertFalse($admin->determinedPerPageValue('foo'));
1268
        $this->assertFalse($admin->determinedPerPageValue(123));
1269
        $this->assertTrue($admin->determinedPerPageValue(16));
1270
        $this->assertTrue($admin->determinedPerPageValue(32));
1271
        $this->assertTrue($admin->determinedPerPageValue(64));
1272
        $this->assertTrue($admin->determinedPerPageValue(128));
1273
        $this->assertTrue($admin->determinedPerPageValue(192));
1274
1275
        $admin->setPerPageOptions([101, 102, 103]);
1276
        $this->assertFalse($admin->determinedPerPageValue(15));
1277
        $this->assertFalse($admin->determinedPerPageValue(25));
1278
        $this->assertFalse($admin->determinedPerPageValue(200));
1279
        $this->assertTrue($admin->determinedPerPageValue(101));
1280
        $this->assertTrue($admin->determinedPerPageValue(102));
1281
        $this->assertTrue($admin->determinedPerPageValue(103));
1282
    }
1283
1284
    public function testIsGranted()
1285
    {
1286
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1287
1288
        $entity = new \stdClass();
1289
1290
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1291
        $securityHandler->expects($this->any())
1292
            ->method('isGranted')
1293
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin, $entity) {
1294
                if ($admin == $adminIn && 'FOO' == $attributes) {
1295
                    if (($object == $admin) || ($object == $entity)) {
1296
                        return true;
1297
                    }
1298
                }
1299
1300
                return false;
1301
            }));
1302
1303
        $admin->setSecurityHandler($securityHandler);
1304
1305
        $this->assertTrue($admin->isGranted('FOO'));
1306
        $this->assertTrue($admin->isGranted('FOO', $entity));
1307
        $this->assertFalse($admin->isGranted('BAR'));
1308
        $this->assertFalse($admin->isGranted('BAR', $entity));
1309
    }
1310
1311
    public function testSupportsPreviewMode()
1312
    {
1313
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1314
1315
        $this->assertFalse($admin->supportsPreviewMode());
1316
    }
1317
1318
    public function testGetPermissionsShow()
1319
    {
1320
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1321
1322
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1323
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1324
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1325
    }
1326
1327
    public function testShowIn()
1328
    {
1329
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1330
1331
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1332
        $securityHandler->expects($this->any())
1333
            ->method('isGranted')
1334
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin) {
0 ignored issues
show
Unused Code introduced by
The parameter $object is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1335
                if ($admin == $adminIn && $attributes == ['LIST']) {
1336
                    return true;
1337
                }
1338
1339
                return false;
1340
            }));
1341
1342
        $admin->setSecurityHandler($securityHandler);
1343
1344
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1345
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1346
        $this->assertTrue($admin->showIn('foo'));
1347
    }
1348
1349
    public function testGetObjectIdentifier()
1350
    {
1351
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1352
1353
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1354
    }
1355
1356
    /**
1357
     * @group legacy
1358
     */
1359
    public function testTrans()
1360
    {
1361
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1362
        $admin->setTranslationDomain('fooMessageDomain');
1363
1364
        $translator = $this->createMock(TranslatorInterface::class);
1365
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1366
1367
        $translator->expects($this->once())
1368
            ->method('trans')
1369
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1370
            ->will($this->returnValue('fooTranslated'));
1371
1372
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1373
    }
1374
1375
    /**
1376
     * @group legacy
1377
     */
1378
    public function testTransWithMessageDomain()
1379
    {
1380
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1381
1382
        $translator = $this->createMock(TranslatorInterface::class);
1383
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1384
1385
        $translator->expects($this->once())
1386
            ->method('trans')
1387
            ->with($this->equalTo('foo'), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1388
            ->will($this->returnValue('fooTranslated'));
1389
1390
        $this->assertSame('fooTranslated', $admin->trans('foo', ['name' => 'Andrej'], 'fooMessageDomain'));
1391
    }
1392
1393
    /**
1394
     * @group legacy
1395
     */
1396
    public function testTransChoice()
1397
    {
1398
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1399
        $admin->setTranslationDomain('fooMessageDomain');
1400
1401
        $translator = $this->createMock(TranslatorInterface::class);
1402
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1403
1404
        $translator->expects($this->once())
1405
            ->method('transChoice')
1406
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1407
            ->will($this->returnValue('fooTranslated'));
1408
1409
        $this->assertSame('fooTranslated', $admin->transChoice('foo', 2));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::transChoice() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1410
    }
1411
1412
    /**
1413
     * @group legacy
1414
     */
1415
    public function testTransChoiceWithMessageDomain()
1416
    {
1417
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1418
1419
        $translator = $this->createMock(TranslatorInterface::class);
1420
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

Loading history...
1421
1422
        $translator->expects($this->once())
1423
            ->method('transChoice')
1424
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1425
            ->will($this->returnValue('fooTranslated'));
1426
1427
        $this->assertSame('fooTranslated', $admin->transChoice('foo', 2, ['name' => 'Andrej'], 'fooMessageDomain'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::transChoice() has been deprecated with message: since 3.9, to be removed with 4.0

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

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

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