Completed
Push — 3.x ( f37b5a...b37d45 )
by Christian
26:43
created

AdminTest   F

Complexity

Total Complexity 132

Size/Duplication

Total Lines 2439
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 24

Importance

Changes 0
Metric Value
wmc 132
lcom 1
cbo 24
dl 0
loc 2439
rs 0.8
c 0
b 0
f 0

118 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 6 1
A testConstructor() 0 10 1
A testGetClass() 0 23 1
A testGetClassException() 0 14 1
A testCheckAccessThrowsExceptionOnMadeUpAction() 0 15 1
A testCheckAccessThrowsAccessDeniedException() 0 24 1
A testHasAccessOnMadeUpAction() 0 10 1
A testHasAccess() 0 19 1
A testHasAccessAllowsAccess() 0 19 1
A testHasAccessAllowsAccessEditAction() 0 18 1
A testChildren() 0 22 1
A testConfigure() 0 15 1
A testConfigureWithValidParentAssociationMapping() 0 8 1
B provideGetBaseRoutePattern() 0 65 1
A testGetBaseRoutePattern() 0 5 1
A testGetBaseRoutePatternWithChildAdmin() 0 8 1
A testGetBaseRoutePatternWithTwoNestedChildAdmin() 0 18 1
A testGetBaseRoutePatternWithSpecifedPattern() 0 6 1
A testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern() 0 8 1
A testGetBaseRoutePatternWithUnreconizedClassname() 0 7 1
B provideGetBaseRouteName() 0 65 1
A testGetBaseRouteName() 0 6 1
B testGetBaseRouteNameWithChildAdmin() 0 85 1
A testGetBaseRouteNameWithUnreconizedClassname() 0 7 1
A testGetBaseRouteNameWithSpecifiedName() 0 6 1
A testGetBaseRouteNameWithChildAdminAndWithSpecifiedName() 0 8 1
A testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName() 0 22 1
A testSetUniqid() 0 9 1
A testUniqidConsistency() 0 26 1
A testToString() 0 17 1
A testIsAclEnabled() 0 10 1
B testDefaultFilters() 0 59 1
A testDefaultBreadcrumbsBuilder() 0 24 1
A testBreadcrumbsBuilderSetter() 0 10 1
A testGetBreadcrumbs() 0 10 1
A testBuildBreadcrumbs() 0 17 1
A testCreateQueryLegacyCallWorks() 0 14 1
A testGetDataSourceIterator() 0 42 2
A testCircularChildAdmin() 0 20 1
A testCircularChildAdminTripleLevel() 0 26 1
A testCircularChildAdminWithItself() 0 14 1
A testGetRootAncestor() 0 34 1
A testGetChildDepth() 0 34 1
A testGetCurrentLeafChildAdmin() 0 37 1
A createTagAdmin() 0 39 1
A testGetObjectIdentifier() 0 6 1
A testTrans() 0 15 1
A testTransWithMessageDomain() 0 14 1
A testTransChoice() 0 15 1
A testTransChoiceWithMessageDomain() 0 14 1
A testSetFilterPersister() 0 11 1
A testGetRootCode() 0 17 1
A testGetRoot() 0 17 1
A testGetExportFields() 0 13 1
A testGetPersistentParametersWithNoExtension() 0 6 1
A testGetPersistentParametersWithInvalidExtension() 0 13 1
A testGetPersistentParametersWithValidExtension() 0 15 1
A testGetFormWithNonCollectionParentValue() 0 10 1
A testGetFormWithCollectionParentValue() 0 34 1
B testFormAddPostSubmitEventForPreValidation() 0 60 2
A testRemoveFieldFromFormGroup() 0 26 1
B testSubClass() 0 62 1
A testNonExistantSubclass() 0 16 1
A testOnlyOneSubclassNeededToBeActive() 0 8 1
A testAddSubClassIsDeprecated() 0 9 1
A testGetPerPageOptions() 0 13 2
A testGetLabelTranslatorStrategy() 0 10 1
A testGetRouteBuilder() 0 10 1
A testGetMenuFactory() 0 10 1
A testGetExtensions() 0 13 1
A testGetFilterTheme() 0 9 1
A testGetFormTheme() 0 10 1
A testGetValidator() 0 11 1
A testGetSecurityHandler() 0 10 1
A testGetSecurityInformation() 0 14 1
A testGetManagerType() 0 9 1
A testGetModelManager() 0 11 1
A testGetBaseCodeRoute() 0 9 1
A testGetRouteGenerator() 0 11 1
A testGetConfigurationPool() 0 13 1
A testGetShowBuilder() 0 11 1
A testGetListBuilder() 0 11 1
A testGetDatagridBuilder() 0 11 1
A testGetFormContractor() 0 11 1
A testGetRequest() 0 12 1
A testGetRequestWithException() 0 8 1
A testGetTranslationDomain() 0 9 1
A testGetTranslator() 0 11 1
A testGetShowGroups() 0 11 1
A testGetFormGroups() 0 11 1
A testGetMaxPageLinks() 0 9 1
A testGetMaxPerPage() 0 9 1
A testGetLabel() 0 9 1
A testGetBaseController() 0 9 1
A testGetTemplates() 0 17 1
A testGetTemplate1() 0 13 1
A testGetIdParameter() 0 31 1
A testGetExportFormats() 0 6 1
A testGetUrlsafeIdentifier() 0 15 1
A testDeterminedPerPageValue() 0 12 1
A testIsGranted() 0 26 5
A testSupportsPreviewMode() 0 6 1
A testGetPermissionsShow() 0 8 1
A testShowIn() 0 17 2
A testGetFilterParameters() 0 40 1
B testGetFilterFieldDescription() 0 71 4
A testGetSubjectNoRequest() 0 12 1
A testGetSideMenu() 0 24 1
A provideGetSubject() 0 10 1
A testGetSubjectFailed() 0 15 1
A testGetSubject() 0 18 1
A testGetSubjectWithParentDescription() 0 28 1
A testGetActionButtonsList() 0 33 1
A testGetActionButtonsListCreateDisabled() 0 14 1
A testGetBatchActions() 0 54 2
A testShowMosaicButton() 0 9 1
A testShowMosaicButtonHideMosaic() 0 10 1
A testDefaultDashboardActionsArePresent() 0 31 3

How to fix   Complexity   

Complex Class

Complex classes like AdminTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AdminTest, and based on these observations, apply Extract Interface, too.

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

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

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

Loading history...
1234
    }
1235
1236
    public function testGetTemplate1(): void
1237
    {
1238
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1239
1240
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1241
        $templateRegistry->getTemplate('edit')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/edit.html.twig');
1242
        $templateRegistry->getTemplate('show')->shouldBeCalled()->willReturn('@FooAdmin/CRUD/show.html.twig');
1243
1244
        $admin->setTemplateRegistry($templateRegistry->reveal());
1245
1246
        $this->assertSame('@FooAdmin/CRUD/edit.html.twig', $admin->getTemplate('edit'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::getTemplate() has been deprecated with message: since 3.34, will be dropped in 4.0. Use TemplateRegistry services instead

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

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

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

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

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

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