Completed
Pull Request — master (#6210)
by Jordi Sala
02:56
created

AdminTest   F

Complexity

Total Complexity 115

Size/Duplication

Total Lines 2162
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 34

Importance

Changes 0
Metric Value
wmc 115
lcom 1
cbo 34
dl 0
loc 2162
rs 0.8
c 0
b 0
f 0

102 Methods

Rating   Name   Duplication   Size   Complexity  
B testGetFilterFieldDescription() 0 71 4
A setUp() 0 6 1
A testConstructor() 0 10 1
A testGetClass() 0 23 1
A testGetClassException() 0 14 1
A testCheckAccessThrowsExceptionOnMadeUpAction() 0 15 1
A testCheckAccessThrowsAccessDeniedException() 0 24 1
A testHasAccessOnMadeUpAction() 0 10 1
A testHasAccess() 0 19 1
A testHasAccessAllowsAccess() 0 19 1
A testHasAccessAllowsAccessEditAction() 0 18 1
A testChildren() 0 22 1
A testConfigure() 0 15 1
A testConfigureWithValidParentAssociationMapping() 0 8 1
B provideGetBaseRoutePattern() 0 65 1
A testGetBaseRoutePattern() 0 5 1
A testGetBaseRoutePatternWithChildAdmin() 0 8 1
A testGetBaseRoutePatternWithTwoNestedChildAdmin() 0 18 1
A testGetBaseRoutePatternWithSpecifedPattern() 0 6 1
A testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern() 0 8 1
A testGetBaseRoutePatternWithUnreconizedClassname() 0 7 1
B provideGetBaseRouteName() 0 65 1
A testGetBaseRouteName() 0 6 1
A testGetBaseRouteNameWithUnreconizedClassname() 0 7 1
A testGetBaseRouteNameWithSpecifiedName() 0 6 1
A testGetBaseRouteNameWithChildAdminAndWithSpecifiedName() 0 8 1
A testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName() 0 22 1
A testSetUniqid() 0 9 1
A testToString() 0 17 1
A testIsAclEnabled() 0 10 1
B testSubClass() 0 56 1
A testNonExistantSubclass() 0 15 1
A testOnlyOneSubclassNeededToBeActive() 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 testGetTranslationDomain() 0 9 1
A testGetShowGroups() 0 11 1
A testGetFormGroups() 0 11 1
A testGetMaxPageLinks() 0 9 1
A testGetLabel() 0 9 1
A testGetBaseController() 0 9 1
A testGetIdParameter() 0 31 1
A testGetExportFormats() 0 6 1
A testGetUrlsafeIdentifier() 0 15 1
A testDeterminedPerPageValue() 0 10 1
B testIsGranted() 0 54 5
A testSupportsPreviewMode() 0 6 1
A testGetPermissionsShow() 0 8 1
A testShowIn() 0 17 2
A testGetObjectIdentifier() 0 6 1
A testSetFilterPersister() 0 8 1
A testGetRootCode() 0 17 1
A testGetRoot() 0 17 1
A testGetExportFields() 0 13 1
A testGetPersistentParametersWithNoExtension() 0 6 1
A testGetPersistentParametersWithValidExtension() 0 15 1
A testGetNewInstanceForChildAdminWithParentValue() 0 34 1
A testGetNewInstanceForChildAdminWithCollectionParentValue() 0 36 1
A testGetNewInstanceForEmbededAdminWithParentValue() 0 39 1
B testFormAddPostSubmitEventForPreValidation() 0 62 2
A testCanAddInlineValidationOnlyForGenericMetadata() 0 49 1
A testRemoveFieldFromFormGroup() 0 26 1
A testGetFilterParameters() 0 40 1
A testGetSubjectNoRequest() 0 12 1
A testGetSideMenu() 0 24 1
A provideGetSubject() 0 10 1
A testGetSubjectFailed() 0 15 1
A testGetSubject() 0 19 1
A testGetSubjectWithParentDescription() 0 29 1
A testGetActionButtonsList() 0 33 1
A testGetActionButtonsListCreateDisabled() 0 14 1
A testGetBatchActions() 0 54 2
A testShowMosaicButton() 0 9 1
A testShowMosaicButtonHideMosaic() 0 10 1
A testDefaultDashboardActionsArePresent() 0 34 3
B testDefaultFilters() 0 59 1
A testGetDataSourceIterator() 0 44 2
A testCircularChildAdmin() 0 20 1
A testCircularChildAdminTripleLevel() 0 26 1
A testCircularChildAdminWithItself() 0 14 1
A testGetRootAncestor() 0 34 1
A testGetChildDepth() 0 34 1
A testGetCurrentLeafChildAdmin() 0 37 1
A testAdminAvoidInifiniteLoop() 0 31 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\Filter\Persister\FilterPersisterInterface;
34
use Sonata\AdminBundle\Model\AuditManagerInterface;
35
use Sonata\AdminBundle\Model\ModelManagerInterface;
36
use Sonata\AdminBundle\Route\DefaultRouteGenerator;
37
use Sonata\AdminBundle\Route\PathInfoBuilder;
38
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
39
use Sonata\AdminBundle\Route\RoutesCache;
40
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
41
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
42
use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface;
43
use Sonata\AdminBundle\Tests\App\Builder\DatagridBuilder;
44
use Sonata\AdminBundle\Tests\App\Builder\FormContractor;
45
use Sonata\AdminBundle\Tests\App\Builder\ListBuilder;
46
use Sonata\AdminBundle\Tests\App\Builder\ShowBuilder;
47
use Sonata\AdminBundle\Tests\Fixtures\Admin\AvoidInfiniteLoopAdmin;
48
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentAdmin;
49
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentVoteAdmin;
50
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentWithCustomRouteAdmin;
51
use Sonata\AdminBundle\Tests\Fixtures\Admin\FieldDescription;
52
use Sonata\AdminBundle\Tests\Fixtures\Admin\FilteredAdmin;
53
use Sonata\AdminBundle\Tests\Fixtures\Admin\ModelAdmin;
54
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostAdmin;
55
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostCategoryAdmin;
56
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostWithCustomRouteAdmin;
57
use Sonata\AdminBundle\Tests\Fixtures\Admin\TagAdmin;
58
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\BlogPost;
59
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Comment;
60
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Post;
61
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\PostCategory;
62
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Tag;
63
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToString;
64
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToStringNull;
65
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
66
use Sonata\Doctrine\Adapter\AdapterInterface;
67
use Sonata\Exporter\Source\ArraySourceIterator;
68
use Symfony\Component\Filesystem\Filesystem;
69
use Symfony\Component\Form\FormBuilder;
70
use Symfony\Component\Form\FormBuilderInterface;
71
use Symfony\Component\Form\FormEvent;
72
use Symfony\Component\Form\FormEvents;
73
use Symfony\Component\Form\FormFactory;
74
use Symfony\Component\Form\FormRegistry;
75
use Symfony\Component\Form\ResolvedFormTypeFactory;
76
use Symfony\Component\HttpFoundation\ParameterBag;
77
use Symfony\Component\HttpFoundation\Request;
78
use Symfony\Component\PropertyAccess\PropertyAccess;
79
use Symfony\Component\Routing\RouterInterface;
80
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
81
use Symfony\Component\Validator\Mapping\MemberMetadata;
82
use Symfony\Component\Validator\Mapping\PropertyMetadataInterface;
83
use Symfony\Component\Validator\Validator\ValidatorInterface;
84
85
class AdminTest extends TestCase
86
{
87
    protected $cacheTempFolder;
88
89
    protected function setUp(): void
90
    {
91
        $this->cacheTempFolder = sprintf('%s/sonata_test_route', sys_get_temp_dir());
92
        $filesystem = new Filesystem();
93
        $filesystem->remove($this->cacheTempFolder);
94
    }
95
96
    /**
97
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
98
     */
99
    public function testConstructor(): void
100
    {
101
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
102
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
103
104
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
105
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
106
        $this->assertSame($class, $admin->getClass());
107
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
108
    }
109
110
    public function testGetClass(): void
111
    {
112
        $class = Post::class;
113
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
114
115
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
116
117
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
118
119
        $admin->setSubject(new BlogPost());
120
        $this->assertSame(BlogPost::class, $admin->getClass());
121
122
        $admin->setSubClasses(['foo']);
123
        $this->assertSame(BlogPost::class, $admin->getClass());
124
125
        $admin->setSubject(null);
126
        $admin->setSubClasses([]);
127
        $this->assertSame($class, $admin->getClass());
128
129
        $admin->setSubClasses(['foo' => 'bar']);
130
        $admin->setRequest(new Request(['subclass' => 'foo']));
131
        $this->assertSame('bar', $admin->getClass());
132
    }
133
134
    public function testGetClassException(): void
135
    {
136
        $this->expectException(\RuntimeException::class);
137
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
138
139
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
140
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
141
142
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
143
        $admin->setParentFieldDescription(new FieldDescription());
144
        $admin->setSubClasses(['foo' => 'bar']);
145
        $admin->setRequest(new Request(['subclass' => 'foo']));
146
        $admin->getClass();
147
    }
148
149
    public function testCheckAccessThrowsExceptionOnMadeUpAction(): void
150
    {
151
        $admin = new PostAdmin(
152
            'sonata.post.admin.post',
153
            'Application\Sonata\NewsBundle\Entity\Post',
154
            'Sonata\NewsBundle\Controller\PostAdminController'
155
        );
156
        $this->expectException(
157
            \InvalidArgumentException::class
158
        );
159
        $this->expectExceptionMessage(
160
            'Action "made-up" could not be found'
161
        );
162
        $admin->checkAccess('made-up');
163
    }
164
165
    public function testCheckAccessThrowsAccessDeniedException(): void
166
    {
167
        $admin = new PostAdmin(
168
            'sonata.post.admin.post',
169
            'Application\Sonata\NewsBundle\Entity\Post',
170
            'Sonata\NewsBundle\Controller\PostAdminController'
171
        );
172
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
173
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
174
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
175
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
176
        $customExtension->getAccessMapping($admin)->willReturn(
177
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
178
        );
179
        $admin->addExtension($customExtension->reveal());
180
        $admin->setSecurityHandler($securityHandler->reveal());
181
        $this->expectException(
182
            AccessDeniedException::class
183
        );
184
        $this->expectExceptionMessage(
185
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
186
        );
187
        $admin->checkAccess('custom_action');
188
    }
189
190
    public function testHasAccessOnMadeUpAction(): void
191
    {
192
        $admin = new PostAdmin(
193
            'sonata.post.admin.post',
194
            'Application\Sonata\NewsBundle\Entity\Post',
195
            'Sonata\NewsBundle\Controller\PostAdminController'
196
        );
197
198
        $this->assertFalse($admin->hasAccess('made-up'));
199
    }
200
201
    public function testHasAccess(): void
202
    {
203
        $admin = new PostAdmin(
204
            'sonata.post.admin.post',
205
            'Application\Sonata\NewsBundle\Entity\Post',
206
            'Sonata\NewsBundle\Controller\PostAdminController'
207
        );
208
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
209
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
210
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
211
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
212
        $customExtension->getAccessMapping($admin)->willReturn(
213
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
214
        );
215
        $admin->addExtension($customExtension->reveal());
216
        $admin->setSecurityHandler($securityHandler->reveal());
217
218
        $this->assertFalse($admin->hasAccess('custom_action'));
219
    }
220
221
    public function testHasAccessAllowsAccess(): void
222
    {
223
        $admin = new PostAdmin(
224
            'sonata.post.admin.post',
225
            'Application\Sonata\NewsBundle\Entity\Post',
226
            'Sonata\NewsBundle\Controller\PostAdminController'
227
        );
228
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
229
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
230
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
231
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
232
        $customExtension->getAccessMapping($admin)->willReturn(
233
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
234
        );
235
        $admin->addExtension($customExtension->reveal());
236
        $admin->setSecurityHandler($securityHandler->reveal());
237
238
        $this->assertTrue($admin->hasAccess('custom_action'));
239
    }
240
241
    public function testHasAccessAllowsAccessEditAction(): void
242
    {
243
        $admin = new PostAdmin(
244
            'sonata.post.admin.post',
245
            'Application\Sonata\NewsBundle\Entity\Post',
246
            'Sonata\NewsBundle\Controller\PostAdminController'
247
        );
248
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
249
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
250
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
251
        $customExtension->getAccessMapping($admin)->willReturn(
252
            ['edit_action' => ['EDIT_ROLE']]
253
        );
254
        $admin->addExtension($customExtension->reveal());
255
        $admin->setSecurityHandler($securityHandler->reveal());
256
257
        $this->assertTrue($admin->hasAccess('edit_action'));
258
    }
259
260
    /**
261
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
262
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
263
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
264
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
265
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
266
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
267
     */
268
    public function testChildren(): void
269
    {
270
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
271
        $this->assertFalse($postAdmin->hasChildren());
272
        $this->assertFalse($postAdmin->hasChild('comment'));
273
274
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
275
        $postAdmin->addChild($commentAdmin, 'post');
276
277
        $this->assertTrue($postAdmin->hasChildren());
278
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
279
280
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
281
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
282
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
283
        $this->assertSame('post', $commentAdmin->getParentAssociationMapping());
284
285
        $this->assertFalse($postAdmin->isChild());
286
        $this->assertTrue($commentAdmin->isChild());
287
288
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
289
    }
290
291
    /**
292
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
293
     */
294
    public function testConfigure(): void
295
    {
296
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
297
        $this->assertNotNull($admin->getUniqid());
298
299
        $admin->initialize();
300
        $this->assertNotNull($admin->getUniqid());
301
        $this->assertSame('Post', $admin->getClassnameLabel());
302
303
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
304
        $admin->setClassnameLabel('postcomment');
305
306
        $admin->initialize();
307
        $this->assertSame('postcomment', $admin->getClassnameLabel());
308
    }
309
310
    public function testConfigureWithValidParentAssociationMapping(): void
311
    {
312
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
313
        $admin->setParentAssociationMapping('Category');
314
315
        $admin->initialize();
316
        $this->assertSame('Category', $admin->getParentAssociationMapping());
317
    }
318
319
    public function provideGetBaseRoutePattern()
320
    {
321
        return [
322
            [
323
                'Application\Sonata\NewsBundle\Entity\Post',
324
                '/sonata/news/post',
325
            ],
326
            [
327
                'Application\Sonata\NewsBundle\Document\Post',
328
                '/sonata/news/post',
329
            ],
330
            [
331
                'MyApplication\MyBundle\Entity\Post',
332
                '/myapplication/my/post',
333
            ],
334
            [
335
                'MyApplication\MyBundle\Entity\Post\Category',
336
                '/myapplication/my/post-category',
337
            ],
338
            [
339
                'MyApplication\MyBundle\Entity\Product\Category',
340
                '/myapplication/my/product-category',
341
            ],
342
            [
343
                'MyApplication\MyBundle\Entity\Other\Product\Category',
344
                '/myapplication/my/other-product-category',
345
            ],
346
            [
347
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
348
                '/cmf/foo/menu',
349
            ],
350
            [
351
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
352
                '/cmf/foo/menu',
353
            ],
354
            [
355
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
356
                '/symfony/barbar/menu',
357
            ],
358
            [
359
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
360
                '/symfony/barbar/menu-item',
361
            ],
362
            [
363
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
364
                '/cmf/foo/menu',
365
            ],
366
            [
367
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
368
                '/cmf/foo/menu',
369
            ],
370
            [
371
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
372
                '/cmf/foo/menu',
373
            ],
374
            [
375
                'AppBundle\Entity\User',
376
                '/app/user',
377
            ],
378
            [
379
                'App\Entity\User',
380
                '/app/user',
381
            ],
382
        ];
383
    }
384
385
    /**
386
     * @dataProvider provideGetBaseRoutePattern
387
     */
388
    public function testGetBaseRoutePattern(string $objFqn, string $expected): void
389
    {
390
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
391
        $this->assertSame($expected, $admin->getBaseRoutePattern());
392
    }
393
394
    /**
395
     * @dataProvider provideGetBaseRoutePattern
396
     */
397
    public function testGetBaseRoutePatternWithChildAdmin(string $objFqn, string $expected): void
398
    {
399
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
400
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
401
        $commentAdmin->setParent($postAdmin);
402
403
        $this->assertSame(sprintf('%s/{id}/comment', $expected), $commentAdmin->getBaseRoutePattern());
404
    }
405
406
    /**
407
     * @dataProvider provideGetBaseRoutePattern
408
     */
409
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin(string $objFqn, string $expected): void
410
    {
411
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
412
        $commentAdmin = new CommentAdmin(
413
            'sonata.post.admin.comment',
414
            'Application\Sonata\NewsBundle\Entity\Comment',
415
            'Sonata\NewsBundle\Controller\CommentAdminController'
416
        );
417
        $commentVoteAdmin = new CommentVoteAdmin(
418
            'sonata.post.admin.comment_vote',
419
            'Application\Sonata\NewsBundle\Entity\CommentVote',
420
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
421
        );
422
        $commentAdmin->setParent($postAdmin);
423
        $commentVoteAdmin->setParent($commentAdmin);
424
425
        $this->assertSame(sprintf('%s/{id}/comment/{childId}/commentvote', $expected), $commentVoteAdmin->getBaseRoutePattern());
426
    }
427
428
    public function testGetBaseRoutePatternWithSpecifedPattern(): void
429
    {
430
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostWithCustomRouteAdminController');
431
432
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
433
    }
434
435
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern(): void
436
    {
437
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
438
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController');
439
        $commentAdmin->setParent($postAdmin);
440
441
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
442
    }
443
444
    public function testGetBaseRoutePatternWithUnreconizedClassname(): void
445
    {
446
        $this->expectException(\RuntimeException::class);
447
448
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
449
        $admin->getBaseRoutePattern();
450
    }
451
452
    public function provideGetBaseRouteName()
453
    {
454
        return [
455
            [
456
                'Application\Sonata\NewsBundle\Entity\Post',
457
                'admin_sonata_news_post',
458
            ],
459
            [
460
                'Application\Sonata\NewsBundle\Document\Post',
461
                'admin_sonata_news_post',
462
            ],
463
            [
464
                'MyApplication\MyBundle\Entity\Post',
465
                'admin_myapplication_my_post',
466
            ],
467
            [
468
                'MyApplication\MyBundle\Entity\Post\Category',
469
                'admin_myapplication_my_post_category',
470
            ],
471
            [
472
                'MyApplication\MyBundle\Entity\Product\Category',
473
                'admin_myapplication_my_product_category',
474
            ],
475
            [
476
                'MyApplication\MyBundle\Entity\Other\Product\Category',
477
                'admin_myapplication_my_other_product_category',
478
            ],
479
            [
480
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
481
                'admin_cmf_foo_menu',
482
            ],
483
            [
484
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
485
                'admin_cmf_foo_menu',
486
            ],
487
            [
488
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
489
                'admin_symfony_barbar_menu',
490
            ],
491
            [
492
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
493
                'admin_symfony_barbar_menu_item',
494
            ],
495
            [
496
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
497
                'admin_cmf_foo_menu',
498
            ],
499
            [
500
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
501
                'admin_cmf_foo_menu',
502
            ],
503
            [
504
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
505
                'admin_cmf_foo_menu',
506
            ],
507
            [
508
                'AppBundle\Entity\User',
509
                'admin_app_user',
510
            ],
511
            [
512
                'App\Entity\User',
513
                'admin_app_user',
514
            ],
515
        ];
516
    }
517
518
    /**
519
     * @dataProvider provideGetBaseRouteName
520
     */
521
    public function testGetBaseRouteName(string $objFqn, string $expected): void
522
    {
523
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
524
525
        $this->assertSame($expected, $admin->getBaseRouteName());
526
    }
527
528
    public function testGetBaseRouteNameWithUnreconizedClassname(): void
529
    {
530
        $this->expectException(\RuntimeException::class);
531
532
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
533
        $admin->getBaseRouteName();
534
    }
535
536
    public function testGetBaseRouteNameWithSpecifiedName(): void
537
    {
538
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
539
540
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
541
    }
542
543
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName(): void
544
    {
545
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
546
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController');
547
        $commentAdmin->setParent($postAdmin);
548
549
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
550
    }
551
552
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName(): void
553
    {
554
        $postAdmin = new PostAdmin(
555
            'sonata.post.admin.post',
556
            'Application\Sonata\NewsBundle\Entity\Post',
557
            'Sonata\NewsBundle\Controller\PostAdminController'
558
        );
559
        $commentAdmin = new CommentWithCustomRouteAdmin(
560
            'sonata.post.admin.comment_with_custom_route',
561
            'Application\Sonata\NewsBundle\Entity\Comment',
562
            'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController'
563
        );
564
        $commentVoteAdmin = new CommentVoteAdmin(
565
            'sonata.post.admin.comment_vote',
566
            'Application\Sonata\NewsBundle\Entity\CommentVote',
567
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
568
        );
569
        $commentAdmin->setParent($postAdmin);
570
        $commentVoteAdmin->setParent($commentAdmin);
571
572
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
573
    }
574
575
    /**
576
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
577
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
578
     */
579
    public function testSetUniqid(): void
580
    {
581
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
582
583
        $uniqid = uniqid();
584
        $admin->setUniqid($uniqid);
585
586
        $this->assertSame($uniqid, $admin->getUniqid());
587
    }
588
589
    public function testToString(): void
590
    {
591
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
592
593
        $s = new \stdClass();
594
595
        $this->assertNotEmpty($admin->toString($s));
596
597
        $s = new FooToString();
598
        $this->assertSame('salut', $admin->toString($s));
599
600
        // To string method is implemented, but returns null
601
        $s = new FooToStringNull();
602
        $this->assertNotEmpty($admin->toString($s));
603
604
        $this->assertSame('', $admin->toString(false));
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a object.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
605
    }
606
607
    public function testIsAclEnabled(): void
608
    {
609
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
610
611
        $this->assertFalse($postAdmin->isAclEnabled());
612
613
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
614
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
615
        $this->assertTrue($commentAdmin->isAclEnabled());
616
    }
617
618
    /**
619
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
620
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
621
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
622
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
623
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
624
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
625
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
626
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
627
     */
628
    public function testSubClass(): void
629
    {
630
        $admin = new PostAdmin(
631
            'sonata.post.admin.post',
632
            Post::class,
633
            'Sonata\NewsBundle\Controller\PostAdminController'
634
        );
635
        $this->assertFalse($admin->hasSubClass('test'));
636
        $this->assertFalse($admin->hasActiveSubClass());
637
        $this->assertCount(0, $admin->getSubClasses());
638
        $this->assertSame(Post::class, $admin->getClass());
639
640
        // Just for the record, if there is no inheritance set, the getSubject is not used
641
        // the getSubject can also lead to some issue
642
        $admin->setSubject(new BlogPost());
643
        $this->assertSame(BlogPost::class, $admin->getClass());
644
645
        $admin->setSubClasses([
646
            'extended1' => 'NewsBundle\Entity\PostExtended1',
647
            'extended2' => 'NewsBundle\Entity\PostExtended2',
648
        ]);
649
        $this->assertFalse($admin->hasSubClass('test'));
650
        $this->assertTrue($admin->hasSubClass('extended1'));
651
        $this->assertFalse($admin->hasActiveSubClass());
652
        $this->assertCount(2, $admin->getSubClasses());
653
        $this->assertSame(
654
            BlogPost::class,
655
            $admin->getClass(),
656
            'When there is no subclass in the query the class parameter should be returned'
657
        );
658
659
        $request = new Request(['subclass' => 'extended1']);
660
        $admin->setRequest($request);
661
        $this->assertFalse($admin->hasSubClass('test'));
662
        $this->assertTrue($admin->hasSubClass('extended1'));
663
        $this->assertTrue($admin->hasActiveSubClass());
664
        $this->assertCount(2, $admin->getSubClasses());
665
        $this->assertSame(
666
            'NewsBundle\Entity\PostExtended1',
667
            $admin->getActiveSubClass(),
668
            'It should return the curently active sub class.'
669
        );
670
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
671
        $this->assertSame(
672
            'NewsBundle\Entity\PostExtended1',
673
            $admin->getClass(),
674
            'getClass() should return the name of the sub class when passed through a request query parameter.'
675
        );
676
677
        $request->query->set('subclass', 'inject');
678
679
        $this->expectException(\LogicException::class);
680
        $this->expectExceptionMessage(sprintf('Admin "%s" has no active subclass.', PostAdmin::class));
681
682
        $admin->getActiveSubclassCode();
683
    }
684
685
    public function testNonExistantSubclass(): void
686
    {
687
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
688
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
689
690
        $admin->setRequest(new Request(['subclass' => 'inject']));
691
692
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
693
694
        $this->assertTrue($admin->hasActiveSubClass());
695
696
        $this->expectException(\LogicException::class);
697
698
        $admin->getActiveSubClass();
699
    }
700
701
    /**
702
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
703
     */
704
    public function testOnlyOneSubclassNeededToBeActive(): void
705
    {
706
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
707
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
708
        $request = new Request(['subclass' => 'extended1']);
709
        $admin->setRequest($request);
710
        $this->assertTrue($admin->hasActiveSubClass());
711
    }
712
713
    public function testGetLabelTranslatorStrategy(): void
714
    {
715
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
716
717
        $this->assertNull($admin->getLabelTranslatorStrategy());
718
719
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
720
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
721
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
722
    }
723
724
    public function testGetRouteBuilder(): void
725
    {
726
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
727
728
        $this->assertNull($admin->getRouteBuilder());
729
730
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
731
        $admin->setRouteBuilder($routeBuilder);
732
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
733
    }
734
735
    public function testGetMenuFactory(): void
736
    {
737
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
738
739
        $this->assertNull($admin->getMenuFactory());
740
741
        $menuFactory = $this->createMock(FactoryInterface::class);
742
        $admin->setMenuFactory($menuFactory);
743
        $this->assertSame($menuFactory, $admin->getMenuFactory());
744
    }
745
746
    public function testGetExtensions(): void
747
    {
748
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
749
750
        $this->assertSame([], $admin->getExtensions());
751
752
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
753
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
754
755
        $admin->addExtension($adminExtension1);
756
        $admin->addExtension($adminExtension2);
757
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
758
    }
759
760
    public function testGetFilterTheme(): void
761
    {
762
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
763
764
        $this->assertSame([], $admin->getFilterTheme());
765
766
        $admin->setFilterTheme(['FooTheme']);
767
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
768
    }
769
770
    public function testGetFormTheme(): void
771
    {
772
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
773
774
        $this->assertSame([], $admin->getFormTheme());
775
776
        $admin->setFormTheme(['FooTheme']);
777
778
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
779
    }
780
781
    public function testGetValidator(): void
782
    {
783
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
784
785
        $this->assertNull($admin->getValidator());
786
787
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
788
789
        $admin->setValidator($validator);
790
        $this->assertSame($validator, $admin->getValidator());
791
    }
792
793
    public function testGetSecurityHandler(): void
794
    {
795
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
796
797
        $this->assertNull($admin->getSecurityHandler());
798
799
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
800
        $admin->setSecurityHandler($securityHandler);
801
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
802
    }
803
804
    public function testGetSecurityInformation(): void
805
    {
806
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
807
808
        $this->assertSame([], $admin->getSecurityInformation());
809
810
        $securityInformation = [
811
            'GUEST' => ['VIEW', 'LIST'],
812
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
813
        ];
814
815
        $admin->setSecurityInformation($securityInformation);
816
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
817
    }
818
819
    public function testGetManagerType(): void
820
    {
821
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
822
823
        $this->assertNull($admin->getManagerType());
824
825
        $admin->setManagerType('foo_orm');
826
        $this->assertSame('foo_orm', $admin->getManagerType());
827
    }
828
829
    public function testGetModelManager(): void
830
    {
831
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
832
833
        $this->assertNull($admin->getModelManager());
834
835
        $modelManager = $this->createMock(ModelManagerInterface::class);
836
837
        $admin->setModelManager($modelManager);
838
        $this->assertSame($modelManager, $admin->getModelManager());
839
    }
840
841
    public function testGetBaseCodeRoute(): void
842
    {
843
        $postAdmin = new PostAdmin(
844
            'sonata.post.admin.post',
845
            'NewsBundle\Entity\Post',
846
            'Sonata\NewsBundle\Controller\PostAdminController'
847
        );
848
        $commentAdmin = new CommentAdmin(
849
            'sonata.post.admin.comment',
850
            'Application\Sonata\NewsBundle\Entity\Comment',
851
            'Sonata\NewsBundle\Controller\CommentAdminController'
852
        );
853
854
        $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
855
856
        $postAdmin->addChild($commentAdmin, 'post');
857
858
        $this->assertSame(
859
            'sonata.post.admin.post|sonata.post.admin.comment',
860
            $commentAdmin->getBaseCodeRoute()
861
        );
862
    }
863
864
    public function testGetRouteGenerator(): void
865
    {
866
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
867
868
        $this->assertNull($admin->getRouteGenerator());
869
870
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
871
872
        $admin->setRouteGenerator($routeGenerator);
873
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
874
    }
875
876
    public function testGetConfigurationPool(): void
877
    {
878
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
879
880
        $this->assertNull($admin->getConfigurationPool());
881
882
        $pool = $this->getMockBuilder(Pool::class)
883
            ->disableOriginalConstructor()
884
            ->getMock();
885
886
        $admin->setConfigurationPool($pool);
887
        $this->assertSame($pool, $admin->getConfigurationPool());
888
    }
889
890
    public function testGetShowBuilder(): void
891
    {
892
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
893
894
        $this->assertNull($admin->getShowBuilder());
895
896
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
897
898
        $admin->setShowBuilder($showBuilder);
899
        $this->assertSame($showBuilder, $admin->getShowBuilder());
900
    }
901
902
    public function testGetListBuilder(): void
903
    {
904
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
905
906
        $this->assertNull($admin->getListBuilder());
907
908
        $listBuilder = $this->createMock(ListBuilderInterface::class);
909
910
        $admin->setListBuilder($listBuilder);
911
        $this->assertSame($listBuilder, $admin->getListBuilder());
912
    }
913
914
    public function testGetDatagridBuilder(): void
915
    {
916
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
917
918
        $this->assertNull($admin->getDatagridBuilder());
919
920
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
921
922
        $admin->setDatagridBuilder($datagridBuilder);
923
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
924
    }
925
926
    public function testGetFormContractor(): void
927
    {
928
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
929
930
        $this->assertNull($admin->getFormContractor());
931
932
        $formContractor = $this->createMock(FormContractorInterface::class);
933
934
        $admin->setFormContractor($formContractor);
935
        $this->assertSame($formContractor, $admin->getFormContractor());
936
    }
937
938
    public function testGetRequest(): void
939
    {
940
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
941
942
        $this->assertFalse($admin->hasRequest());
943
944
        $request = new Request();
945
946
        $admin->setRequest($request);
947
        $this->assertSame($request, $admin->getRequest());
948
        $this->assertTrue($admin->hasRequest());
949
    }
950
951
    public function testGetRequestWithException(): void
952
    {
953
        $this->expectException(\LogicException::class);
954
        $this->expectExceptionMessage('The Request object has not been set');
955
956
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
957
        $admin->getRequest();
958
    }
959
960
    public function testGetTranslationDomain(): void
961
    {
962
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
963
964
        $this->assertSame('messages', $admin->getTranslationDomain());
965
966
        $admin->setTranslationDomain('foo');
967
        $this->assertSame('foo', $admin->getTranslationDomain());
968
    }
969
970
    public function testGetShowGroups(): void
971
    {
972
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
973
974
        $this->assertSame([], $admin->getShowGroups());
975
976
        $groups = ['foo', 'bar', 'baz'];
977
978
        $admin->setShowGroups($groups);
979
        $this->assertSame($groups, $admin->getShowGroups());
980
    }
981
982
    public function testGetFormGroups(): void
983
    {
984
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
985
986
        $this->assertSame([], $admin->getFormGroups());
987
988
        $groups = ['foo', 'bar', 'baz'];
989
990
        $admin->setFormGroups($groups);
991
        $this->assertSame($groups, $admin->getFormGroups());
992
    }
993
994
    public function testGetMaxPageLinks(): void
995
    {
996
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
997
998
        $this->assertSame(25, $admin->getMaxPageLinks());
999
1000
        $admin->setMaxPageLinks(14);
1001
        $this->assertSame(14, $admin->getMaxPageLinks());
1002
    }
1003
1004
    public function testGetLabel(): void
1005
    {
1006
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1007
1008
        $this->assertNull($admin->getLabel());
1009
1010
        $admin->setLabel('FooLabel');
1011
        $this->assertSame('FooLabel', $admin->getLabel());
1012
    }
1013
1014
    public function testGetBaseController(): void
1015
    {
1016
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1017
1018
        $this->assertSame('Sonata\NewsBundle\Controller\PostAdminController', $admin->getBaseControllerName());
1019
1020
        $admin->setBaseControllerName('Sonata\NewsBundle\Controller\FooAdminController');
1021
        $this->assertSame('Sonata\NewsBundle\Controller\FooAdminController', $admin->getBaseControllerName());
1022
    }
1023
1024
    public function testGetIdParameter(): void
1025
    {
1026
        $postAdmin = new PostAdmin(
1027
            'sonata.post.admin.post',
1028
            'NewsBundle\Entity\Post',
1029
            'Sonata\NewsBundle\Controller\PostAdminController'
1030
        );
1031
1032
        $this->assertSame('id', $postAdmin->getIdParameter());
1033
        $this->assertFalse($postAdmin->isChild());
1034
1035
        $commentAdmin = new CommentAdmin(
1036
            'sonata.post.admin.comment',
1037
            'Application\Sonata\NewsBundle\Entity\Comment',
1038
            'Sonata\NewsBundle\Controller\CommentAdminController'
1039
        );
1040
        $commentAdmin->setParent($postAdmin);
1041
1042
        $this->assertTrue($commentAdmin->isChild());
1043
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1044
1045
        $commentVoteAdmin = new CommentVoteAdmin(
1046
            'sonata.post.admin.comment_vote',
1047
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1048
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
1049
        );
1050
        $commentVoteAdmin->setParent($commentAdmin);
1051
1052
        $this->assertTrue($commentVoteAdmin->isChild());
1053
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1054
    }
1055
1056
    public function testGetExportFormats(): void
1057
    {
1058
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1059
1060
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1061
    }
1062
1063
    public function testGetUrlsafeIdentifier(): void
1064
    {
1065
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1066
1067
        $model = new \stdClass();
1068
1069
        $modelManager = $this->createMock(ModelManagerInterface::class);
1070
        $modelManager->expects($this->once())
1071
            ->method('getUrlSafeIdentifier')
1072
            ->with($this->equalTo($model))
1073
            ->willReturn('foo');
1074
        $admin->setModelManager($modelManager);
1075
1076
        $this->assertSame('foo', $admin->getUrlSafeIdentifier($model));
1077
    }
1078
1079
    public function testDeterminedPerPageValue(): void
1080
    {
1081
        $modelManager = $this->createStub(ModelManagerInterface::class);
1082
1083
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1084
        $admin->setModelManager($modelManager);
1085
1086
        $this->assertFalse($admin->determinedPerPageValue(123));
1087
        $this->assertTrue($admin->determinedPerPageValue(25));
1088
    }
1089
1090
    public function testIsGranted(): void
1091
    {
1092
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1093
        $modelManager = $this->createStub(ModelManagerInterface::class);
1094
        $modelManager
1095
            ->method('getNormalizedIdentifier')
1096
            ->willReturnCallback(static function (?object $model = null): ?string {
1097
                return $model ? $model->id : null;
1098
            });
1099
1100
        $admin->setModelManager($modelManager);
1101
1102
        $entity1 = new \stdClass();
1103
        $entity1->id = '1';
1104
1105
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1106
        $securityHandler
1107
            ->expects($this->exactly(6))
1108
            ->method('isGranted')
1109
            ->willReturnCallback(static function (
1110
                AdminInterface $adminIn,
1111
                string $attributes,
1112
                ?object $object = null
1113
            ) use (
1114
                $admin,
1115
                $entity1
1116
            ): bool {
1117
                return $admin === $adminIn && 'FOO' === $attributes &&
1118
                    ($object === $admin || $object === $entity1);
1119
            });
1120
1121
        $admin->setSecurityHandler($securityHandler);
1122
1123
        $this->assertTrue($admin->isGranted('FOO'));
1124
        $this->assertTrue($admin->isGranted('FOO'));
1125
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1126
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1127
        $this->assertFalse($admin->isGranted('BAR'));
1128
        $this->assertFalse($admin->isGranted('BAR'));
1129
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1130
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1131
1132
        $entity2 = new \stdClass();
1133
        $entity2->id = '2';
1134
1135
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1136
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1137
1138
        $entity3 = new \stdClass();
1139
        $entity3->id = '3';
1140
1141
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1142
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1143
    }
1144
1145
    public function testSupportsPreviewMode(): void
1146
    {
1147
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1148
1149
        $this->assertFalse($admin->supportsPreviewMode());
1150
    }
1151
1152
    public function testGetPermissionsShow(): void
1153
    {
1154
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1155
1156
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1157
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1158
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1159
    }
1160
1161
    public function testShowIn(): void
1162
    {
1163
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1164
1165
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1166
        $securityHandler
1167
            ->method('isGranted')
1168
            ->willReturnCallback(static function (AdminInterface $adminIn, array $attributes, $object = null) use ($admin): bool {
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...
1169
                return $admin === $adminIn && $attributes === ['LIST'];
1170
            });
1171
1172
        $admin->setSecurityHandler($securityHandler);
1173
1174
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1175
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1176
        $this->assertTrue($admin->showIn('foo'));
1177
    }
1178
1179
    public function testGetObjectIdentifier(): void
1180
    {
1181
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1182
1183
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1184
    }
1185
1186
    /**
1187
     * @doesNotPerformAssertions
1188
     */
1189
    public function testSetFilterPersister(): void
1190
    {
1191
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle\Controller\PostAdminController');
1192
1193
        $filterPersister = $this->createMock(FilterPersisterInterface::class);
1194
1195
        $admin->setFilterPersister($filterPersister);
1196
    }
1197
1198
    public function testGetRootCode(): void
1199
    {
1200
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1201
1202
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1203
1204
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'Sonata\NewsBundle\Controller\PostParentAdminController');
1205
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1206
        $parentFieldDescription->expects($this->once())
1207
            ->method('getAdmin')
1208
            ->willReturn($parentAdmin);
1209
1210
        $this->assertFalse($admin->hasParentFieldDescription());
1211
        $admin->setParentFieldDescription($parentFieldDescription);
1212
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1213
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1214
    }
1215
1216
    public function testGetRoot(): void
1217
    {
1218
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1219
1220
        $this->assertSame($admin, $admin->getRoot());
1221
1222
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'Sonata\NewsBundle\Controller\PostParentAdminController');
1223
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1224
        $parentFieldDescription->expects($this->once())
1225
            ->method('getAdmin')
1226
            ->willReturn($parentAdmin);
1227
1228
        $this->assertFalse($admin->hasParentFieldDescription());
1229
        $admin->setParentFieldDescription($parentFieldDescription);
1230
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1231
        $this->assertSame($parentAdmin, $admin->getRoot());
1232
    }
1233
1234
    public function testGetExportFields(): void
1235
    {
1236
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1237
1238
        $modelManager = $this->createMock(ModelManagerInterface::class);
1239
        $modelManager->expects($this->once())
1240
            ->method('getExportFields')
1241
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1242
            ->willReturn(['foo', 'bar']);
1243
1244
        $admin->setModelManager($modelManager);
1245
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1246
    }
1247
1248
    public function testGetPersistentParametersWithNoExtension(): void
1249
    {
1250
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1251
1252
        $this->assertEmpty($admin->getPersistentParameters());
1253
    }
1254
1255
    public function testGetPersistentParametersWithValidExtension(): void
1256
    {
1257
        $expected = [
1258
            'context' => 'foobar',
1259
        ];
1260
1261
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1262
1263
        $extension = $this->createMock(AdminExtensionInterface::class);
1264
        $extension->expects($this->once())->method('getPersistentParameters')->willReturn($expected);
1265
1266
        $admin->addExtension($extension);
1267
1268
        $this->assertSame($expected, $admin->getPersistentParameters());
1269
    }
1270
1271
    public function testGetNewInstanceForChildAdminWithParentValue(): void
1272
    {
1273
        $post = new Post();
1274
1275
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1276
        $postAdmin->method('getObject')->willReturn($post);
1277
1278
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1279
        $formBuilder->method('getForm')->willReturn(null);
1280
1281
        $tag = new Tag();
1282
1283
        $modelManager = $this->createStub(ModelManagerInterface::class);
1284
        $modelManager->method('getModelInstance')->willReturn($tag);
1285
1286
        $tagAdmin = new TagAdmin('admin.tag', Tag::class, 'MyBundle\MyController');
1287
        $tagAdmin->setModelManager($modelManager);
1288
        $tagAdmin->setParent($postAdmin);
1289
1290
        $request = $this->createStub(Request::class);
1291
        $tagAdmin->setRequest($request);
1292
1293
        $configurationPool = $this->getMockBuilder(Pool::class)
1294
            ->disableOriginalConstructor()
1295
            ->getMock();
1296
1297
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1298
1299
        $tagAdmin->setConfigurationPool($configurationPool);
1300
1301
        $tag = $tagAdmin->getNewInstance();
1302
1303
        $this->assertSame($post, $tag->getPost());
1304
    }
1305
1306
    public function testGetNewInstanceForChildAdminWithCollectionParentValue(): void
1307
    {
1308
        $post = new Post();
1309
1310
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1311
        $postAdmin->method('getObject')->willReturn($post);
1312
1313
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1314
        $formBuilder->method('getForm')->willReturn(null);
1315
1316
        $postCategory = new PostCategory();
1317
1318
        $modelManager = $this->createStub(ModelManagerInterface::class);
1319
        $modelManager->method('getModelInstance')->willReturn($postCategory);
1320
1321
        $postCategoryAdmin = new PostCategoryAdmin('admin.post_category', PostCategoryAdmin::class, 'MyBundle\MyController');
1322
        $postCategoryAdmin->setModelManager($modelManager);
1323
        $postCategoryAdmin->setParent($postAdmin);
1324
1325
        $request = $this->createStub(Request::class);
1326
        $postCategoryAdmin->setRequest($request);
1327
1328
        $configurationPool = $this->getMockBuilder(Pool::class)
1329
            ->disableOriginalConstructor()
1330
            ->getMock();
1331
1332
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1333
1334
        $postCategoryAdmin->setConfigurationPool($configurationPool);
1335
1336
        $postCategory = $postCategoryAdmin->getNewInstance();
1337
1338
        $this->assertInstanceOf(Collection::class, $postCategory->getPosts());
1339
        $this->assertCount(1, $postCategory->getPosts());
1340
        $this->assertContains($post, $postCategory->getPosts());
1341
    }
1342
1343
    public function testGetNewInstanceForEmbededAdminWithParentValue(): void
1344
    {
1345
        $post = new Post();
1346
1347
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1348
        $postAdmin->method('getObject')->willReturn($post);
1349
1350
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1351
        $formBuilder->method('getForm')->willReturn(null);
1352
1353
        $parentField = $this->createStub(FieldDescriptionInterface::class);
1354
        $parentField->method('getAdmin')->willReturn($postAdmin);
1355
        $parentField->method('getParentAssociationMappings')->willReturn([]);
1356
        $parentField->method('getAssociationMapping')->willReturn(['fieldName' => 'tag', 'mappedBy' => 'post']);
1357
1358
        $tag = new Tag();
1359
1360
        $modelManager = $this->createStub(ModelManagerInterface::class);
1361
        $modelManager->method('getModelInstance')->willReturn($tag);
1362
1363
        $tagAdmin = new TagAdmin('admin.tag', Tag::class, 'MyBundle\MyController');
1364
        $tagAdmin->setModelManager($modelManager);
1365
        $tagAdmin->setParentFieldDescription($parentField);
1366
1367
        $request = $this->createStub(Request::class);
1368
        $tagAdmin->setRequest($request);
1369
1370
        $configurationPool = $this->getMockBuilder(Pool::class)
1371
            ->disableOriginalConstructor()
1372
            ->getMock();
1373
1374
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1375
1376
        $tagAdmin->setConfigurationPool($configurationPool);
1377
1378
        $tag = $tagAdmin->getNewInstance();
1379
1380
        $this->assertSame($post, $tag->getPost());
1381
    }
1382
1383
    public function testFormAddPostSubmitEventForPreValidation(): void
1384
    {
1385
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', \stdClass::class, 'Sonata\FooBundle\Controller\ModelAdminController');
1386
        $object = new \stdClass();
1387
1388
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1389
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1390
1391
        $validator = $this->createMock(ValidatorInterface::class);
1392
        $validator
1393
                ->method('getMetadataFor')
1394
                ->willReturn($this->createMock(MemberMetadata::class));
1395
        $modelAdmin->setValidator($validator);
1396
1397
        $modelManager = $this->createMock(ModelManagerInterface::class);
1398
        $modelManager
1399
            ->method('getNewFieldDescriptionInstance')
1400
            ->willReturn(new FieldDescription());
1401
        $modelAdmin->setModelManager($modelManager);
1402
1403
        // a Admin class to test that preValidate is called
1404
        $testAdminPreValidate = $this->createMock(AbstractAdmin::class);
1405
        $testAdminPreValidate->expects($this->once())
1406
                ->method('preValidate')
1407
                ->with($this->identicalTo($object));
1408
1409
        $event = $this->createMock(FormEvent::class);
1410
        $event
1411
                ->method('getData')
1412
                ->willReturn($object);
1413
1414
        $formBuild = $this->createMock(FormBuilder::class);
1415
        $formBuild->expects($this->once())
1416
                ->method('addEventListener')
1417
                ->with(
1418
                    $this->identicalTo(FormEvents::POST_SUBMIT),
1419
                    $this->callback(static function ($callback) use ($testAdminPreValidate, $event): bool {
1420
                        if (\is_callable($callback)) {
1421
                            $closure = $callback->bindTo($testAdminPreValidate);
0 ignored issues
show
Bug introduced by
The method bindTo cannot be called on $callback (of type callable).

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

Loading history...
1422
                            $closure($event);
1423
1424
                            return true;
1425
                        }
1426
1427
                        return false;
1428
                    }),
1429
                    $this->greaterThan(0)
1430
                );
1431
1432
        $formContractor = $this->createMock(FormContractorInterface::class);
1433
        $formContractor
1434
                ->method('getDefaultOptions')
1435
                ->willReturn([]);
1436
        $formContractor
1437
                ->method('getFormBuilder')
1438
                ->willReturn($formBuild);
1439
1440
        $modelAdmin->setFormContractor($formContractor);
1441
        $modelAdmin->setSubject($object);
1442
        $modelAdmin->defineFormBuilder($formBuild);
1443
        $modelAdmin->getForm();
1444
    }
1445
1446
    public function testCanAddInlineValidationOnlyForGenericMetadata(): void
1447
    {
1448
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', \stdClass::class, 'Sonata\FooBundle\Controller\ModelAdminController');
1449
        $object = new \stdClass();
1450
1451
        $labelTranslatorStrategy = $this->createStub(LabelTranslatorStrategyInterface::class);
1452
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1453
1454
        $validator = $this->createStub(ValidatorInterface::class);
1455
        $metadata = $this->createStub(PropertyMetadataInterface::class);
1456
        $validator
1457
            ->method('getMetadataFor')
1458
            ->willReturn($metadata);
1459
        $modelAdmin->setValidator($validator);
1460
1461
        $modelManager = $this->createStub(ModelManagerInterface::class);
1462
        $modelManager
1463
            ->method('getNewFieldDescriptionInstance')
1464
            ->willReturn(new FieldDescription());
1465
        $modelAdmin->setModelManager($modelManager);
1466
1467
        $event = $this->createStub(FormEvent::class);
1468
        $event
1469
            ->method('getData')
1470
            ->willReturn($object);
1471
1472
        $formBuild = $this->createStub(FormBuilder::class);
1473
1474
        $formContractor = $this->createStub(FormContractorInterface::class);
1475
        $formContractor
1476
            ->method('getDefaultOptions')
1477
            ->willReturn([]);
1478
        $formContractor
1479
            ->method('getFormBuilder')
1480
            ->willReturn($formBuild);
1481
1482
        $modelAdmin->setFormContractor($formContractor);
1483
        $modelAdmin->setSubject($object);
1484
1485
        $this->expectException(\RuntimeException::class);
1486
        $this->expectExceptionMessage(
1487
            sprintf(
1488
                'Cannot add inline validator for stdClass because its metadata is an instance of %s instead of Symfony\Component\Validator\Mapping\GenericMetadata',
1489
                \get_class($metadata)
1490
            )
1491
        );
1492
1493
        $modelAdmin->defineFormBuilder($formBuild);
1494
    }
1495
1496
    public function testRemoveFieldFromFormGroup(): void
1497
    {
1498
        $formGroups = [
1499
            'foobar' => [
1500
                'fields' => [
1501
                    'foo' => 'foo',
1502
                    'bar' => 'bar',
1503
                ],
1504
            ],
1505
        ];
1506
1507
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1508
        $admin->setFormGroups($formGroups);
1509
1510
        $admin->removeFieldFromFormGroup('foo');
1511
        $this->assertSame($admin->getFormGroups(), [
1512
            'foobar' => [
1513
                'fields' => [
1514
                    'bar' => 'bar',
1515
                ],
1516
            ],
1517
        ]);
1518
1519
        $admin->removeFieldFromFormGroup('bar');
1520
        $this->assertSame($admin->getFormGroups(), []);
1521
    }
1522
1523
    public function testGetFilterParameters(): void
1524
    {
1525
        $authorId = uniqid();
1526
1527
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1528
1529
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
1530
        $commentAdmin->setParentAssociationMapping('post.author');
1531
        $commentAdmin->setParent($postAdmin);
1532
1533
        $request = $this->createMock(Request::class);
1534
        $query = $this->createMock(ParameterBag::class);
1535
        $query
1536
            ->method('get')
1537
            ->willReturn([
1538
                'filter' => [
1539
                    '_page' => '1',
1540
                    '_per_page' => '32',
1541
                ],
1542
            ]);
1543
1544
        $request->query = $query;
1545
        $request
1546
            ->method('get')
1547
            ->willReturn($authorId);
1548
1549
        $commentAdmin->setRequest($request);
1550
1551
        $modelManager = $this->createMock(ModelManagerInterface::class);
1552
        $modelManager
1553
            ->method('getDefaultSortValues')
1554
            ->willReturn([]);
1555
1556
        $commentAdmin->setModelManager($modelManager);
1557
1558
        $parameters = $commentAdmin->getFilterParameters();
1559
1560
        $this->assertTrue(isset($parameters['post__author']));
1561
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1562
    }
1563
1564
    public function testGetFilterFieldDescription(): void
1565
    {
1566
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1567
1568
        $fooFieldDescription = new FieldDescription();
1569
        $barFieldDescription = new FieldDescription();
1570
        $bazFieldDescription = new FieldDescription();
1571
1572
        $modelManager = $this->createMock(ModelManagerInterface::class);
1573
        $modelManager->expects($this->exactly(3))
1574
            ->method('getNewFieldDescriptionInstance')
1575
            ->willReturnCallback(static function ($adminClass, string $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...
1576
                switch ($name) {
1577
                    case 'foo':
1578
                        $fieldDescription = $fooFieldDescription;
1579
1580
                        break;
1581
1582
                    case 'bar':
1583
                        $fieldDescription = $barFieldDescription;
1584
1585
                        break;
1586
1587
                    case 'baz':
1588
                        $fieldDescription = $bazFieldDescription;
1589
1590
                        break;
1591
1592
                    default:
1593
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1594
                        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...
1595
                }
1596
1597
                $fieldDescription->setName($name);
1598
1599
                return $fieldDescription;
1600
            });
1601
1602
        $modelAdmin->setModelManager($modelManager);
1603
1604
        $pager = $this->createMock(PagerInterface::class);
1605
1606
        $datagrid = $this->createMock(DatagridInterface::class);
1607
        $datagrid->expects($this->once())
1608
            ->method('getPager')
1609
            ->willReturn($pager);
1610
1611
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1612
        $datagridBuilder->expects($this->once())
1613
            ->method('getBaseDatagrid')
1614
            ->with($this->identicalTo($modelAdmin), [])
1615
            ->willReturn($datagrid);
1616
1617
        $datagridBuilder->expects($this->exactly(3))
1618
            ->method('addFilter')
1619
            ->willReturnCallback(static function ($datagrid, $type, $fieldDescription, AdminInterface $admin): void {
1620
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1621
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1622
            });
1623
1624
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1625
1626
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1627
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1628
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1629
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1630
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1631
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1632
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1633
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1634
    }
1635
1636
    public function testGetSubjectNoRequest(): void
1637
    {
1638
        $modelManager = $this->createMock(ModelManagerInterface::class);
1639
        $modelManager
1640
            ->expects($this->never())
1641
            ->method('find');
1642
1643
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1644
        $admin->setModelManager($modelManager);
1645
1646
        $this->assertFalse($admin->hasSubject());
1647
    }
1648
1649
    public function testGetSideMenu(): void
1650
    {
1651
        $item = $this->createMock(ItemInterface::class);
1652
        $item
1653
            ->expects($this->once())
1654
            ->method('setChildrenAttribute')
1655
            ->with('class', 'nav navbar-nav');
1656
        $item
1657
            ->expects($this->once())
1658
            ->method('setExtra')
1659
            ->with('translation_domain', 'foo_bar_baz');
1660
1661
        $menuFactory = $this->createMock(FactoryInterface::class);
1662
        $menuFactory
1663
            ->expects($this->once())
1664
            ->method('createItem')
1665
            ->willReturn($item);
1666
1667
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1668
        $modelAdmin->setMenuFactory($menuFactory);
1669
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1670
1671
        $modelAdmin->getSideMenu('foo');
1672
    }
1673
1674
    /**
1675
     * @return array
1676
     */
1677
    public function provideGetSubject()
1678
    {
1679
        return [
1680
            [23],
1681
            ['azerty'],
1682
            ['4f69bbb5f14a13347f000092'],
1683
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1684
            [sprintf('123%smy_type', AdapterInterface::ID_SEPARATOR)], // composite keys are supported
1685
        ];
1686
    }
1687
1688
    /**
1689
     * @dataProvider provideGetSubject
1690
     */
1691
    public function testGetSubjectFailed($id): void
1692
    {
1693
        $modelManager = $this->createMock(ModelManagerInterface::class);
1694
        $modelManager
1695
            ->expects($this->once())
1696
            ->method('find')
1697
            ->with('NewsBundle\Entity\Post', $id)
1698
            ->willReturn(null); // entity not found
1699
1700
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1701
        $admin->setModelManager($modelManager);
1702
1703
        $admin->setRequest(new Request(['id' => $id]));
1704
        $this->assertFalse($admin->hasSubject());
1705
    }
1706
1707
    /**
1708
     * @dataProvider provideGetSubject
1709
     */
1710
    public function testGetSubject($id): void
1711
    {
1712
        $model = new Post();
1713
1714
        $modelManager = $this->createMock(ModelManagerInterface::class);
1715
        $modelManager
1716
            ->expects($this->once())
1717
            ->method('find')
1718
            ->with('NewsBundle\Entity\Post', $id)
1719
            ->willReturn($model);
1720
1721
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1722
        $admin->setModelManager($modelManager);
1723
1724
        $admin->setRequest(new Request(['id' => $id]));
1725
        $this->assertTrue($admin->hasSubject());
1726
        $this->assertSame($model, $admin->getSubject());
1727
        $this->assertSame($model, $admin->getSubject()); // model manager must be used only once
1728
    }
1729
1730
    public function testGetSubjectWithParentDescription(): void
1731
    {
1732
        $adminId = 1;
1733
1734
        $comment = new Comment();
1735
1736
        $modelManager = $this->createMock(ModelManagerInterface::class);
1737
        $modelManager
1738
            ->method('find')
1739
            ->with('NewsBundle\Entity\Comment', $adminId)
1740
            ->willReturn($comment);
1741
1742
        $request = new Request(['id' => $adminId]);
1743
1744
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1745
        $postAdmin->setRequest($request);
1746
1747
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
1748
        $commentAdmin->setRequest($request);
1749
        $commentAdmin->setModelManager($modelManager);
1750
1751
        $this->assertTrue($commentAdmin->hasSubject());
1752
        $this->assertSame($comment, $commentAdmin->getSubject());
1753
1754
        $commentAdmin->setSubject(null);
1755
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1756
1757
        $this->assertFalse($commentAdmin->hasSubject());
1758
    }
1759
1760
    /**
1761
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1762
     */
1763
    public function testGetActionButtonsList(): void
1764
    {
1765
        $expected = [
1766
            'create' => [
1767
                'template' => 'Foo.html.twig',
1768
            ],
1769
        ];
1770
1771
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1772
1773
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1774
        $templateRegistry->getTemplate('button_create')->willReturn('Foo.html.twig');
1775
1776
        $admin->setTemplateRegistry($templateRegistry->reveal());
1777
1778
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1779
        $securityHandler
1780
            ->expects($this->once())
1781
            ->method('isGranted')
1782
            ->with($admin, 'CREATE', $admin)
1783
            ->willReturn(true);
1784
        $admin->setSecurityHandler($securityHandler);
1785
1786
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1787
        $routeGenerator
1788
            ->expects($this->once())
1789
            ->method('hasAdminRoute')
1790
            ->with($admin, 'create')
1791
            ->willReturn(true);
1792
        $admin->setRouteGenerator($routeGenerator);
1793
1794
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1795
    }
1796
1797
    /**
1798
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1799
     */
1800
    public function testGetActionButtonsListCreateDisabled(): void
1801
    {
1802
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1803
1804
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1805
        $securityHandler
1806
            ->expects($this->once())
1807
            ->method('isGranted')
1808
            ->with($admin, 'CREATE', $admin)
1809
            ->willReturn(false);
1810
        $admin->setSecurityHandler($securityHandler);
1811
1812
        $this->assertSame([], $admin->getActionButtons('list', null));
1813
    }
1814
1815
    /**
1816
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1817
     */
1818
    public function testGetBatchActions(): void
1819
    {
1820
        $expected = [
1821
            'delete' => [
1822
                'label' => 'action_delete',
1823
                'translation_domain' => 'SonataAdminBundle',
1824
                'ask_confirmation' => true, // by default always true
1825
            ],
1826
            'foo' => [
1827
                'label' => 'action_foo',
1828
                'translation_domain' => 'SonataAdminBundle',
1829
            ],
1830
            'bar' => [
1831
                'label' => 'batch.label_bar',
1832
                'translation_domain' => 'SonataAdminBundle',
1833
            ],
1834
            'baz' => [
1835
                'label' => 'action_baz',
1836
                'translation_domain' => 'AcmeAdminBundle',
1837
            ],
1838
        ];
1839
1840
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1841
1842
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1843
        $labelTranslatorStrategy
1844
            ->method('getLabel')
1845
            ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string {
1846
                return sprintf('%s.%s_%s', $context, $type, $label);
1847
            });
1848
1849
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1850
        $admin->setRouteBuilder($pathInfo);
1851
        $admin->setTranslationDomain('SonataAdminBundle');
1852
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1853
1854
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1855
        $routeGenerator
1856
            ->expects($this->once())
1857
            ->method('hasAdminRoute')
1858
            ->with($admin, 'delete')
1859
            ->willReturn(true);
1860
        $admin->setRouteGenerator($routeGenerator);
1861
1862
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1863
        $securityHandler
1864
            ->method('isGranted')
1865
            ->willReturnCallback(static function (AdminInterface $adminIn, string $attributes, $object = null) use ($admin): bool {
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...
1866
                return $admin === $adminIn && 'DELETE' === $attributes;
1867
            });
1868
        $admin->setSecurityHandler($securityHandler);
1869
1870
        $this->assertSame($expected, $admin->getBatchActions());
1871
    }
1872
1873
    /**
1874
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1875
     */
1876
    public function testShowMosaicButton(): void
1877
    {
1878
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1879
        $listModes = $admin->getListModes();
1880
1881
        $admin->showMosaicButton(true);
1882
1883
        $this->assertSame($listModes, $admin->getListModes());
1884
    }
1885
1886
    /**
1887
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1888
     */
1889
    public function testShowMosaicButtonHideMosaic(): void
1890
    {
1891
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1892
        $listModes = $admin->getListModes();
1893
        $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...
1894
1895
        $admin->showMosaicButton(false);
1896
1897
        $this->assertSame($expected, $admin->getListModes());
1898
    }
1899
1900
    /**
1901
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
1902
     * @dataProvider provideGetBaseRouteName
1903
     */
1904
    public function testDefaultDashboardActionsArePresent(string $objFqn, string $expected): void
1905
    {
1906
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1907
        $routerMock = $this->createMock(RouterInterface::class);
1908
1909
        $routerMock->method('generate')->willReturn('/admin/post');
1910
1911
        $routeGenerator = new DefaultRouteGenerator(
1912
            $routerMock,
1913
            new RoutesCache($this->cacheTempFolder, true)
1914
        );
1915
1916
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
1917
        $admin->setRouteBuilder($pathInfo);
1918
        $admin->setRouteGenerator($routeGenerator);
1919
        $admin->initialize();
1920
1921
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1922
        $templateRegistry->getTemplate('action_create')->willReturn('Foo.html.twig');
1923
1924
        $admin->setTemplateRegistry($templateRegistry->reveal());
1925
1926
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1927
        $securityHandler
1928
            ->method('isGranted')
1929
            ->willReturnCallback(static function (AdminInterface $adminIn, string $attributes, $object = null) use ($admin): bool {
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...
1930
                return $admin === $adminIn && ('CREATE' === $attributes || 'LIST' === $attributes);
1931
            });
1932
1933
        $admin->setSecurityHandler($securityHandler);
1934
1935
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
1936
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
1937
    }
1938
1939
    public function testDefaultFilters(): void
1940
    {
1941
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1942
1943
        $subjectId = uniqid();
1944
1945
        $request = $this->createMock(Request::class);
1946
        $query = $this->createMock(ParameterBag::class);
1947
        $query
1948
            ->method('get')
1949
            ->with($this->equalTo('filter'))
1950
            ->willReturn([
1951
                'a' => [
1952
                    'value' => 'b',
1953
                ],
1954
                'foo' => [
1955
                    'type' => '1',
1956
                    'value' => 'bar',
1957
                ],
1958
                'baz' => [
1959
                    'type' => '5',
1960
                    'value' => 'test',
1961
                ],
1962
            ]);
1963
        $request->query = $query;
1964
1965
        $request
1966
            ->method('get')
1967
            ->willReturn($subjectId);
1968
1969
        $admin->setRequest($request);
1970
1971
        $modelManager = $this->createMock(ModelManagerInterface::class);
1972
        $modelManager
1973
            ->method('getDefaultSortValues')
1974
            ->willReturn([]);
1975
1976
        $admin->setModelManager($modelManager);
1977
1978
        $this->assertSame([
1979
            '_page' => 1,
1980
            '_per_page' => 32,
1981
            'foo' => [
1982
                'type' => '1',
1983
                'value' => 'bar',
1984
            ],
1985
            'baz' => [
1986
                'type' => '5',
1987
                'value' => 'test',
1988
            ],
1989
            'a' => [
1990
                'value' => 'b',
1991
            ],
1992
        ], $admin->getFilterParameters());
1993
1994
        $this->assertTrue($admin->isDefaultFilter('foo'));
1995
        $this->assertFalse($admin->isDefaultFilter('bar'));
1996
        $this->assertFalse($admin->isDefaultFilter('a'));
1997
    }
1998
1999
    public function testGetDataSourceIterator(): void
2000
    {
2001
        $datagrid = $this->createMock(DatagridInterface::class);
2002
        $datagrid->method('buildPager');
2003
2004
        $modelManager = $this->createMock(ModelManagerInterface::class);
2005
        $modelManager->method('getExportFields')->willReturn([
2006
            'field',
2007
            'foo',
2008
            'bar',
2009
        ]);
2010
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2011
            ->with($this->equalTo($datagrid), $this->equalTo([
2012
                'Feld' => 'field',
2013
                1 => 'foo',
2014
                2 => 'bar',
2015
            ]))
2016
            ->willReturn(new ArraySourceIterator([]));
2017
2018
        $admin = $this->getMockBuilder(AbstractAdmin::class)
2019
            ->disableOriginalConstructor()
2020
            ->setMethods(['getClass', 'getDatagrid', 'getTranslationLabel', 'trans'])
2021
            ->getMockForAbstractClass();
2022
        $admin->method('getClass')->willReturn('App\Admin\MyAdmin');
2023
        $admin->method('getDatagrid')->willReturn($datagrid);
2024
        $admin->setModelManager($modelManager);
2025
2026
        $admin
2027
            ->method('getTranslationLabel')
2028
            ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string {
2029
                return sprintf('%s.%s_%s', $context, $type, $label);
2030
            });
2031
        $admin
2032
            ->method('trans')
2033
            ->willReturnCallback(static function (string $label): string {
2034
                if ('export.label_field' === $label) {
2035
                    return 'Feld';
2036
                }
2037
2038
                return $label;
2039
            });
2040
2041
        $admin->getDataSourceIterator();
2042
    }
2043
2044
    public function testCircularChildAdmin(): void
2045
    {
2046
        $this->expectException(\RuntimeException::class);
2047
        $this->expectExceptionMessage(
2048
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2049
        );
2050
2051
        $postAdmin = new PostAdmin(
2052
            'sonata.post.admin.post',
2053
            'Application\Sonata\NewsBundle\Entity\Post',
2054
            'Sonata\NewsBundle\Controller\PostAdminController'
2055
        );
2056
        $commentAdmin = new CommentAdmin(
2057
            'sonata.post.admin.comment',
2058
            'Application\Sonata\NewsBundle\Entity\Comment',
2059
            'Sonata\NewsBundle\Controller\CommentAdminController'
2060
        );
2061
        $postAdmin->addChild($commentAdmin, 'post');
2062
        $commentAdmin->addChild($postAdmin, 'comment');
2063
    }
2064
2065
    public function testCircularChildAdminTripleLevel(): void
2066
    {
2067
        $this->expectException(\RuntimeException::class);
2068
        $this->expectExceptionMessage(
2069
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2070
        );
2071
2072
        $postAdmin = new PostAdmin(
2073
            'sonata.post.admin.post',
2074
            'Application\Sonata\NewsBundle\Entity\Post',
2075
            'Sonata\NewsBundle\Controller\PostAdminController'
2076
        );
2077
        $commentAdmin = new CommentAdmin(
2078
            'sonata.post.admin.comment',
2079
            'Application\Sonata\NewsBundle\Entity\Comment',
2080
            'Sonata\NewsBundle\Controller\CommentAdminController'
2081
        );
2082
        $commentVoteAdmin = new CommentVoteAdmin(
2083
            'sonata.post.admin.comment_vote',
2084
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2085
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2086
        );
2087
        $postAdmin->addChild($commentAdmin, 'post');
2088
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2089
        $commentVoteAdmin->addChild($postAdmin, 'post');
2090
    }
2091
2092
    public function testCircularChildAdminWithItself(): void
2093
    {
2094
        $this->expectException(\RuntimeException::class);
2095
        $this->expectExceptionMessage(
2096
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2097
        );
2098
2099
        $postAdmin = new PostAdmin(
2100
            'sonata.post.admin.post',
2101
            'Application\Sonata\NewsBundle\Entity\Post',
2102
            'Sonata\NewsBundle\Controller\PostAdminController'
2103
        );
2104
        $postAdmin->addChild($postAdmin, 'post');
2105
    }
2106
2107
    public function testGetRootAncestor(): void
2108
    {
2109
        $postAdmin = new PostAdmin(
2110
            'sonata.post.admin.post',
2111
            'Application\Sonata\NewsBundle\Entity\Post',
2112
            'Sonata\NewsBundle\Controller\PostAdminController'
2113
        );
2114
        $commentAdmin = new CommentAdmin(
2115
            'sonata.post.admin.comment',
2116
            'Application\Sonata\NewsBundle\Entity\Comment',
2117
            'Sonata\NewsBundle\Controller\CommentAdminController'
2118
        );
2119
        $commentVoteAdmin = new CommentVoteAdmin(
2120
            'sonata.post.admin.comment_vote',
2121
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2122
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2123
        );
2124
2125
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2126
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2127
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2128
2129
        $postAdmin->addChild($commentAdmin, 'post');
2130
2131
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2132
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2133
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2134
2135
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2136
2137
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2138
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2139
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2140
    }
2141
2142
    public function testGetChildDepth(): void
2143
    {
2144
        $postAdmin = new PostAdmin(
2145
            'sonata.post.admin.post',
2146
            'Application\Sonata\NewsBundle\Entity\Post',
2147
            'Sonata\NewsBundle\Controller\PostAdminController'
2148
        );
2149
        $commentAdmin = new CommentAdmin(
2150
            'sonata.post.admin.comment',
2151
            'Application\Sonata\NewsBundle\Entity\Comment',
2152
            'Sonata\NewsBundle\Controller\CommentAdminController'
2153
        );
2154
        $commentVoteAdmin = new CommentVoteAdmin(
2155
            'sonata.post.admin.comment_vote',
2156
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2157
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2158
        );
2159
2160
        $this->assertSame(0, $postAdmin->getChildDepth());
2161
        $this->assertSame(0, $commentAdmin->getChildDepth());
2162
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2163
2164
        $postAdmin->addChild($commentAdmin, 'post');
2165
2166
        $this->assertSame(0, $postAdmin->getChildDepth());
2167
        $this->assertSame(1, $commentAdmin->getChildDepth());
2168
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2169
2170
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2171
2172
        $this->assertSame(0, $postAdmin->getChildDepth());
2173
        $this->assertSame(1, $commentAdmin->getChildDepth());
2174
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2175
    }
2176
2177
    public function testGetCurrentLeafChildAdmin(): void
2178
    {
2179
        $postAdmin = new PostAdmin(
2180
            'sonata.post.admin.post',
2181
            'Application\Sonata\NewsBundle\Entity\Post',
2182
            'Sonata\NewsBundle\Controller\PostAdminController'
2183
        );
2184
        $commentAdmin = new CommentAdmin(
2185
            'sonata.post.admin.comment',
2186
            'Application\Sonata\NewsBundle\Entity\Comment',
2187
            'Sonata\NewsBundle\Controller\CommentAdminController'
2188
        );
2189
        $commentVoteAdmin = new CommentVoteAdmin(
2190
            'sonata.post.admin.comment_vote',
2191
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2192
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2193
        );
2194
2195
        $postAdmin->addChild($commentAdmin, 'post');
2196
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2197
2198
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2199
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2200
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2201
2202
        $commentAdmin->setCurrentChild(true);
2203
2204
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2205
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2206
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2207
2208
        $commentVoteAdmin->setCurrentChild(true);
2209
2210
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2211
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2212
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2213
    }
2214
2215
    public function testAdminAvoidInifiniteLoop(): void
2216
    {
2217
        $this->expectNotToPerformAssertions();
2218
2219
        $formFactory = new FormFactory(new FormRegistry([], new ResolvedFormTypeFactory()));
2220
2221
        $admin = new AvoidInfiniteLoopAdmin('code', \stdClass::class, null);
2222
        $admin->setSubject(new \stdClass());
2223
2224
        $admin->setFormContractor(new FormContractor($formFactory));
2225
2226
        $admin->setShowBuilder(new ShowBuilder());
2227
2228
        $admin->setListBuilder(new ListBuilder());
2229
2230
        $pager = $this->createStub(PagerInterface::class);
2231
        $admin->setDatagridBuilder(new DatagridBuilder($formFactory, $pager));
2232
2233
        $validator = $this->createMock(ValidatorInterface::class);
2234
        $validator->method('getMetadataFor')->willReturn($this->createStub(MemberMetadata::class));
2235
        $admin->setValidator($validator);
2236
2237
        $routeGenerator = $this->createStub(RouteGeneratorInterface::class);
2238
        $routeGenerator->method('hasAdminRoute')->willReturn(false);
2239
        $admin->setRouteGenerator($routeGenerator);
2240
2241
        $admin->getForm();
2242
        $admin->getShow();
2243
        $admin->getList();
2244
        $admin->getDatagrid();
2245
    }
2246
}
2247