Completed
Push — master ( 848fca...e5a7d1 )
by Grégoire
11s
created

AdminTest   F

Complexity

Total Complexity 128

Size/Duplication

Total Lines 2250
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 23

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 128
lcom 1
cbo 23
dl 0
loc 2250
rs 0.6197
c 2
b 0
f 0

113 Methods

Rating   Name   Duplication   Size   Complexity  
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 15 1
A testGetTemplate1() 0 12 1
A testGetTemplate2() 0 17 1
B testGetIdParameter() 0 31 1
A testGetExportFormats() 0 6 1
A testGetUrlsafeIdentifier() 0 15 1
A testDeterminedPerPageValue() 0 20 1
B testIsGranted() 0 26 5
A testSupportsPreviewMode() 0 6 1
A testGetPermissionsShow() 0 8 1
A testShowIn() 0 21 3
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 testSetPersistFilters() 0 8 1
A testGetRootCode() 0 17 1
A testGetRoot() 0 17 1
A testGetExportFields() 0 13 1
A testGetPersistentParametersWithNoExtension() 0 6 1
A testGetBaseRouteNameWithSpecifiedName() 0 6 1
A testGetBaseRouteNameWithChildAdminAndWithSpecifiedName() 0 8 1
A testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName() 0 22 1
A testUniqid() 0 9 1
A testToString() 0 17 1
A testIsAclEnabled() 0 10 1
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
B 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 20 1
A testConfigure() 0 15 1
A testConfigureWithValidParentAssociationMapping() 0 8 1
A 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
A provideGetBaseRouteName() 0 65 1
A testGetBaseRouteName() 0 6 1
B testGetBaseRouteNameWithChildAdmin() 0 83 1
A testGetBaseRouteNameWithUnreconizedClassname() 0 7 1
A testSubClass() 0 56 1
A testNonExistantSubclass() 0 15 1
A testOnlyOneSubclassNeededToBeActive() 0 8 1
A testAddSubClassIsDeprecated() 0 9 1
A testGetPerPageOptions() 0 8 1
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 22 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 testGetPersistentParametersWithInvalidExtension() 0 13 1
A testGetPersistentParametersWithValidExtension() 0 15 1
A testGetFormWithNonCollectionParentValue() 0 10 1
B testGetFormWithCollectionParentValue() 0 34 1
B testRemoveFieldFromFormGroup() 0 26 1
B testGetFilterParameters() 0 34 1
B testGetFilterFieldDescription() 0 71 4
A testGetSubjectNoRequest() 0 12 1
B testGetSideMenu() 0 24 1
A provideGetSubject() 0 10 1
A testGetSubjectFailed() 0 15 1
A testGetSubject() 0 18 1
B testGetSubjectWithParentDescription() 0 29 1
B testGetActionButtonsList() 0 30 1
A testGetActionButtonsListCreateDisabled() 0 14 1
A testGetBatchActions() 0 58 3
A testShowMosaicButton() 0 9 1
A testShowMosaicButtonHideMosaic() 0 10 1
B testDefaultDashboardActionsArePresent() 0 30 4
A testDefaultFilters() 0 59 1
A testCreateQueryLegacyCallWorks() 0 14 1
B testGetDataSourceIterator() 0 42 2
A testCircularChildAdmin() 0 20 1
B testCircularChildAdminTripleLevel() 0 26 1
A testCircularChildAdminWithItself() 0 14 1
B testGetRootAncestor() 0 34 1
B testGetChildDepth() 0 34 1
B testGetCurrentLeafChildAdmin() 0 37 1
B createTagAdmin() 0 39 1

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\FieldDescriptionInterface;
25
use Sonata\AdminBundle\Admin\Pool;
26
use Sonata\AdminBundle\Builder\DatagridBuilderInterface;
27
use Sonata\AdminBundle\Builder\FormContractorInterface;
28
use Sonata\AdminBundle\Builder\ListBuilderInterface;
29
use Sonata\AdminBundle\Builder\RouteBuilderInterface;
30
use Sonata\AdminBundle\Builder\ShowBuilderInterface;
31
use Sonata\AdminBundle\Datagrid\DatagridInterface;
32
use Sonata\AdminBundle\Datagrid\PagerInterface;
33
use Sonata\AdminBundle\Model\AuditManagerInterface;
34
use Sonata\AdminBundle\Model\ModelManagerInterface;
35
use Sonata\AdminBundle\Route\DefaultRouteGenerator;
36
use Sonata\AdminBundle\Route\PathInfoBuilder;
37
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
38
use Sonata\AdminBundle\Route\RoutesCache;
39
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
40
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
41
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentAdmin;
42
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentVoteAdmin;
43
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentWithCustomRouteAdmin;
44
use Sonata\AdminBundle\Tests\Fixtures\Admin\FieldDescription;
45
use Sonata\AdminBundle\Tests\Fixtures\Admin\FilteredAdmin;
46
use Sonata\AdminBundle\Tests\Fixtures\Admin\ModelAdmin;
47
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostAdmin;
48
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostWithCustomRouteAdmin;
49
use Sonata\AdminBundle\Tests\Fixtures\Admin\TagAdmin;
50
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\BlogPost;
51
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Comment;
52
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Post;
53
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Tag;
54
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToString;
55
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToStringNull;
56
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
57
use Sonata\CoreBundle\Model\Adapter\AdapterInterface;
58
use Symfony\Component\DependencyInjection\Container;
59
use Symfony\Component\Form\FormBuilderInterface;
60
use Symfony\Component\HttpFoundation\ParameterBag;
61
use Symfony\Component\HttpFoundation\Request;
62
use Symfony\Component\PropertyAccess\PropertyAccess;
63
use Symfony\Component\Routing\RouterInterface;
64
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
65
use Symfony\Component\Translation\TranslatorInterface;
66
use Symfony\Component\Validator\Validator\ValidatorInterface;
67
68
class AdminTest extends TestCase
69
{
70
    protected $cacheTempFolder;
71
72
    public function setUp(): void
73
    {
74
        $this->cacheTempFolder = sys_get_temp_dir().'/sonata_test_route';
75
76
        exec('rm -rf '.$this->cacheTempFolder);
77
    }
78
79
    /**
80
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
81
     */
82
    public function testConstructor(): void
83
    {
84
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
85
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
86
87
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
88
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
89
        $this->assertSame($class, $admin->getClass());
90
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
91
    }
92
93
    public function testGetClass(): void
94
    {
95
        $class = Post::class;
96
        $baseControllerName = 'SonataNewsBundle:PostAdmin';
97
98
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
99
100
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
101
102
        $admin->setSubject(new BlogPost());
103
        $this->assertSame(BlogPost::class, $admin->getClass());
104
105
        $admin->setSubClasses(['foo']);
106
        $this->assertSame(BlogPost::class, $admin->getClass());
107
108
        $admin->setSubject(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

Loading history...
1314
                if ($admin == $adminIn && $attributes == ['LIST']) {
1315
                    return true;
1316
                }
1317
1318
                return false;
1319
            }));
1320
1321
        $admin->setSecurityHandler($securityHandler);
1322
1323
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1324
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1325
        $this->assertTrue($admin->showIn('foo'));
1326
    }
1327
1328
    public function testGetObjectIdentifier(): void
1329
    {
1330
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1331
1332
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1333
    }
1334
1335
    /**
1336
     * @group legacy
1337
     */
1338
    public function testTrans(): void
1339
    {
1340
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1341
        $admin->setTranslationDomain('fooMessageDomain');
1342
1343
        $translator = $this->createMock(TranslatorInterface::class);
1344
        $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...
1345
1346
        $translator->expects($this->once())
1347
            ->method('trans')
1348
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1349
            ->will($this->returnValue('fooTranslated'));
1350
1351
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1352
    }
1353
1354
    /**
1355
     * @group legacy
1356
     */
1357
    public function testTransWithMessageDomain(): void
1358
    {
1359
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1360
1361
        $translator = $this->createMock(TranslatorInterface::class);
1362
        $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...
1363
1364
        $translator->expects($this->once())
1365
            ->method('trans')
1366
            ->with($this->equalTo('foo'), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1367
            ->will($this->returnValue('fooTranslated'));
1368
1369
        $this->assertSame('fooTranslated', $admin->trans('foo', ['name' => 'Andrej'], 'fooMessageDomain'));
1370
    }
1371
1372
    /**
1373
     * @group legacy
1374
     */
1375
    public function testTransChoice(): void
1376
    {
1377
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1378
        $admin->setTranslationDomain('fooMessageDomain');
1379
1380
        $translator = $this->createMock(TranslatorInterface::class);
1381
        $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...
1382
1383
        $translator->expects($this->once())
1384
            ->method('transChoice')
1385
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1386
            ->will($this->returnValue('fooTranslated'));
1387
1388
        $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...
1389
    }
1390
1391
    /**
1392
     * @group legacy
1393
     */
1394
    public function testTransChoiceWithMessageDomain(): void
1395
    {
1396
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1397
1398
        $translator = $this->createMock(TranslatorInterface::class);
1399
        $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...
1400
1401
        $translator->expects($this->once())
1402
            ->method('transChoice')
1403
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1404
            ->will($this->returnValue('fooTranslated'));
1405
1406
        $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...
1407
    }
1408
1409
    public function testSetPersistFilters(): void
1410
    {
1411
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1412
1413
        $this->assertAttributeSame(false, 'persistFilters', $admin);
1414
        $admin->setPersistFilters(true);
1415
        $this->assertAttributeSame(true, 'persistFilters', $admin);
1416
    }
1417
1418
    public function testGetRootCode(): void
1419
    {
1420
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1421
1422
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1423
1424
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1425
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1426
        $parentFieldDescription->expects($this->once())
1427
            ->method('getAdmin')
1428
            ->will($this->returnValue($parentAdmin));
1429
1430
        $this->assertNull($admin->getParentFieldDescription());
1431
        $admin->setParentFieldDescription($parentFieldDescription);
1432
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1433
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1434
    }
1435
1436
    public function testGetRoot(): void
1437
    {
1438
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1439
1440
        $this->assertSame($admin, $admin->getRoot());
1441
1442
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'SonataNewsBundle:PostParentAdmin');
1443
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1444
        $parentFieldDescription->expects($this->once())
1445
            ->method('getAdmin')
1446
            ->will($this->returnValue($parentAdmin));
1447
1448
        $this->assertNull($admin->getParentFieldDescription());
1449
        $admin->setParentFieldDescription($parentFieldDescription);
1450
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1451
        $this->assertSame($parentAdmin, $admin->getRoot());
1452
    }
1453
1454
    public function testGetExportFields(): void
1455
    {
1456
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1457
1458
        $modelManager = $this->createMock(ModelManagerInterface::class);
1459
        $modelManager->expects($this->once())
1460
            ->method('getExportFields')
1461
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1462
            ->will($this->returnValue(['foo', 'bar']));
1463
1464
        $admin->setModelManager($modelManager);
1465
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1466
    }
1467
1468
    public function testGetPersistentParametersWithNoExtension(): void
1469
    {
1470
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1471
1472
        $this->assertEmpty($admin->getPersistentParameters());
1473
    }
1474
1475
    public function testGetPersistentParametersWithInvalidExtension(): void
1476
    {
1477
        $this->expectException(\RuntimeException::class);
1478
1479
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1480
1481
        $extension = $this->createMock(AdminExtensionInterface::class);
1482
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue(null));
1483
1484
        $admin->addExtension($extension);
1485
1486
        $admin->getPersistentParameters();
1487
    }
1488
1489
    public function testGetPersistentParametersWithValidExtension(): void
1490
    {
1491
        $expected = [
1492
            'context' => 'foobar',
1493
        ];
1494
1495
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1496
1497
        $extension = $this->createMock(AdminExtensionInterface::class);
1498
        $extension->expects($this->once())->method('getPersistentParameters')->will($this->returnValue($expected));
1499
1500
        $admin->addExtension($extension);
1501
1502
        $this->assertSame($expected, $admin->getPersistentParameters());
1503
    }
1504
1505
    public function testGetFormWithNonCollectionParentValue(): void
1506
    {
1507
        $post = new Post();
1508
        $tagAdmin = $this->createTagAdmin($post);
1509
        $tag = $tagAdmin->getSubject();
1510
1511
        $tag->setPosts(null);
1512
        $tagAdmin->getForm();
1513
        $this->assertSame($post, $tag->getPosts());
1514
    }
1515
1516
    public function testGetFormWithCollectionParentValue(): void
1517
    {
1518
        $post = new Post();
1519
        $tagAdmin = $this->createTagAdmin($post);
1520
        $tag = $tagAdmin->getSubject();
1521
1522
        // Case of a doctrine collection
1523
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1524
        $this->assertCount(0, $tag->getPosts());
1525
1526
        $tag->addPost(new Post());
1527
1528
        $this->assertCount(1, $tag->getPosts());
1529
1530
        $tagAdmin->getForm();
1531
1532
        $this->assertInstanceOf(Collection::class, $tag->getPosts());
1533
        $this->assertCount(2, $tag->getPosts());
1534
        $this->assertContains($post, $tag->getPosts());
1535
1536
        // Case of an array
1537
        $tag->setPosts([]);
1538
        $this->assertCount(0, $tag->getPosts());
1539
1540
        $tag->addPost(new Post());
1541
1542
        $this->assertCount(1, $tag->getPosts());
1543
1544
        $tagAdmin->getForm();
1545
1546
        $this->assertInternalType('array', $tag->getPosts());
1547
        $this->assertCount(2, $tag->getPosts());
1548
        $this->assertContains($post, $tag->getPosts());
1549
    }
1550
1551
    public function testRemoveFieldFromFormGroup(): void
1552
    {
1553
        $formGroups = [
1554
            'foobar' => [
1555
                'fields' => [
1556
                    'foo' => 'foo',
1557
                    'bar' => 'bar',
1558
                ],
1559
            ],
1560
        ];
1561
1562
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1563
        $admin->setFormGroups($formGroups);
1564
1565
        $admin->removeFieldFromFormGroup('foo');
1566
        $this->assertSame($admin->getFormGroups(), [
1567
            'foobar' => [
1568
                'fields' => [
1569
                    'bar' => 'bar',
1570
                ],
1571
            ],
1572
        ]);
1573
1574
        $admin->removeFieldFromFormGroup('bar');
1575
        $this->assertSame($admin->getFormGroups(), []);
1576
    }
1577
1578
    public function testGetFilterParameters(): void
1579
    {
1580
        $authorId = uniqid();
1581
1582
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1583
1584
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1585
        $commentAdmin->setParentAssociationMapping('post.author');
1586
        $commentAdmin->setParent($postAdmin);
1587
1588
        $request = $this->createMock(Request::class, ['get']);
1589
        $query = $this->createMock(ParameterBag::class, ['get']);
1590
        $query->expects($this->any())
1591
            ->method('get')
1592
            ->will($this->returnValue([]));
1593
        $request->query = $query;
1594
        $request->expects($this->any())
1595
            ->method('get')
1596
            ->will($this->returnValue($authorId));
1597
1598
        $commentAdmin->setRequest($request);
1599
1600
        $modelManager = $this->createMock(ModelManagerInterface::class);
1601
        $modelManager->expects($this->any())
1602
            ->method('getDefaultSortValues')
1603
            ->will($this->returnValue([]));
1604
1605
        $commentAdmin->setModelManager($modelManager);
1606
1607
        $parameters = $commentAdmin->getFilterParameters();
1608
1609
        $this->assertTrue(isset($parameters['post__author']));
1610
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1611
    }
1612
1613
    public function testGetFilterFieldDescription(): void
1614
    {
1615
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1616
1617
        $fooFieldDescription = new FieldDescription();
1618
        $barFieldDescription = new FieldDescription();
1619
        $bazFieldDescription = new FieldDescription();
1620
1621
        $modelManager = $this->createMock(ModelManagerInterface::class);
1622
        $modelManager->expects($this->exactly(3))
1623
            ->method('getNewFieldDescriptionInstance')
1624
            ->will($this->returnCallback(function ($adminClass, $name, $filterOptions) use ($fooFieldDescription, $barFieldDescription, $bazFieldDescription) {
0 ignored issues
show
Unused Code introduced by
The parameter $filterOptions is not used and could be removed.

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

Loading history...
1625
                switch ($name) {
1626
                    case 'foo':
1627
                        $fieldDescription = $fooFieldDescription;
1628
1629
                        break;
1630
1631
                    case 'bar':
1632
                        $fieldDescription = $barFieldDescription;
1633
1634
                        break;
1635
1636
                    case 'baz':
1637
                        $fieldDescription = $bazFieldDescription;
1638
1639
                        break;
1640
1641
                    default:
1642
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1643
                        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...
1644
                }
1645
1646
                $fieldDescription->setName($name);
1647
1648
                return $fieldDescription;
1649
            }));
1650
1651
        $modelAdmin->setModelManager($modelManager);
1652
1653
        $pager = $this->createMock(PagerInterface::class);
1654
1655
        $datagrid = $this->createMock(DatagridInterface::class);
1656
        $datagrid->expects($this->once())
1657
            ->method('getPager')
1658
            ->will($this->returnValue($pager));
1659
1660
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1661
        $datagridBuilder->expects($this->once())
1662
            ->method('getBaseDatagrid')
1663
            ->with($this->identicalTo($modelAdmin), [])
1664
            ->will($this->returnValue($datagrid));
1665
1666
        $datagridBuilder->expects($this->exactly(3))
1667
            ->method('addFilter')
1668
            ->will($this->returnCallback(function ($datagrid, $type, $fieldDescription, AdminInterface $admin): void {
1669
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1670
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1671
            }));
1672
1673
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1674
1675
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1676
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1677
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1678
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1679
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1680
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1681
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1682
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1683
    }
1684
1685
    public function testGetSubjectNoRequest(): void
1686
    {
1687
        $modelManager = $this->createMock(ModelManagerInterface::class);
1688
        $modelManager
1689
            ->expects($this->never())
1690
            ->method('find');
1691
1692
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1693
        $admin->setModelManager($modelManager);
1694
1695
        $this->assertNull($admin->getSubject());
1696
    }
1697
1698
    public function testGetSideMenu(): void
1699
    {
1700
        $item = $this->createMock(ItemInterface::class);
1701
        $item
1702
            ->expects($this->once())
1703
            ->method('setChildrenAttribute')
1704
            ->with('class', 'nav navbar-nav');
1705
        $item
1706
            ->expects($this->once())
1707
            ->method('setExtra')
1708
            ->with('translation_domain', 'foo_bar_baz');
1709
1710
        $menuFactory = $this->createMock(FactoryInterface::class);
1711
        $menuFactory
1712
            ->expects($this->once())
1713
            ->method('createItem')
1714
            ->will($this->returnValue($item));
1715
1716
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1717
        $modelAdmin->setMenuFactory($menuFactory);
1718
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1719
1720
        $modelAdmin->getSideMenu('foo');
1721
    }
1722
1723
    /**
1724
     * @return array
1725
     */
1726
    public function provideGetSubject()
1727
    {
1728
        return [
1729
            [23],
1730
            ['azerty'],
1731
            ['4f69bbb5f14a13347f000092'],
1732
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1733
            ['123'.AdapterInterface::ID_SEPARATOR.'my_type'], // composite keys are supported
1734
        ];
1735
    }
1736
1737
    /**
1738
     * @dataProvider provideGetSubject
1739
     */
1740
    public function testGetSubjectFailed($id): void
1741
    {
1742
        $modelManager = $this->createMock(ModelManagerInterface::class);
1743
        $modelManager
1744
            ->expects($this->once())
1745
            ->method('find')
1746
            ->with('NewsBundle\Entity\Post', $id)
1747
            ->will($this->returnValue(null)); // entity not found
1748
1749
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1750
        $admin->setModelManager($modelManager);
1751
1752
        $admin->setRequest(new Request(['id' => $id]));
1753
        $this->assertNull($admin->getSubject());
1754
    }
1755
1756
    /**
1757
     * @dataProvider provideGetSubject
1758
     */
1759
    public function testGetSubject($id): void
1760
    {
1761
        $entity = new Post();
1762
1763
        $modelManager = $this->createMock(ModelManagerInterface::class);
1764
        $modelManager
1765
            ->expects($this->once())
1766
            ->method('find')
1767
            ->with('NewsBundle\Entity\Post', $id)
1768
            ->will($this->returnValue($entity));
1769
1770
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1771
        $admin->setModelManager($modelManager);
1772
1773
        $admin->setRequest(new Request(['id' => $id]));
1774
        $this->assertSame($entity, $admin->getSubject());
1775
        $this->assertSame($entity, $admin->getSubject()); // model manager must be used only once
1776
    }
1777
1778
    public function testGetSubjectWithParentDescription(): void
1779
    {
1780
        $adminId = 1;
1781
1782
        $comment = new Comment();
1783
1784
        $modelManager = $this->createMock(ModelManagerInterface::class);
1785
        $modelManager
1786
            ->expects($this->any())
1787
            ->method('find')
1788
            ->with('NewsBundle\Entity\Comment', $adminId)
1789
            ->will($this->returnValue($comment));
1790
1791
        $request = new Request(['id' => $adminId]);
1792
1793
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1794
        $postAdmin->setRequest($request);
1795
1796
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'SonataNewsBundle:CommentAdmin');
1797
        $commentAdmin->setRequest($request);
1798
        $commentAdmin->setModelManager($modelManager);
1799
1800
        $this->assertEquals($comment, $commentAdmin->getSubject());
1801
1802
        $commentAdmin->setSubject(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1803
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1804
1805
        $this->assertNull($commentAdmin->getSubject());
1806
    }
1807
1808
    /**
1809
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1810
     */
1811
    public function testGetActionButtonsList(): void
1812
    {
1813
        $expected = [
1814
            'create' => [
1815
                'template' => 'Foo.html.twig',
1816
            ],
1817
        ];
1818
1819
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1820
1821
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1822
        $securityHandler
1823
            ->expects($this->once())
1824
            ->method('isGranted')
1825
            ->with($admin, 'CREATE', $admin)
1826
            ->will($this->returnValue(true));
1827
        $admin->setSecurityHandler($securityHandler);
1828
1829
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1830
        $routeGenerator
1831
            ->expects($this->once())
1832
            ->method('hasAdminRoute')
1833
            ->with($admin, 'create')
1834
            ->will($this->returnValue(true));
1835
        $admin->setRouteGenerator($routeGenerator);
1836
1837
        $admin->setTemplate('button_create', 'Foo.html.twig');
1838
1839
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1840
    }
1841
1842
    /**
1843
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1844
     */
1845
    public function testGetActionButtonsListCreateDisabled(): void
1846
    {
1847
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1848
1849
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1850
        $securityHandler
1851
            ->expects($this->once())
1852
            ->method('isGranted')
1853
            ->with($admin, 'CREATE', $admin)
1854
            ->will($this->returnValue(false));
1855
        $admin->setSecurityHandler($securityHandler);
1856
1857
        $this->assertSame([], $admin->getActionButtons('list', null));
1858
    }
1859
1860
    /**
1861
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1862
     */
1863
    public function testGetBatchActions(): void
1864
    {
1865
        $expected = [
1866
            'delete' => [
1867
                'label' => 'action_delete',
1868
                'translation_domain' => 'SonataAdminBundle',
1869
                'ask_confirmation' => true, // by default always true
1870
            ],
1871
            'foo' => [
1872
                'label' => 'action_foo',
1873
                'translation_domain' => 'SonataAdminBundle',
1874
            ],
1875
            'bar' => [
1876
                'label' => 'batch.label_bar',
1877
                'translation_domain' => 'SonataAdminBundle',
1878
            ],
1879
            'baz' => [
1880
                'label' => 'action_baz',
1881
                'translation_domain' => 'AcmeAdminBundle',
1882
            ],
1883
        ];
1884
1885
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1886
1887
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1888
        $labelTranslatorStrategy->expects($this->any())
1889
            ->method('getLabel')
1890
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
1891
                return $context.'.'.$type.'_'.$label;
1892
            }));
1893
1894
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1895
        $admin->setRouteBuilder($pathInfo);
1896
        $admin->setTranslationDomain('SonataAdminBundle');
1897
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1898
1899
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1900
        $routeGenerator
1901
            ->expects($this->once())
1902
            ->method('hasAdminRoute')
1903
            ->with($admin, 'delete')
1904
            ->will($this->returnValue(true));
1905
        $admin->setRouteGenerator($routeGenerator);
1906
1907
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1908
        $securityHandler->expects($this->any())
1909
            ->method('isGranted')
1910
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin) {
0 ignored issues
show
Unused Code introduced by
The parameter $object is not used and could be removed.

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

Loading history...
1911
                if ($admin == $adminIn && 'DELETE' == $attributes) {
1912
                    return true;
1913
                }
1914
1915
                return false;
1916
            }));
1917
        $admin->setSecurityHandler($securityHandler);
1918
1919
        $this->assertSame($expected, $admin->getBatchActions());
1920
    }
1921
1922
    /**
1923
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1924
     */
1925
    public function testShowMosaicButton(): void
1926
    {
1927
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1928
        $listModes = $admin->getListModes();
1929
1930
        $admin->showMosaicButton(true);
1931
1932
        $this->assertSame($listModes, $admin->getListModes());
1933
    }
1934
1935
    /**
1936
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1937
     */
1938
    public function testShowMosaicButtonHideMosaic(): void
1939
    {
1940
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle:PostAdmin');
1941
        $listModes = $admin->getListModes();
1942
        $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...
1943
1944
        $admin->showMosaicButton(false);
1945
1946
        $this->assertSame($expected, $admin->getListModes());
1947
    }
1948
1949
    /**
1950
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
1951
     * @dataProvider provideGetBaseRouteName
1952
     */
1953
    public function testDefaultDashboardActionsArePresent($objFqn, $expected): void
1954
    {
1955
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1956
1957
        $routeGenerator = new DefaultRouteGenerator(
1958
            $this->createMock(RouterInterface::class),
1959
            new RoutesCache($this->cacheTempFolder, true)
1960
        );
1961
1962
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'SonataNewsBundle:PostAdmin');
1963
        $admin->setRouteBuilder($pathInfo);
1964
        $admin->setRouteGenerator($routeGenerator);
1965
        $admin->initialize();
1966
1967
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1968
        $securityHandler->expects($this->any())
1969
            ->method('isGranted')
1970
            ->will($this->returnCallback(function (AdminInterface $adminIn, $attributes, $object = null) use ($admin) {
0 ignored issues
show
Unused Code introduced by
The parameter $object is not used and could be removed.

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

Loading history...
1971
                if ($admin == $adminIn && ('CREATE' == $attributes || 'LIST' == $attributes)) {
1972
                    return true;
1973
                }
1974
1975
                return false;
1976
            }));
1977
1978
        $admin->setSecurityHandler($securityHandler);
1979
1980
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
1981
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
1982
    }
1983
1984
    public function testDefaultFilters(): void
1985
    {
1986
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
1987
1988
        $subjectId = uniqid();
1989
1990
        $request = $this->createMock(Request::class, ['get']);
1991
        $query = $this->createMock(ParameterBag::class, ['set', 'get']);
1992
        $query->expects($this->any())
1993
            ->method('get')
1994
            ->with($this->equalTo('filter'))
1995
            ->will($this->returnValue([
1996
                'a' => [
1997
                    'value' => 'b',
1998
                ],
1999
                'foo' => [
2000
                    'type' => '1',
2001
                    'value' => 'bar',
2002
                ],
2003
                'baz' => [
2004
                    'type' => '5',
2005
                    'value' => 'test',
2006
                ],
2007
            ]));
2008
        $request->query = $query;
2009
2010
        $request->expects($this->any())
2011
            ->method('get')
2012
            ->will($this->returnValue($subjectId));
2013
2014
        $admin->setRequest($request);
2015
2016
        $modelManager = $this->createMock(ModelManagerInterface::class);
2017
        $modelManager->expects($this->any())
2018
            ->method('getDefaultSortValues')
2019
            ->will($this->returnValue([]));
2020
2021
        $admin->setModelManager($modelManager);
2022
2023
        $this->assertEquals([
2024
            'foo' => [
2025
                'type' => '1',
2026
                'value' => 'bar',
2027
            ],
2028
            'baz' => [
2029
                'type' => '5',
2030
                'value' => 'test',
2031
            ],
2032
            '_page' => 1,
2033
            '_per_page' => 32,
2034
            'a' => [
2035
                'value' => 'b',
2036
            ],
2037
        ], $admin->getFilterParameters());
2038
2039
        $this->assertTrue($admin->isDefaultFilter('foo'));
2040
        $this->assertFalse($admin->isDefaultFilter('bar'));
2041
        $this->assertFalse($admin->isDefaultFilter('a'));
2042
    }
2043
2044
    /**
2045
     * NEXT_MAJOR: remove this method.
2046
     *
2047
     * @group legacy
2048
     */
2049
    public function testCreateQueryLegacyCallWorks(): void
2050
    {
2051
        $admin = $this->getMockForAbstractClass(AbstractAdmin::class, [
2052
            'admin.my_code', 'My\Class', 'MyBundle:ClassAdmin',
2053
        ]);
2054
        $modelManager = $this->createMock(ModelManagerInterface::class);
2055
        $modelManager->expects($this->once())
2056
            ->method('createQuery')
2057
            ->with('My\Class')
2058
            ->willReturn('a query');
2059
2060
        $admin->setModelManager($modelManager);
2061
        $this->assertSame('a query', $admin->createQuery('list'));
2062
    }
2063
2064
    public function testGetDataSourceIterator(): void
2065
    {
2066
        $datagrid = $this->createMock(DatagridInterface::class);
2067
        $datagrid->method('buildPager');
2068
2069
        $modelManager = $this->createMock(ModelManagerInterface::class);
2070
        $modelManager->method('getExportFields')->will($this->returnValue([
2071
            'field',
2072
            'foo',
2073
            'bar',
2074
        ]));
2075
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2076
            ->with($this->equalTo($datagrid), $this->equalTo([
2077
                'Feld' => 'field',
2078
                1 => 'foo',
2079
                2 => 'bar',
2080
            ]));
2081
2082
        $admin = $this->getMockBuilder(AbstractAdmin::class)
2083
            ->disableOriginalConstructor()
2084
            ->setMethods(['getDatagrid', 'getTranslationLabel', 'trans'])
2085
            ->getMockForAbstractClass();
2086
        $admin->method('getDatagrid')->will($this->returnValue($datagrid));
2087
        $admin->setModelManager($modelManager);
2088
2089
        $admin->expects($this->any())
2090
            ->method('getTranslationLabel')
2091
            ->will($this->returnCallback(function ($label, $context = '', $type = '') {
2092
                return $context.'.'.$type.'_'.$label;
2093
            }));
2094
        $admin->expects($this->any())
2095
            ->method('trans')
2096
            ->will($this->returnCallback(function ($label) {
2097
                if ('export.label_field' == $label) {
2098
                    return 'Feld';
2099
                }
2100
2101
                return $label;
2102
            }));
2103
2104
        $admin->getDataSourceIterator();
2105
    }
2106
2107
    public function testCircularChildAdmin(): void
2108
    {
2109
        $this->expectException(
2110
            \RuntimeException::class,
2111
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2112
        );
2113
2114
        $postAdmin = new PostAdmin(
2115
            'sonata.post.admin.post',
2116
            'Application\Sonata\NewsBundle\Entity\Post',
2117
            'SonataNewsBundle:PostAdmin'
2118
        );
2119
        $commentAdmin = new CommentAdmin(
2120
            'sonata.post.admin.comment',
2121
            'Application\Sonata\NewsBundle\Entity\Comment',
2122
            'SonataNewsBundle:CommentAdmin'
2123
        );
2124
        $postAdmin->addChild($commentAdmin);
2125
        $commentAdmin->addChild($postAdmin);
2126
    }
2127
2128
    public function testCircularChildAdminTripleLevel(): void
2129
    {
2130
        $this->expectException(
2131
            \RuntimeException::class,
2132
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2133
        );
2134
2135
        $postAdmin = new PostAdmin(
2136
            'sonata.post.admin.post',
2137
            'Application\Sonata\NewsBundle\Entity\Post',
2138
            'SonataNewsBundle:PostAdmin'
2139
        );
2140
        $commentAdmin = new CommentAdmin(
2141
            'sonata.post.admin.comment',
2142
            'Application\Sonata\NewsBundle\Entity\Comment',
2143
            'SonataNewsBundle:CommentAdmin'
2144
        );
2145
        $commentVoteAdmin = new CommentVoteAdmin(
2146
            'sonata.post.admin.comment_vote',
2147
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2148
            'SonataNewsBundle:CommentVoteAdmin'
2149
        );
2150
        $postAdmin->addChild($commentAdmin);
2151
        $commentAdmin->addChild($commentVoteAdmin);
2152
        $commentVoteAdmin->addChild($postAdmin);
2153
    }
2154
2155
    public function testCircularChildAdminWithItself(): void
2156
    {
2157
        $this->expectException(
2158
            \RuntimeException::class,
2159
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2160
        );
2161
2162
        $postAdmin = new PostAdmin(
2163
            'sonata.post.admin.post',
2164
            'Application\Sonata\NewsBundle\Entity\Post',
2165
            'SonataNewsBundle:PostAdmin'
2166
        );
2167
        $postAdmin->addChild($postAdmin);
2168
    }
2169
2170
    public function testGetRootAncestor(): void
2171
    {
2172
        $postAdmin = new PostAdmin(
2173
            'sonata.post.admin.post',
2174
            'Application\Sonata\NewsBundle\Entity\Post',
2175
            'SonataNewsBundle:PostAdmin'
2176
        );
2177
        $commentAdmin = new CommentAdmin(
2178
            'sonata.post.admin.comment',
2179
            'Application\Sonata\NewsBundle\Entity\Comment',
2180
            'SonataNewsBundle:CommentAdmin'
2181
        );
2182
        $commentVoteAdmin = new CommentVoteAdmin(
2183
            'sonata.post.admin.comment_vote',
2184
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2185
            'SonataNewsBundle:CommentVoteAdmin'
2186
        );
2187
2188
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2189
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2190
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2191
2192
        $postAdmin->addChild($commentAdmin);
2193
2194
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2195
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2196
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2197
2198
        $commentAdmin->addChild($commentVoteAdmin);
2199
2200
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2201
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2202
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2203
    }
2204
2205
    public function testGetChildDepth(): void
2206
    {
2207
        $postAdmin = new PostAdmin(
2208
            'sonata.post.admin.post',
2209
            'Application\Sonata\NewsBundle\Entity\Post',
2210
            'SonataNewsBundle:PostAdmin'
2211
        );
2212
        $commentAdmin = new CommentAdmin(
2213
            'sonata.post.admin.comment',
2214
            'Application\Sonata\NewsBundle\Entity\Comment',
2215
            'SonataNewsBundle:CommentAdmin'
2216
        );
2217
        $commentVoteAdmin = new CommentVoteAdmin(
2218
            'sonata.post.admin.comment_vote',
2219
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2220
            'SonataNewsBundle:CommentVoteAdmin'
2221
        );
2222
2223
        $this->assertSame(0, $postAdmin->getChildDepth());
2224
        $this->assertSame(0, $commentAdmin->getChildDepth());
2225
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2226
2227
        $postAdmin->addChild($commentAdmin);
2228
2229
        $this->assertSame(0, $postAdmin->getChildDepth());
2230
        $this->assertSame(1, $commentAdmin->getChildDepth());
2231
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2232
2233
        $commentAdmin->addChild($commentVoteAdmin);
2234
2235
        $this->assertSame(0, $postAdmin->getChildDepth());
2236
        $this->assertSame(1, $commentAdmin->getChildDepth());
2237
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2238
    }
2239
2240
    public function testGetCurrentLeafChildAdmin(): void
2241
    {
2242
        $postAdmin = new PostAdmin(
2243
            'sonata.post.admin.post',
2244
            'Application\Sonata\NewsBundle\Entity\Post',
2245
            'SonataNewsBundle:PostAdmin'
2246
        );
2247
        $commentAdmin = new CommentAdmin(
2248
            'sonata.post.admin.comment',
2249
            'Application\Sonata\NewsBundle\Entity\Comment',
2250
            'SonataNewsBundle:CommentAdmin'
2251
        );
2252
        $commentVoteAdmin = new CommentVoteAdmin(
2253
            'sonata.post.admin.comment_vote',
2254
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2255
            'SonataNewsBundle:CommentVoteAdmin'
2256
        );
2257
2258
        $postAdmin->addChild($commentAdmin);
2259
        $commentAdmin->addChild($commentVoteAdmin);
2260
2261
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2262
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2263
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2264
2265
        $commentAdmin->setCurrentChild(true);
2266
2267
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2268
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2269
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2270
2271
        $commentVoteAdmin->setCurrentChild(true);
2272
2273
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2274
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2275
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2276
    }
2277
2278
    private function createTagAdmin(Post $post)
2279
    {
2280
        $postAdmin = $this->getMockBuilder(PostAdmin::class)
2281
            ->disableOriginalConstructor()
2282
            ->getMock();
2283
2284
        $postAdmin->expects($this->any())->method('getObject')->will($this->returnValue($post));
2285
2286
        $formBuilder = $this->createMock(FormBuilderInterface::class);
2287
        $formBuilder->expects($this->any())->method('getForm')->will($this->returnValue(null));
2288
2289
        $tagAdmin = $this->getMockBuilder(TagAdmin::class)
2290
            ->setConstructorArgs([
2291
                'admin.tag',
2292
                Tag::class,
2293
                'MyBundle:MyController',
2294
            ])
2295
            ->setMethods(['getFormBuilder'])
2296
            ->getMock();
2297
2298
        $tagAdmin->expects($this->any())->method('getFormBuilder')->will($this->returnValue($formBuilder));
2299
        $tagAdmin->setParent($postAdmin);
2300
2301
        $tag = new Tag();
2302
        $tagAdmin->setSubject($tag);
2303
2304
        $request = $this->createMock(Request::class);
2305
        $tagAdmin->setRequest($request);
2306
2307
        $configurationPool = $this->getMockBuilder(Pool::class)
2308
            ->disableOriginalConstructor()
2309
            ->getMock();
2310
2311
        $configurationPool->expects($this->any())->method('getPropertyAccessor')->will($this->returnValue(PropertyAccess::createPropertyAccessor()));
2312
2313
        $tagAdmin->setConfigurationPool($configurationPool);
2314
2315
        return $tagAdmin;
2316
    }
2317
}
2318