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

AdminTest   F

Complexity

Total Complexity 115

Size/Duplication

Total Lines 2163
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 34

Importance

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

102 Methods

Rating   Name   Duplication   Size   Complexity  
A testRemoveFieldFromFormGroup() 0 26 1
A setUp() 0 6 1
A testConstructor() 0 10 1
A testGetClass() 0 23 1
A testGetClassException() 0 14 1
A testCheckAccessThrowsExceptionOnMadeUpAction() 0 15 1
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 57 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 testGetFilterParameters() 0 40 1
B testGetFilterFieldDescription() 0 71 4
A testGetSubjectNoRequest() 0 12 1
A testGetSideMenu() 0 24 1
A provideGetSubject() 0 10 1
A testGetSubjectFailed() 0 15 1
A testGetSubject() 0 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
        // NEXT_MAJOR: Remove the "@group" and "@expectedDeprecation" annotations
631
        $admin = new PostAdmin(
632
            'sonata.post.admin.post',
633
            Post::class,
634
            'Sonata\NewsBundle\Controller\PostAdminController'
635
        );
636
        $this->assertFalse($admin->hasSubClass('test'));
637
        $this->assertFalse($admin->hasActiveSubClass());
638
        $this->assertCount(0, $admin->getSubClasses());
639
        $this->assertSame(Post::class, $admin->getClass());
640
641
        // Just for the record, if there is no inheritance set, the getSubject is not used
642
        // the getSubject can also lead to some issue
643
        $admin->setSubject(new BlogPost());
644
        $this->assertSame(BlogPost::class, $admin->getClass());
645
646
        $admin->setSubClasses([
647
            'extended1' => 'NewsBundle\Entity\PostExtended1',
648
            'extended2' => 'NewsBundle\Entity\PostExtended2',
649
        ]);
650
        $this->assertFalse($admin->hasSubClass('test'));
651
        $this->assertTrue($admin->hasSubClass('extended1'));
652
        $this->assertFalse($admin->hasActiveSubClass());
653
        $this->assertCount(2, $admin->getSubClasses());
654
        $this->assertSame(
655
            BlogPost::class,
656
            $admin->getClass(),
657
            'When there is no subclass in the query the class parameter should be returned'
658
        );
659
660
        $request = new Request(['subclass' => 'extended1']);
661
        $admin->setRequest($request);
662
        $this->assertFalse($admin->hasSubClass('test'));
663
        $this->assertTrue($admin->hasSubClass('extended1'));
664
        $this->assertTrue($admin->hasActiveSubClass());
665
        $this->assertCount(2, $admin->getSubClasses());
666
        $this->assertSame(
667
            'NewsBundle\Entity\PostExtended1',
668
            $admin->getActiveSubClass(),
669
            'It should return the curently active sub class.'
670
        );
671
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
672
        $this->assertSame(
673
            'NewsBundle\Entity\PostExtended1',
674
            $admin->getClass(),
675
            'getClass() should return the name of the sub class when passed through a request query parameter.'
676
        );
677
678
        $request->query->set('subclass', 'inject');
679
680
        $this->expectException(\LogicException::class);
681
        $this->expectExceptionMessage(sprintf('Admin "%s" has no active subclass.', PostAdmin::class));
682
683
        $admin->getActiveSubclassCode();
684
    }
685
686
    public function testNonExistantSubclass(): void
687
    {
688
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
689
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
690
691
        $admin->setRequest(new Request(['subclass' => 'inject']));
692
693
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
694
695
        $this->assertTrue($admin->hasActiveSubClass());
696
697
        $this->expectException(\LogicException::class);
698
699
        $admin->getActiveSubClass();
700
    }
701
702
    /**
703
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
704
     */
705
    public function testOnlyOneSubclassNeededToBeActive(): void
706
    {
707
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
708
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
709
        $request = new Request(['subclass' => 'extended1']);
710
        $admin->setRequest($request);
711
        $this->assertTrue($admin->hasActiveSubClass());
712
    }
713
714
    public function testGetLabelTranslatorStrategy(): void
715
    {
716
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
717
718
        $this->assertNull($admin->getLabelTranslatorStrategy());
719
720
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
721
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
722
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
723
    }
724
725
    public function testGetRouteBuilder(): void
726
    {
727
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
728
729
        $this->assertNull($admin->getRouteBuilder());
730
731
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
732
        $admin->setRouteBuilder($routeBuilder);
733
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
734
    }
735
736
    public function testGetMenuFactory(): void
737
    {
738
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
739
740
        $this->assertNull($admin->getMenuFactory());
741
742
        $menuFactory = $this->createMock(FactoryInterface::class);
743
        $admin->setMenuFactory($menuFactory);
744
        $this->assertSame($menuFactory, $admin->getMenuFactory());
745
    }
746
747
    public function testGetExtensions(): void
748
    {
749
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
750
751
        $this->assertSame([], $admin->getExtensions());
752
753
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
754
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
755
756
        $admin->addExtension($adminExtension1);
757
        $admin->addExtension($adminExtension2);
758
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
759
    }
760
761
    public function testGetFilterTheme(): void
762
    {
763
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
764
765
        $this->assertSame([], $admin->getFilterTheme());
766
767
        $admin->setFilterTheme(['FooTheme']);
768
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
769
    }
770
771
    public function testGetFormTheme(): void
772
    {
773
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
774
775
        $this->assertSame([], $admin->getFormTheme());
776
777
        $admin->setFormTheme(['FooTheme']);
778
779
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
780
    }
781
782
    public function testGetValidator(): void
783
    {
784
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
785
786
        $this->assertNull($admin->getValidator());
787
788
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
789
790
        $admin->setValidator($validator);
791
        $this->assertSame($validator, $admin->getValidator());
792
    }
793
794
    public function testGetSecurityHandler(): void
795
    {
796
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
797
798
        $this->assertNull($admin->getSecurityHandler());
799
800
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
801
        $admin->setSecurityHandler($securityHandler);
802
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
803
    }
804
805
    public function testGetSecurityInformation(): void
806
    {
807
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
808
809
        $this->assertSame([], $admin->getSecurityInformation());
810
811
        $securityInformation = [
812
            'GUEST' => ['VIEW', 'LIST'],
813
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
814
        ];
815
816
        $admin->setSecurityInformation($securityInformation);
817
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
818
    }
819
820
    public function testGetManagerType(): void
821
    {
822
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
823
824
        $this->assertNull($admin->getManagerType());
825
826
        $admin->setManagerType('foo_orm');
827
        $this->assertSame('foo_orm', $admin->getManagerType());
828
    }
829
830
    public function testGetModelManager(): void
831
    {
832
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
833
834
        $this->assertNull($admin->getModelManager());
835
836
        $modelManager = $this->createMock(ModelManagerInterface::class);
837
838
        $admin->setModelManager($modelManager);
839
        $this->assertSame($modelManager, $admin->getModelManager());
840
    }
841
842
    public function testGetBaseCodeRoute(): void
843
    {
844
        $postAdmin = new PostAdmin(
845
            'sonata.post.admin.post',
846
            'NewsBundle\Entity\Post',
847
            'Sonata\NewsBundle\Controller\PostAdminController'
848
        );
849
        $commentAdmin = new CommentAdmin(
850
            'sonata.post.admin.comment',
851
            'Application\Sonata\NewsBundle\Entity\Comment',
852
            'Sonata\NewsBundle\Controller\CommentAdminController'
853
        );
854
855
        $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
856
857
        $postAdmin->addChild($commentAdmin, 'post');
858
859
        $this->assertSame(
860
            'sonata.post.admin.post|sonata.post.admin.comment',
861
            $commentAdmin->getBaseCodeRoute()
862
        );
863
    }
864
865
    public function testGetRouteGenerator(): void
866
    {
867
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
868
869
        $this->assertNull($admin->getRouteGenerator());
870
871
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
872
873
        $admin->setRouteGenerator($routeGenerator);
874
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
875
    }
876
877
    public function testGetConfigurationPool(): void
878
    {
879
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
880
881
        $this->assertNull($admin->getConfigurationPool());
882
883
        $pool = $this->getMockBuilder(Pool::class)
884
            ->disableOriginalConstructor()
885
            ->getMock();
886
887
        $admin->setConfigurationPool($pool);
888
        $this->assertSame($pool, $admin->getConfigurationPool());
889
    }
890
891
    public function testGetShowBuilder(): void
892
    {
893
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
894
895
        $this->assertNull($admin->getShowBuilder());
896
897
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
898
899
        $admin->setShowBuilder($showBuilder);
900
        $this->assertSame($showBuilder, $admin->getShowBuilder());
901
    }
902
903
    public function testGetListBuilder(): void
904
    {
905
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
906
907
        $this->assertNull($admin->getListBuilder());
908
909
        $listBuilder = $this->createMock(ListBuilderInterface::class);
910
911
        $admin->setListBuilder($listBuilder);
912
        $this->assertSame($listBuilder, $admin->getListBuilder());
913
    }
914
915
    public function testGetDatagridBuilder(): void
916
    {
917
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
918
919
        $this->assertNull($admin->getDatagridBuilder());
920
921
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
922
923
        $admin->setDatagridBuilder($datagridBuilder);
924
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
925
    }
926
927
    public function testGetFormContractor(): void
928
    {
929
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
930
931
        $this->assertNull($admin->getFormContractor());
932
933
        $formContractor = $this->createMock(FormContractorInterface::class);
934
935
        $admin->setFormContractor($formContractor);
936
        $this->assertSame($formContractor, $admin->getFormContractor());
937
    }
938
939
    public function testGetRequest(): void
940
    {
941
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
942
943
        $this->assertFalse($admin->hasRequest());
944
945
        $request = new Request();
946
947
        $admin->setRequest($request);
948
        $this->assertSame($request, $admin->getRequest());
949
        $this->assertTrue($admin->hasRequest());
950
    }
951
952
    public function testGetRequestWithException(): void
953
    {
954
        $this->expectException(\LogicException::class);
955
        $this->expectExceptionMessage('The Request object has not been set');
956
957
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
958
        $admin->getRequest();
959
    }
960
961
    public function testGetTranslationDomain(): void
962
    {
963
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
964
965
        $this->assertSame('messages', $admin->getTranslationDomain());
966
967
        $admin->setTranslationDomain('foo');
968
        $this->assertSame('foo', $admin->getTranslationDomain());
969
    }
970
971
    public function testGetShowGroups(): void
972
    {
973
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
974
975
        $this->assertSame([], $admin->getShowGroups());
976
977
        $groups = ['foo', 'bar', 'baz'];
978
979
        $admin->setShowGroups($groups);
980
        $this->assertSame($groups, $admin->getShowGroups());
981
    }
982
983
    public function testGetFormGroups(): void
984
    {
985
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
986
987
        $this->assertSame([], $admin->getFormGroups());
988
989
        $groups = ['foo', 'bar', 'baz'];
990
991
        $admin->setFormGroups($groups);
992
        $this->assertSame($groups, $admin->getFormGroups());
993
    }
994
995
    public function testGetMaxPageLinks(): void
996
    {
997
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
998
999
        $this->assertSame(25, $admin->getMaxPageLinks());
1000
1001
        $admin->setMaxPageLinks(14);
1002
        $this->assertSame(14, $admin->getMaxPageLinks());
1003
    }
1004
1005
    public function testGetLabel(): void
1006
    {
1007
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1008
1009
        $this->assertNull($admin->getLabel());
1010
1011
        $admin->setLabel('FooLabel');
1012
        $this->assertSame('FooLabel', $admin->getLabel());
1013
    }
1014
1015
    public function testGetBaseController(): void
1016
    {
1017
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1018
1019
        $this->assertSame('Sonata\NewsBundle\Controller\PostAdminController', $admin->getBaseControllerName());
1020
1021
        $admin->setBaseControllerName('Sonata\NewsBundle\Controller\FooAdminController');
1022
        $this->assertSame('Sonata\NewsBundle\Controller\FooAdminController', $admin->getBaseControllerName());
1023
    }
1024
1025
    public function testGetIdParameter(): void
1026
    {
1027
        $postAdmin = new PostAdmin(
1028
            'sonata.post.admin.post',
1029
            'NewsBundle\Entity\Post',
1030
            'Sonata\NewsBundle\Controller\PostAdminController'
1031
        );
1032
1033
        $this->assertSame('id', $postAdmin->getIdParameter());
1034
        $this->assertFalse($postAdmin->isChild());
1035
1036
        $commentAdmin = new CommentAdmin(
1037
            'sonata.post.admin.comment',
1038
            'Application\Sonata\NewsBundle\Entity\Comment',
1039
            'Sonata\NewsBundle\Controller\CommentAdminController'
1040
        );
1041
        $commentAdmin->setParent($postAdmin);
1042
1043
        $this->assertTrue($commentAdmin->isChild());
1044
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1045
1046
        $commentVoteAdmin = new CommentVoteAdmin(
1047
            'sonata.post.admin.comment_vote',
1048
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1049
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
1050
        );
1051
        $commentVoteAdmin->setParent($commentAdmin);
1052
1053
        $this->assertTrue($commentVoteAdmin->isChild());
1054
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1055
    }
1056
1057
    public function testGetExportFormats(): void
1058
    {
1059
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1060
1061
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1062
    }
1063
1064
    public function testGetUrlsafeIdentifier(): void
1065
    {
1066
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1067
1068
        $model = new \stdClass();
1069
1070
        $modelManager = $this->createMock(ModelManagerInterface::class);
1071
        $modelManager->expects($this->once())
1072
            ->method('getUrlSafeIdentifier')
1073
            ->with($this->equalTo($model))
1074
            ->willReturn('foo');
1075
        $admin->setModelManager($modelManager);
1076
1077
        $this->assertSame('foo', $admin->getUrlSafeIdentifier($model));
1078
    }
1079
1080
    public function testDeterminedPerPageValue(): void
1081
    {
1082
        $modelManager = $this->createStub(ModelManagerInterface::class);
1083
1084
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1085
        $admin->setModelManager($modelManager);
1086
1087
        $this->assertFalse($admin->determinedPerPageValue(123));
1088
        $this->assertTrue($admin->determinedPerPageValue(25));
1089
    }
1090
1091
    public function testIsGranted(): void
1092
    {
1093
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1094
        $modelManager = $this->createStub(ModelManagerInterface::class);
1095
        $modelManager
1096
            ->method('getNormalizedIdentifier')
1097
            ->willReturnCallback(static function (?object $model = null): ?string {
1098
                return $model ? $model->id : null;
1099
            });
1100
1101
        $admin->setModelManager($modelManager);
1102
1103
        $entity1 = new \stdClass();
1104
        $entity1->id = '1';
1105
1106
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1107
        $securityHandler
1108
            ->expects($this->exactly(6))
1109
            ->method('isGranted')
1110
            ->willReturnCallback(static function (
1111
                AdminInterface $adminIn,
1112
                string $attributes,
1113
                ?object $object = null
1114
            ) use (
1115
                $admin,
1116
                $entity1
1117
            ): bool {
1118
                return $admin === $adminIn && 'FOO' === $attributes &&
1119
                    ($object === $admin || $object === $entity1);
1120
            });
1121
1122
        $admin->setSecurityHandler($securityHandler);
1123
1124
        $this->assertTrue($admin->isGranted('FOO'));
1125
        $this->assertTrue($admin->isGranted('FOO'));
1126
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1127
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1128
        $this->assertFalse($admin->isGranted('BAR'));
1129
        $this->assertFalse($admin->isGranted('BAR'));
1130
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1131
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1132
1133
        $entity2 = new \stdClass();
1134
        $entity2->id = '2';
1135
1136
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1137
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1138
1139
        $entity3 = new \stdClass();
1140
        $entity3->id = '3';
1141
1142
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1143
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1144
    }
1145
1146
    public function testSupportsPreviewMode(): void
1147
    {
1148
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1149
1150
        $this->assertFalse($admin->supportsPreviewMode());
1151
    }
1152
1153
    public function testGetPermissionsShow(): void
1154
    {
1155
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1156
1157
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1158
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1159
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1160
    }
1161
1162
    public function testShowIn(): void
1163
    {
1164
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1165
1166
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1167
        $securityHandler
1168
            ->method('isGranted')
1169
            ->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...
1170
                return $admin === $adminIn && $attributes === ['LIST'];
1171
            });
1172
1173
        $admin->setSecurityHandler($securityHandler);
1174
1175
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1176
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1177
        $this->assertTrue($admin->showIn('foo'));
1178
    }
1179
1180
    public function testGetObjectIdentifier(): void
1181
    {
1182
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1183
1184
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1185
    }
1186
1187
    /**
1188
     * @doesNotPerformAssertions
1189
     */
1190
    public function testSetFilterPersister(): void
1191
    {
1192
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle\Controller\PostAdminController');
1193
1194
        $filterPersister = $this->createMock(FilterPersisterInterface::class);
1195
1196
        $admin->setFilterPersister($filterPersister);
1197
    }
1198
1199
    public function testGetRootCode(): void
1200
    {
1201
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1202
1203
        $this->assertSame('sonata.post.admin.post', $admin->getRootCode());
1204
1205
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'Sonata\NewsBundle\Controller\PostParentAdminController');
1206
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1207
        $parentFieldDescription->expects($this->once())
1208
            ->method('getAdmin')
1209
            ->willReturn($parentAdmin);
1210
1211
        $this->assertFalse($admin->hasParentFieldDescription());
1212
        $admin->setParentFieldDescription($parentFieldDescription);
1213
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1214
        $this->assertSame('sonata.post.admin.post.parent', $admin->getRootCode());
1215
    }
1216
1217
    public function testGetRoot(): void
1218
    {
1219
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1220
1221
        $this->assertSame($admin, $admin->getRoot());
1222
1223
        $parentAdmin = new PostAdmin('sonata.post.admin.post.parent', 'NewsBundle\Entity\PostParent', 'Sonata\NewsBundle\Controller\PostParentAdminController');
1224
        $parentFieldDescription = $this->createMock(FieldDescriptionInterface::class);
1225
        $parentFieldDescription->expects($this->once())
1226
            ->method('getAdmin')
1227
            ->willReturn($parentAdmin);
1228
1229
        $this->assertFalse($admin->hasParentFieldDescription());
1230
        $admin->setParentFieldDescription($parentFieldDescription);
1231
        $this->assertSame($parentFieldDescription, $admin->getParentFieldDescription());
1232
        $this->assertSame($parentAdmin, $admin->getRoot());
1233
    }
1234
1235
    public function testGetExportFields(): void
1236
    {
1237
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1238
1239
        $modelManager = $this->createMock(ModelManagerInterface::class);
1240
        $modelManager->expects($this->once())
1241
            ->method('getExportFields')
1242
            ->with($this->equalTo('NewsBundle\Entity\Post'))
1243
            ->willReturn(['foo', 'bar']);
1244
1245
        $admin->setModelManager($modelManager);
1246
        $this->assertSame(['foo', 'bar'], $admin->getExportFields());
1247
    }
1248
1249
    public function testGetPersistentParametersWithNoExtension(): void
1250
    {
1251
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1252
1253
        $this->assertEmpty($admin->getPersistentParameters());
1254
    }
1255
1256
    public function testGetPersistentParametersWithValidExtension(): void
1257
    {
1258
        $expected = [
1259
            'context' => 'foobar',
1260
        ];
1261
1262
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1263
1264
        $extension = $this->createMock(AdminExtensionInterface::class);
1265
        $extension->expects($this->once())->method('getPersistentParameters')->willReturn($expected);
1266
1267
        $admin->addExtension($extension);
1268
1269
        $this->assertSame($expected, $admin->getPersistentParameters());
1270
    }
1271
1272
    public function testGetNewInstanceForChildAdminWithParentValue(): void
1273
    {
1274
        $post = new Post();
1275
1276
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1277
        $postAdmin->method('getObject')->willReturn($post);
1278
1279
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1280
        $formBuilder->method('getForm')->willReturn(null);
1281
1282
        $tag = new Tag();
1283
1284
        $modelManager = $this->createStub(ModelManagerInterface::class);
1285
        $modelManager->method('getModelInstance')->willReturn($tag);
1286
1287
        $tagAdmin = new TagAdmin('admin.tag', Tag::class, 'MyBundle\MyController');
1288
        $tagAdmin->setModelManager($modelManager);
1289
        $tagAdmin->setParent($postAdmin);
1290
1291
        $request = $this->createStub(Request::class);
1292
        $tagAdmin->setRequest($request);
1293
1294
        $configurationPool = $this->getMockBuilder(Pool::class)
1295
            ->disableOriginalConstructor()
1296
            ->getMock();
1297
1298
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1299
1300
        $tagAdmin->setConfigurationPool($configurationPool);
1301
1302
        $tag = $tagAdmin->getNewInstance();
1303
1304
        $this->assertSame($post, $tag->getPost());
1305
    }
1306
1307
    public function testGetNewInstanceForChildAdminWithCollectionParentValue(): void
1308
    {
1309
        $post = new Post();
1310
1311
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1312
        $postAdmin->method('getObject')->willReturn($post);
1313
1314
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1315
        $formBuilder->method('getForm')->willReturn(null);
1316
1317
        $postCategory = new PostCategory();
1318
1319
        $modelManager = $this->createStub(ModelManagerInterface::class);
1320
        $modelManager->method('getModelInstance')->willReturn($postCategory);
1321
1322
        $postCategoryAdmin = new PostCategoryAdmin('admin.post_category', PostCategoryAdmin::class, 'MyBundle\MyController');
1323
        $postCategoryAdmin->setModelManager($modelManager);
1324
        $postCategoryAdmin->setParent($postAdmin);
1325
1326
        $request = $this->createStub(Request::class);
1327
        $postCategoryAdmin->setRequest($request);
1328
1329
        $configurationPool = $this->getMockBuilder(Pool::class)
1330
            ->disableOriginalConstructor()
1331
            ->getMock();
1332
1333
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1334
1335
        $postCategoryAdmin->setConfigurationPool($configurationPool);
1336
1337
        $postCategory = $postCategoryAdmin->getNewInstance();
1338
1339
        $this->assertInstanceOf(Collection::class, $postCategory->getPosts());
1340
        $this->assertCount(1, $postCategory->getPosts());
1341
        $this->assertContains($post, $postCategory->getPosts());
1342
    }
1343
1344
    public function testGetNewInstanceForEmbededAdminWithParentValue(): void
1345
    {
1346
        $post = new Post();
1347
1348
        $postAdmin = $this->getMockBuilder(PostAdmin::class)->disableOriginalConstructor()->getMock();
1349
        $postAdmin->method('getObject')->willReturn($post);
1350
1351
        $formBuilder = $this->createStub(FormBuilderInterface::class);
1352
        $formBuilder->method('getForm')->willReturn(null);
1353
1354
        $parentField = $this->createStub(FieldDescriptionInterface::class);
1355
        $parentField->method('getAdmin')->willReturn($postAdmin);
1356
        $parentField->method('getParentAssociationMappings')->willReturn([]);
1357
        $parentField->method('getAssociationMapping')->willReturn(['fieldName' => 'tag', 'mappedBy' => 'post']);
1358
1359
        $tag = new Tag();
1360
1361
        $modelManager = $this->createStub(ModelManagerInterface::class);
1362
        $modelManager->method('getModelInstance')->willReturn($tag);
1363
1364
        $tagAdmin = new TagAdmin('admin.tag', Tag::class, 'MyBundle\MyController');
1365
        $tagAdmin->setModelManager($modelManager);
1366
        $tagAdmin->setParentFieldDescription($parentField);
1367
1368
        $request = $this->createStub(Request::class);
1369
        $tagAdmin->setRequest($request);
1370
1371
        $configurationPool = $this->getMockBuilder(Pool::class)
1372
            ->disableOriginalConstructor()
1373
            ->getMock();
1374
1375
        $configurationPool->method('getPropertyAccessor')->willReturn(PropertyAccess::createPropertyAccessor());
1376
1377
        $tagAdmin->setConfigurationPool($configurationPool);
1378
1379
        $tag = $tagAdmin->getNewInstance();
1380
1381
        $this->assertSame($post, $tag->getPost());
1382
    }
1383
1384
    public function testFormAddPostSubmitEventForPreValidation(): void
1385
    {
1386
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', \stdClass::class, 'Sonata\FooBundle\Controller\ModelAdminController');
1387
        $object = new \stdClass();
1388
1389
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1390
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1391
1392
        $validator = $this->createMock(ValidatorInterface::class);
1393
        $validator
1394
                ->method('getMetadataFor')
1395
                ->willReturn($this->createMock(MemberMetadata::class));
1396
        $modelAdmin->setValidator($validator);
1397
1398
        $modelManager = $this->createMock(ModelManagerInterface::class);
1399
        $modelManager
1400
            ->method('getNewFieldDescriptionInstance')
1401
            ->willReturn(new FieldDescription());
1402
        $modelAdmin->setModelManager($modelManager);
1403
1404
        // a Admin class to test that preValidate is called
1405
        $testAdminPreValidate = $this->createMock(AbstractAdmin::class);
1406
        $testAdminPreValidate->expects($this->once())
1407
                ->method('preValidate')
1408
                ->with($this->identicalTo($object));
1409
1410
        $event = $this->createMock(FormEvent::class);
1411
        $event
1412
                ->method('getData')
1413
                ->willReturn($object);
1414
1415
        $formBuild = $this->createMock(FormBuilder::class);
1416
        $formBuild->expects($this->once())
1417
                ->method('addEventListener')
1418
                ->with(
1419
                    $this->identicalTo(FormEvents::POST_SUBMIT),
1420
                    $this->callback(static function ($callback) use ($testAdminPreValidate, $event): bool {
1421
                        if (\is_callable($callback)) {
1422
                            $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...
1423
                            $closure($event);
1424
1425
                            return true;
1426
                        }
1427
1428
                        return false;
1429
                    }),
1430
                    $this->greaterThan(0)
1431
                );
1432
1433
        $formContractor = $this->createMock(FormContractorInterface::class);
1434
        $formContractor
1435
                ->method('getDefaultOptions')
1436
                ->willReturn([]);
1437
        $formContractor
1438
                ->method('getFormBuilder')
1439
                ->willReturn($formBuild);
1440
1441
        $modelAdmin->setFormContractor($formContractor);
1442
        $modelAdmin->setSubject($object);
1443
        $modelAdmin->defineFormBuilder($formBuild);
1444
        $modelAdmin->getForm();
1445
    }
1446
1447
    public function testCanAddInlineValidationOnlyForGenericMetadata(): void
1448
    {
1449
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', \stdClass::class, 'Sonata\FooBundle\Controller\ModelAdminController');
1450
        $object = new \stdClass();
1451
1452
        $labelTranslatorStrategy = $this->createStub(LabelTranslatorStrategyInterface::class);
1453
        $modelAdmin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1454
1455
        $validator = $this->createStub(ValidatorInterface::class);
1456
        $metadata = $this->createStub(PropertyMetadataInterface::class);
1457
        $validator
1458
            ->method('getMetadataFor')
1459
            ->willReturn($metadata);
1460
        $modelAdmin->setValidator($validator);
1461
1462
        $modelManager = $this->createStub(ModelManagerInterface::class);
1463
        $modelManager
1464
            ->method('getNewFieldDescriptionInstance')
1465
            ->willReturn(new FieldDescription());
1466
        $modelAdmin->setModelManager($modelManager);
1467
1468
        $event = $this->createStub(FormEvent::class);
1469
        $event
1470
            ->method('getData')
1471
            ->willReturn($object);
1472
1473
        $formBuild = $this->createStub(FormBuilder::class);
1474
1475
        $formContractor = $this->createStub(FormContractorInterface::class);
1476
        $formContractor
1477
            ->method('getDefaultOptions')
1478
            ->willReturn([]);
1479
        $formContractor
1480
            ->method('getFormBuilder')
1481
            ->willReturn($formBuild);
1482
1483
        $modelAdmin->setFormContractor($formContractor);
1484
        $modelAdmin->setSubject($object);
1485
1486
        $this->expectException(\RuntimeException::class);
1487
        $this->expectExceptionMessage(
1488
            sprintf(
1489
                'Cannot add inline validator for stdClass because its metadata is an instance of %s instead of Symfony\Component\Validator\Mapping\GenericMetadata',
1490
                \get_class($metadata)
1491
            )
1492
        );
1493
1494
        $modelAdmin->defineFormBuilder($formBuild);
1495
    }
1496
1497
    public function testRemoveFieldFromFormGroup(): void
1498
    {
1499
        $formGroups = [
1500
            'foobar' => [
1501
                'fields' => [
1502
                    'foo' => 'foo',
1503
                    'bar' => 'bar',
1504
                ],
1505
            ],
1506
        ];
1507
1508
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1509
        $admin->setFormGroups($formGroups);
1510
1511
        $admin->removeFieldFromFormGroup('foo');
1512
        $this->assertSame($admin->getFormGroups(), [
1513
            'foobar' => [
1514
                'fields' => [
1515
                    'bar' => 'bar',
1516
                ],
1517
            ],
1518
        ]);
1519
1520
        $admin->removeFieldFromFormGroup('bar');
1521
        $this->assertSame($admin->getFormGroups(), []);
1522
    }
1523
1524
    public function testGetFilterParameters(): void
1525
    {
1526
        $authorId = uniqid();
1527
1528
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1529
1530
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
1531
        $commentAdmin->setParentAssociationMapping('post.author');
1532
        $commentAdmin->setParent($postAdmin);
1533
1534
        $request = $this->createMock(Request::class);
1535
        $query = $this->createMock(ParameterBag::class);
1536
        $query
1537
            ->method('get')
1538
            ->willReturn([
1539
                'filter' => [
1540
                    '_page' => '1',
1541
                    '_per_page' => '32',
1542
                ],
1543
            ]);
1544
1545
        $request->query = $query;
1546
        $request
1547
            ->method('get')
1548
            ->willReturn($authorId);
1549
1550
        $commentAdmin->setRequest($request);
1551
1552
        $modelManager = $this->createMock(ModelManagerInterface::class);
1553
        $modelManager
1554
            ->method('getDefaultSortValues')
1555
            ->willReturn([]);
1556
1557
        $commentAdmin->setModelManager($modelManager);
1558
1559
        $parameters = $commentAdmin->getFilterParameters();
1560
1561
        $this->assertTrue(isset($parameters['post__author']));
1562
        $this->assertSame(['value' => $authorId], $parameters['post__author']);
1563
    }
1564
1565
    public function testGetFilterFieldDescription(): void
1566
    {
1567
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1568
1569
        $fooFieldDescription = new FieldDescription();
1570
        $barFieldDescription = new FieldDescription();
1571
        $bazFieldDescription = new FieldDescription();
1572
1573
        $modelManager = $this->createMock(ModelManagerInterface::class);
1574
        $modelManager->expects($this->exactly(3))
1575
            ->method('getNewFieldDescriptionInstance')
1576
            ->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...
1577
                switch ($name) {
1578
                    case 'foo':
1579
                        $fieldDescription = $fooFieldDescription;
1580
1581
                        break;
1582
1583
                    case 'bar':
1584
                        $fieldDescription = $barFieldDescription;
1585
1586
                        break;
1587
1588
                    case 'baz':
1589
                        $fieldDescription = $bazFieldDescription;
1590
1591
                        break;
1592
1593
                    default:
1594
                        throw new \RuntimeException(sprintf('Unknown filter name "%s"', $name));
1595
                        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...
1596
                }
1597
1598
                $fieldDescription->setName($name);
1599
1600
                return $fieldDescription;
1601
            });
1602
1603
        $modelAdmin->setModelManager($modelManager);
1604
1605
        $pager = $this->createMock(PagerInterface::class);
1606
1607
        $datagrid = $this->createMock(DatagridInterface::class);
1608
        $datagrid->expects($this->once())
1609
            ->method('getPager')
1610
            ->willReturn($pager);
1611
1612
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1613
        $datagridBuilder->expects($this->once())
1614
            ->method('getBaseDatagrid')
1615
            ->with($this->identicalTo($modelAdmin), [])
1616
            ->willReturn($datagrid);
1617
1618
        $datagridBuilder->expects($this->exactly(3))
1619
            ->method('addFilter')
1620
            ->willReturnCallback(static function ($datagrid, $type, $fieldDescription, AdminInterface $admin): void {
1621
                $admin->addFilterFieldDescription($fieldDescription->getName(), $fieldDescription);
1622
                $fieldDescription->mergeOption('field_options', ['required' => false]);
1623
            });
1624
1625
        $modelAdmin->setDatagridBuilder($datagridBuilder);
1626
1627
        $this->assertSame(['foo' => $fooFieldDescription, 'bar' => $barFieldDescription, 'baz' => $bazFieldDescription], $modelAdmin->getFilterFieldDescriptions());
1628
        $this->assertFalse($modelAdmin->hasFilterFieldDescription('fooBar'));
1629
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('foo'));
1630
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('bar'));
1631
        $this->assertTrue($modelAdmin->hasFilterFieldDescription('baz'));
1632
        $this->assertSame($fooFieldDescription, $modelAdmin->getFilterFieldDescription('foo'));
1633
        $this->assertSame($barFieldDescription, $modelAdmin->getFilterFieldDescription('bar'));
1634
        $this->assertSame($bazFieldDescription, $modelAdmin->getFilterFieldDescription('baz'));
1635
    }
1636
1637
    public function testGetSubjectNoRequest(): void
1638
    {
1639
        $modelManager = $this->createMock(ModelManagerInterface::class);
1640
        $modelManager
1641
            ->expects($this->never())
1642
            ->method('find');
1643
1644
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1645
        $admin->setModelManager($modelManager);
1646
1647
        $this->assertFalse($admin->hasSubject());
1648
    }
1649
1650
    public function testGetSideMenu(): void
1651
    {
1652
        $item = $this->createMock(ItemInterface::class);
1653
        $item
1654
            ->expects($this->once())
1655
            ->method('setChildrenAttribute')
1656
            ->with('class', 'nav navbar-nav');
1657
        $item
1658
            ->expects($this->once())
1659
            ->method('setExtra')
1660
            ->with('translation_domain', 'foo_bar_baz');
1661
1662
        $menuFactory = $this->createMock(FactoryInterface::class);
1663
        $menuFactory
1664
            ->expects($this->once())
1665
            ->method('createItem')
1666
            ->willReturn($item);
1667
1668
        $modelAdmin = new ModelAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1669
        $modelAdmin->setMenuFactory($menuFactory);
1670
        $modelAdmin->setTranslationDomain('foo_bar_baz');
1671
1672
        $modelAdmin->getSideMenu('foo');
1673
    }
1674
1675
    /**
1676
     * @return array
1677
     */
1678
    public function provideGetSubject()
1679
    {
1680
        return [
1681
            [23],
1682
            ['azerty'],
1683
            ['4f69bbb5f14a13347f000092'],
1684
            ['0779ca8d-e2be-11e4-ac58-0242ac11000b'],
1685
            [sprintf('123%smy_type', AdapterInterface::ID_SEPARATOR)], // composite keys are supported
1686
        ];
1687
    }
1688
1689
    /**
1690
     * @dataProvider provideGetSubject
1691
     */
1692
    public function testGetSubjectFailed($id): void
1693
    {
1694
        $modelManager = $this->createMock(ModelManagerInterface::class);
1695
        $modelManager
1696
            ->expects($this->once())
1697
            ->method('find')
1698
            ->with('NewsBundle\Entity\Post', $id)
1699
            ->willReturn(null); // entity not found
1700
1701
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1702
        $admin->setModelManager($modelManager);
1703
1704
        $admin->setRequest(new Request(['id' => $id]));
1705
        $this->assertFalse($admin->hasSubject());
1706
    }
1707
1708
    /**
1709
     * @dataProvider provideGetSubject
1710
     */
1711
    public function testGetSubject($id): void
1712
    {
1713
        $model = new Post();
1714
1715
        $modelManager = $this->createMock(ModelManagerInterface::class);
1716
        $modelManager
1717
            ->expects($this->once())
1718
            ->method('find')
1719
            ->with('NewsBundle\Entity\Post', $id)
1720
            ->willReturn($model);
1721
1722
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1723
        $admin->setModelManager($modelManager);
1724
1725
        $admin->setRequest(new Request(['id' => $id]));
1726
        $this->assertTrue($admin->hasSubject());
1727
        $this->assertSame($model, $admin->getSubject());
1728
        $this->assertSame($model, $admin->getSubject()); // model manager must be used only once
1729
    }
1730
1731
    public function testGetSubjectWithParentDescription(): void
1732
    {
1733
        $adminId = 1;
1734
1735
        $comment = new Comment();
1736
1737
        $modelManager = $this->createMock(ModelManagerInterface::class);
1738
        $modelManager
1739
            ->method('find')
1740
            ->with('NewsBundle\Entity\Comment', $adminId)
1741
            ->willReturn($comment);
1742
1743
        $request = new Request(['id' => $adminId]);
1744
1745
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1746
        $postAdmin->setRequest($request);
1747
1748
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
1749
        $commentAdmin->setRequest($request);
1750
        $commentAdmin->setModelManager($modelManager);
1751
1752
        $this->assertTrue($commentAdmin->hasSubject());
1753
        $this->assertSame($comment, $commentAdmin->getSubject());
1754
1755
        $commentAdmin->setSubject(null);
1756
        $commentAdmin->setParentFieldDescription(new FieldDescription());
1757
1758
        $this->assertFalse($commentAdmin->hasSubject());
1759
    }
1760
1761
    /**
1762
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1763
     */
1764
    public function testGetActionButtonsList(): void
1765
    {
1766
        $expected = [
1767
            'create' => [
1768
                'template' => 'Foo.html.twig',
1769
            ],
1770
        ];
1771
1772
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1773
1774
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1775
        $templateRegistry->getTemplate('button_create')->willReturn('Foo.html.twig');
1776
1777
        $admin->setTemplateRegistry($templateRegistry->reveal());
1778
1779
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1780
        $securityHandler
1781
            ->expects($this->once())
1782
            ->method('isGranted')
1783
            ->with($admin, 'CREATE', $admin)
1784
            ->willReturn(true);
1785
        $admin->setSecurityHandler($securityHandler);
1786
1787
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1788
        $routeGenerator
1789
            ->expects($this->once())
1790
            ->method('hasAdminRoute')
1791
            ->with($admin, 'create')
1792
            ->willReturn(true);
1793
        $admin->setRouteGenerator($routeGenerator);
1794
1795
        $this->assertSame($expected, $admin->getActionButtons('list', null));
1796
    }
1797
1798
    /**
1799
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureActionButtons
1800
     */
1801
    public function testGetActionButtonsListCreateDisabled(): void
1802
    {
1803
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1804
1805
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1806
        $securityHandler
1807
            ->expects($this->once())
1808
            ->method('isGranted')
1809
            ->with($admin, 'CREATE', $admin)
1810
            ->willReturn(false);
1811
        $admin->setSecurityHandler($securityHandler);
1812
1813
        $this->assertSame([], $admin->getActionButtons('list', null));
1814
    }
1815
1816
    /**
1817
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configureBatchActions
1818
     */
1819
    public function testGetBatchActions(): void
1820
    {
1821
        $expected = [
1822
            'delete' => [
1823
                'label' => 'action_delete',
1824
                'translation_domain' => 'SonataAdminBundle',
1825
                'ask_confirmation' => true, // by default always true
1826
            ],
1827
            'foo' => [
1828
                'label' => 'action_foo',
1829
                'translation_domain' => 'SonataAdminBundle',
1830
            ],
1831
            'bar' => [
1832
                'label' => 'batch.label_bar',
1833
                'translation_domain' => 'SonataAdminBundle',
1834
            ],
1835
            'baz' => [
1836
                'label' => 'action_baz',
1837
                'translation_domain' => 'AcmeAdminBundle',
1838
            ],
1839
        ];
1840
1841
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1842
1843
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
1844
        $labelTranslatorStrategy
1845
            ->method('getLabel')
1846
            ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string {
1847
                return sprintf('%s.%s_%s', $context, $type, $label);
1848
            });
1849
1850
        $admin = new PostAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1851
        $admin->setRouteBuilder($pathInfo);
1852
        $admin->setTranslationDomain('SonataAdminBundle');
1853
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
1854
1855
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
1856
        $routeGenerator
1857
            ->expects($this->once())
1858
            ->method('hasAdminRoute')
1859
            ->with($admin, 'delete')
1860
            ->willReturn(true);
1861
        $admin->setRouteGenerator($routeGenerator);
1862
1863
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1864
        $securityHandler
1865
            ->method('isGranted')
1866
            ->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...
1867
                return $admin === $adminIn && 'DELETE' === $attributes;
1868
            });
1869
        $admin->setSecurityHandler($securityHandler);
1870
1871
        $this->assertSame($expected, $admin->getBatchActions());
1872
    }
1873
1874
    /**
1875
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1876
     */
1877
    public function testShowMosaicButton(): void
1878
    {
1879
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1880
        $listModes = $admin->getListModes();
1881
1882
        $admin->showMosaicButton(true);
1883
1884
        $this->assertSame($listModes, $admin->getListModes());
1885
    }
1886
1887
    /**
1888
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::showMosaicButton
1889
     */
1890
    public function testShowMosaicButtonHideMosaic(): void
1891
    {
1892
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1893
        $listModes = $admin->getListModes();
1894
        $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...
1895
1896
        $admin->showMosaicButton(false);
1897
1898
        $this->assertSame($expected, $admin->getListModes());
1899
    }
1900
1901
    /**
1902
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getDashboardActions
1903
     * @dataProvider provideGetBaseRouteName
1904
     */
1905
    public function testDefaultDashboardActionsArePresent(string $objFqn, string $expected): void
1906
    {
1907
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
1908
        $routerMock = $this->createMock(RouterInterface::class);
1909
1910
        $routerMock->method('generate')->willReturn('/admin/post');
1911
1912
        $routeGenerator = new DefaultRouteGenerator(
1913
            $routerMock,
1914
            new RoutesCache($this->cacheTempFolder, true)
1915
        );
1916
1917
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
1918
        $admin->setRouteBuilder($pathInfo);
1919
        $admin->setRouteGenerator($routeGenerator);
1920
        $admin->initialize();
1921
1922
        $templateRegistry = $this->prophesize(MutableTemplateRegistryInterface::class);
1923
        $templateRegistry->getTemplate('action_create')->willReturn('Foo.html.twig');
1924
1925
        $admin->setTemplateRegistry($templateRegistry->reveal());
1926
1927
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
1928
        $securityHandler
1929
            ->method('isGranted')
1930
            ->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...
1931
                return $admin === $adminIn && ('CREATE' === $attributes || 'LIST' === $attributes);
1932
            });
1933
1934
        $admin->setSecurityHandler($securityHandler);
1935
1936
        $this->assertArrayHasKey('list', $admin->getDashboardActions());
1937
        $this->assertArrayHasKey('create', $admin->getDashboardActions());
1938
    }
1939
1940
    public function testDefaultFilters(): void
1941
    {
1942
        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'Sonata\FooBundle\Controller\ModelAdminController');
1943
1944
        $subjectId = uniqid();
1945
1946
        $request = $this->createMock(Request::class);
1947
        $query = $this->createMock(ParameterBag::class);
1948
        $query
1949
            ->method('get')
1950
            ->with($this->equalTo('filter'))
1951
            ->willReturn([
1952
                'a' => [
1953
                    'value' => 'b',
1954
                ],
1955
                'foo' => [
1956
                    'type' => '1',
1957
                    'value' => 'bar',
1958
                ],
1959
                'baz' => [
1960
                    'type' => '5',
1961
                    'value' => 'test',
1962
                ],
1963
            ]);
1964
        $request->query = $query;
1965
1966
        $request
1967
            ->method('get')
1968
            ->willReturn($subjectId);
1969
1970
        $admin->setRequest($request);
1971
1972
        $modelManager = $this->createMock(ModelManagerInterface::class);
1973
        $modelManager
1974
            ->method('getDefaultSortValues')
1975
            ->willReturn([]);
1976
1977
        $admin->setModelManager($modelManager);
1978
1979
        $this->assertSame([
1980
            '_page' => 1,
1981
            '_per_page' => 32,
1982
            'foo' => [
1983
                'type' => '1',
1984
                'value' => 'bar',
1985
            ],
1986
            'baz' => [
1987
                'type' => '5',
1988
                'value' => 'test',
1989
            ],
1990
            'a' => [
1991
                'value' => 'b',
1992
            ],
1993
        ], $admin->getFilterParameters());
1994
1995
        $this->assertTrue($admin->isDefaultFilter('foo'));
1996
        $this->assertFalse($admin->isDefaultFilter('bar'));
1997
        $this->assertFalse($admin->isDefaultFilter('a'));
1998
    }
1999
2000
    public function testGetDataSourceIterator(): void
2001
    {
2002
        $datagrid = $this->createMock(DatagridInterface::class);
2003
        $datagrid->method('buildPager');
2004
2005
        $modelManager = $this->createMock(ModelManagerInterface::class);
2006
        $modelManager->method('getExportFields')->willReturn([
2007
            'field',
2008
            'foo',
2009
            'bar',
2010
        ]);
2011
        $modelManager->expects($this->once())->method('getDataSourceIterator')
2012
            ->with($this->equalTo($datagrid), $this->equalTo([
2013
                'Feld' => 'field',
2014
                1 => 'foo',
2015
                2 => 'bar',
2016
            ]))
2017
            ->willReturn(new ArraySourceIterator([]));
2018
2019
        $admin = $this->getMockBuilder(AbstractAdmin::class)
2020
            ->disableOriginalConstructor()
2021
            ->setMethods(['getClass', 'getDatagrid', 'getTranslationLabel', 'trans'])
2022
            ->getMockForAbstractClass();
2023
        $admin->method('getClass')->willReturn('App\Admin\MyAdmin');
2024
        $admin->method('getDatagrid')->willReturn($datagrid);
2025
        $admin->setModelManager($modelManager);
2026
2027
        $admin
2028
            ->method('getTranslationLabel')
2029
            ->willReturnCallback(static function (string $label, string $context = '', string $type = ''): string {
2030
                return sprintf('%s.%s_%s', $context, $type, $label);
2031
            });
2032
        $admin
2033
            ->method('trans')
2034
            ->willReturnCallback(static function (string $label): string {
2035
                if ('export.label_field' === $label) {
2036
                    return 'Feld';
2037
                }
2038
2039
                return $label;
2040
            });
2041
2042
        $admin->getDataSourceIterator();
2043
    }
2044
2045
    public function testCircularChildAdmin(): void
2046
    {
2047
        $this->expectException(\RuntimeException::class);
2048
        $this->expectExceptionMessage(
2049
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment` admin.'
2050
        );
2051
2052
        $postAdmin = new PostAdmin(
2053
            'sonata.post.admin.post',
2054
            'Application\Sonata\NewsBundle\Entity\Post',
2055
            'Sonata\NewsBundle\Controller\PostAdminController'
2056
        );
2057
        $commentAdmin = new CommentAdmin(
2058
            'sonata.post.admin.comment',
2059
            'Application\Sonata\NewsBundle\Entity\Comment',
2060
            'Sonata\NewsBundle\Controller\CommentAdminController'
2061
        );
2062
        $postAdmin->addChild($commentAdmin, 'post');
2063
        $commentAdmin->addChild($postAdmin, 'comment');
2064
    }
2065
2066
    public function testCircularChildAdminTripleLevel(): void
2067
    {
2068
        $this->expectException(\RuntimeException::class);
2069
        $this->expectExceptionMessage(
2070
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.comment_vote` admin.'
2071
        );
2072
2073
        $postAdmin = new PostAdmin(
2074
            'sonata.post.admin.post',
2075
            'Application\Sonata\NewsBundle\Entity\Post',
2076
            'Sonata\NewsBundle\Controller\PostAdminController'
2077
        );
2078
        $commentAdmin = new CommentAdmin(
2079
            'sonata.post.admin.comment',
2080
            'Application\Sonata\NewsBundle\Entity\Comment',
2081
            'Sonata\NewsBundle\Controller\CommentAdminController'
2082
        );
2083
        $commentVoteAdmin = new CommentVoteAdmin(
2084
            'sonata.post.admin.comment_vote',
2085
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2086
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2087
        );
2088
        $postAdmin->addChild($commentAdmin, 'post');
2089
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2090
        $commentVoteAdmin->addChild($postAdmin, 'post');
2091
    }
2092
2093
    public function testCircularChildAdminWithItself(): void
2094
    {
2095
        $this->expectException(\RuntimeException::class);
2096
        $this->expectExceptionMessage(
2097
            'Circular reference detected! The child admin `sonata.post.admin.post` is already in the parent tree of the `sonata.post.admin.post` admin.'
2098
        );
2099
2100
        $postAdmin = new PostAdmin(
2101
            'sonata.post.admin.post',
2102
            'Application\Sonata\NewsBundle\Entity\Post',
2103
            'Sonata\NewsBundle\Controller\PostAdminController'
2104
        );
2105
        $postAdmin->addChild($postAdmin, 'post');
2106
    }
2107
2108
    public function testGetRootAncestor(): void
2109
    {
2110
        $postAdmin = new PostAdmin(
2111
            'sonata.post.admin.post',
2112
            'Application\Sonata\NewsBundle\Entity\Post',
2113
            'Sonata\NewsBundle\Controller\PostAdminController'
2114
        );
2115
        $commentAdmin = new CommentAdmin(
2116
            'sonata.post.admin.comment',
2117
            'Application\Sonata\NewsBundle\Entity\Comment',
2118
            'Sonata\NewsBundle\Controller\CommentAdminController'
2119
        );
2120
        $commentVoteAdmin = new CommentVoteAdmin(
2121
            'sonata.post.admin.comment_vote',
2122
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2123
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2124
        );
2125
2126
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2127
        $this->assertSame($commentAdmin, $commentAdmin->getRootAncestor());
2128
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2129
2130
        $postAdmin->addChild($commentAdmin, 'post');
2131
2132
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2133
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2134
        $this->assertSame($commentVoteAdmin, $commentVoteAdmin->getRootAncestor());
2135
2136
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2137
2138
        $this->assertSame($postAdmin, $postAdmin->getRootAncestor());
2139
        $this->assertSame($postAdmin, $commentAdmin->getRootAncestor());
2140
        $this->assertSame($postAdmin, $commentVoteAdmin->getRootAncestor());
2141
    }
2142
2143
    public function testGetChildDepth(): void
2144
    {
2145
        $postAdmin = new PostAdmin(
2146
            'sonata.post.admin.post',
2147
            'Application\Sonata\NewsBundle\Entity\Post',
2148
            'Sonata\NewsBundle\Controller\PostAdminController'
2149
        );
2150
        $commentAdmin = new CommentAdmin(
2151
            'sonata.post.admin.comment',
2152
            'Application\Sonata\NewsBundle\Entity\Comment',
2153
            'Sonata\NewsBundle\Controller\CommentAdminController'
2154
        );
2155
        $commentVoteAdmin = new CommentVoteAdmin(
2156
            'sonata.post.admin.comment_vote',
2157
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2158
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2159
        );
2160
2161
        $this->assertSame(0, $postAdmin->getChildDepth());
2162
        $this->assertSame(0, $commentAdmin->getChildDepth());
2163
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2164
2165
        $postAdmin->addChild($commentAdmin, 'post');
2166
2167
        $this->assertSame(0, $postAdmin->getChildDepth());
2168
        $this->assertSame(1, $commentAdmin->getChildDepth());
2169
        $this->assertSame(0, $commentVoteAdmin->getChildDepth());
2170
2171
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2172
2173
        $this->assertSame(0, $postAdmin->getChildDepth());
2174
        $this->assertSame(1, $commentAdmin->getChildDepth());
2175
        $this->assertSame(2, $commentVoteAdmin->getChildDepth());
2176
    }
2177
2178
    public function testGetCurrentLeafChildAdmin(): void
2179
    {
2180
        $postAdmin = new PostAdmin(
2181
            'sonata.post.admin.post',
2182
            'Application\Sonata\NewsBundle\Entity\Post',
2183
            'Sonata\NewsBundle\Controller\PostAdminController'
2184
        );
2185
        $commentAdmin = new CommentAdmin(
2186
            'sonata.post.admin.comment',
2187
            'Application\Sonata\NewsBundle\Entity\Comment',
2188
            'Sonata\NewsBundle\Controller\CommentAdminController'
2189
        );
2190
        $commentVoteAdmin = new CommentVoteAdmin(
2191
            'sonata.post.admin.comment_vote',
2192
            'Application\Sonata\NewsBundle\Entity\CommentVote',
2193
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
2194
        );
2195
2196
        $postAdmin->addChild($commentAdmin, 'post');
2197
        $commentAdmin->addChild($commentVoteAdmin, 'comment');
2198
2199
        $this->assertNull($postAdmin->getCurrentLeafChildAdmin());
2200
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2201
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2202
2203
        $commentAdmin->setCurrentChild(true);
2204
2205
        $this->assertSame($commentAdmin, $postAdmin->getCurrentLeafChildAdmin());
2206
        $this->assertNull($commentAdmin->getCurrentLeafChildAdmin());
2207
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2208
2209
        $commentVoteAdmin->setCurrentChild(true);
2210
2211
        $this->assertSame($commentVoteAdmin, $postAdmin->getCurrentLeafChildAdmin());
2212
        $this->assertSame($commentVoteAdmin, $commentAdmin->getCurrentLeafChildAdmin());
2213
        $this->assertNull($commentVoteAdmin->getCurrentLeafChildAdmin());
2214
    }
2215
2216
    public function testAdminAvoidInifiniteLoop(): void
2217
    {
2218
        $this->expectNotToPerformAssertions();
2219
2220
        $formFactory = new FormFactory(new FormRegistry([], new ResolvedFormTypeFactory()));
2221
2222
        $admin = new AvoidInfiniteLoopAdmin('code', \stdClass::class, null);
2223
        $admin->setSubject(new \stdClass());
2224
2225
        $admin->setFormContractor(new FormContractor($formFactory));
2226
2227
        $admin->setShowBuilder(new ShowBuilder());
2228
2229
        $admin->setListBuilder(new ListBuilder());
2230
2231
        $pager = $this->createStub(PagerInterface::class);
2232
        $admin->setDatagridBuilder(new DatagridBuilder($formFactory, $pager));
2233
2234
        $validator = $this->createMock(ValidatorInterface::class);
2235
        $validator->method('getMetadataFor')->willReturn($this->createStub(MemberMetadata::class));
2236
        $admin->setValidator($validator);
2237
2238
        $routeGenerator = $this->createStub(RouteGeneratorInterface::class);
2239
        $routeGenerator->method('hasAdminRoute')->willReturn(false);
2240
        $admin->setRouteGenerator($routeGenerator);
2241
2242
        $admin->getForm();
2243
        $admin->getShow();
2244
        $admin->getList();
2245
        $admin->getDatagrid();
2246
    }
2247
}
2248