Completed
Pull Request — master (#6194)
by Vincent
03:04
created

AdminTest   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 2389
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 46
dl 0
loc 2389
rs 7.52
c 0
b 0
f 0

114 Methods

Rating   Name   Duplication   Size   Complexity  
A testGetRouteGenerator() 0 11 1
A testGetConfigurationPool() 0 13 1
A testGetShowBuilder() 0 11 1
A testGetListBuilder() 0 11 1
A testGetDatagridBuilder() 0 11 1
A testGetFormContractor() 0 11 1
A testGetRequest() 0 12 1
A testGetRequestWithException() 0 8 1
A testGetTranslationDomain() 0 9 1
A testGetTranslator() 0 11 1
A testGetShowGroups() 0 11 1
A testGetFormGroups() 0 11 1
A testGetMaxPageLinks() 0 9 1
A testCheckAccessThrowsAccessDeniedException() 0 24 1
A testHasAccessOnMadeUpAction() 0 10 1
A testHasAccess() 0 19 1
A testHasAccessAllowsAccess() 0 19 1
A testHasAccessAllowsAccessEditAction() 0 18 1
A testChildren() 0 22 1
A testConfigure() 0 15 1
A testConfigureWithValidParentAssociationMapping() 0 8 1
B provideGetBaseRoutePattern() 0 65 1
A testGetBaseRoutePattern() 0 5 1
A testGetBaseRoutePatternWithChildAdmin() 0 8 1
A testGetBaseRoutePatternWithTwoNestedChildAdmin() 0 18 1
A testGetBaseRoutePatternWithSpecifedPattern() 0 6 1
A testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern() 0 8 1
A testGetBaseRoutePatternWithUnreconizedClassname() 0 7 1
B provideGetBaseRouteName() 0 65 1
A testGetBaseRouteName() 0 6 1
B testGetBaseRouteNameWithChildAdmin() 0 85 1
A testGetBaseRouteNameWithUnreconizedClassname() 0 7 1
A testGetBaseRouteNameWithSpecifiedName() 0 6 1
A testGetBaseRouteNameWithChildAdminAndWithSpecifiedName() 0 8 1
A testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName() 0 22 1
A testSetUniqid() 0 9 1
A testRemoveFieldFromFormGroup() 0 26 1
A testShowMosaicButton() 0 9 1
A testShowMosaicButtonHideMosaic() 0 10 1
A testGetPerPageOptions() 0 13 2
A testGetLabelTranslatorStrategy() 0 10 1
A testGetRouteBuilder() 0 10 1
A testGetMenuFactory() 0 10 1
A testGetExtensions() 0 13 1
A testGetFilterTheme() 0 9 1
A testGetFormTheme() 0 10 1
A testGetValidator() 0 11 1
A testGetSecurityHandler() 0 10 1
A testGetSecurityInformation() 0 14 1
A testGetManagerType() 0 9 1
A testGetModelManager() 0 11 1
A testGetBaseCodeRoute() 0 22 1
A hp$0 ➔ persistFilters() 0 4 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 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 testAddSubClassIsDeprecated() 0 9 1
A testGetMaxPerPage() 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 7 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 testTrans() 0 15 1
A testTransWithMessageDomain() 0 14 1
A testTransChoice() 0 15 1
A testTransChoiceWithMessageDomain() 0 14 1
A testSetFilterPersister() 0 14 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 testGetFormWithNonCollectionParentValue() 0 10 1
A testGetFormWithCollectionParentValue() 0 20 1
A testGetFormWithArrayParentValue() 0 20 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 testDefaultDashboardActionsArePresent() 0 34 3
B testDefaultFilters() 0 59 1
A testCreateQueryLegacyCallWorks() 0 15 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
A createTagAdmin() 0 39 1

How to fix   Complexity   

Complex Class

Complex classes like AdminTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

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\Datagrid\ProxyQueryInterface;
34
use Sonata\AdminBundle\Filter\Persister\FilterPersisterInterface;
35
use Sonata\AdminBundle\Model\AuditManagerInterface;
36
use Sonata\AdminBundle\Model\ModelManagerInterface;
37
use Sonata\AdminBundle\Route\DefaultRouteGenerator;
38
use Sonata\AdminBundle\Route\PathInfoBuilder;
39
use Sonata\AdminBundle\Route\RouteGeneratorInterface;
40
use Sonata\AdminBundle\Route\RoutesCache;
41
use Sonata\AdminBundle\Security\Handler\AclSecurityHandlerInterface;
42
use Sonata\AdminBundle\Security\Handler\SecurityHandlerInterface;
43
use Sonata\AdminBundle\Templating\MutableTemplateRegistryInterface;
44
use Sonata\AdminBundle\Tests\App\Builder\DatagridBuilder;
45
use Sonata\AdminBundle\Tests\App\Builder\FormContractor;
46
use Sonata\AdminBundle\Tests\App\Builder\ListBuilder;
47
use Sonata\AdminBundle\Tests\App\Builder\ShowBuilder;
48
use Sonata\AdminBundle\Tests\Fixtures\Admin\AvoidInfiniteLoopAdmin;
49
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentAdmin;
50
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentVoteAdmin;
51
use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentWithCustomRouteAdmin;
52
use Sonata\AdminBundle\Tests\Fixtures\Admin\FieldDescription;
53
use Sonata\AdminBundle\Tests\Fixtures\Admin\FilteredAdmin;
54
use Sonata\AdminBundle\Tests\Fixtures\Admin\ModelAdmin;
55
use Sonata\AdminBundle\Tests\Fixtures\Admin\PostAdmin;
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\Tag;
62
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToString;
63
use Sonata\AdminBundle\Tests\Fixtures\Entity\FooToStringNull;
64
use Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface;
65
use Sonata\Doctrine\Adapter\AdapterInterface;
66
use Sonata\Exporter\Source\ArraySourceIterator;
67
use Symfony\Component\DependencyInjection\Container;
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\Translation\TranslatorInterface;
82
use Symfony\Component\Validator\Mapping\MemberMetadata;
83
use Symfony\Component\Validator\Mapping\PropertyMetadataInterface;
84
use Symfony\Component\Validator\Validator\ValidatorInterface;
85
86
class AdminTest extends TestCase
87
{
88
    protected $cacheTempFolder;
89
90
    protected function setUp(): void
91
    {
92
        $this->cacheTempFolder = sprintf('%s/sonata_test_route', sys_get_temp_dir());
93
        $filesystem = new Filesystem();
94
        $filesystem->remove($this->cacheTempFolder);
95
    }
96
97
    /**
98
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::__construct
99
     */
100
    public function testConstructor(): void
101
    {
102
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
103
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
104
105
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
106
        $this->assertInstanceOf(AbstractAdmin::class, $admin);
107
        $this->assertSame($class, $admin->getClass());
108
        $this->assertSame($baseControllerName, $admin->getBaseControllerName());
109
    }
110
111
    public function testGetClass(): void
112
    {
113
        $class = Post::class;
114
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
115
116
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
117
118
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
119
120
        $admin->setSubject(new BlogPost());
121
        $this->assertSame(BlogPost::class, $admin->getClass());
122
123
        $admin->setSubClasses(['foo']);
124
        $this->assertSame(BlogPost::class, $admin->getClass());
125
126
        $admin->setSubject(null);
127
        $admin->setSubClasses([]);
128
        $this->assertSame($class, $admin->getClass());
129
130
        $admin->setSubClasses(['foo' => 'bar']);
131
        $admin->setRequest(new Request(['subclass' => 'foo']));
132
        $this->assertSame('bar', $admin->getClass());
133
    }
134
135
    public function testGetClassException(): void
136
    {
137
        $this->expectException(\RuntimeException::class);
138
        $this->expectExceptionMessage('Feature not implemented: an embedded admin cannot have subclass');
139
140
        $class = 'Application\Sonata\NewsBundle\Entity\Post';
141
        $baseControllerName = 'Sonata\NewsBundle\Controller\PostAdminController';
142
143
        $admin = new PostAdmin('sonata.post.admin.post', $class, $baseControllerName);
144
        $admin->setParentFieldDescription(new FieldDescription());
145
        $admin->setSubClasses(['foo' => 'bar']);
146
        $admin->setRequest(new Request(['subclass' => 'foo']));
147
        $admin->getClass();
148
    }
149
150
    public function testCheckAccessThrowsExceptionOnMadeUpAction(): void
151
    {
152
        $admin = new PostAdmin(
153
            'sonata.post.admin.post',
154
            'Application\Sonata\NewsBundle\Entity\Post',
155
            'Sonata\NewsBundle\Controller\PostAdminController'
156
        );
157
        $this->expectException(
158
            \InvalidArgumentException::class
159
        );
160
        $this->expectExceptionMessage(
161
            'Action "made-up" could not be found'
162
        );
163
        $admin->checkAccess('made-up');
164
    }
165
166
    public function testCheckAccessThrowsAccessDeniedException(): void
167
    {
168
        $admin = new PostAdmin(
169
            'sonata.post.admin.post',
170
            'Application\Sonata\NewsBundle\Entity\Post',
171
            'Sonata\NewsBundle\Controller\PostAdminController'
172
        );
173
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
174
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
175
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
176
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
177
        $customExtension->getAccessMapping($admin)->willReturn(
178
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
179
        );
180
        $admin->addExtension($customExtension->reveal());
181
        $admin->setSecurityHandler($securityHandler->reveal());
182
        $this->expectException(
183
            AccessDeniedException::class
184
        );
185
        $this->expectExceptionMessage(
186
            'Access Denied to the action custom_action and role EXTRA_CUSTOM_ROLE'
187
        );
188
        $admin->checkAccess('custom_action');
189
    }
190
191
    public function testHasAccessOnMadeUpAction(): void
192
    {
193
        $admin = new PostAdmin(
194
            'sonata.post.admin.post',
195
            'Application\Sonata\NewsBundle\Entity\Post',
196
            'Sonata\NewsBundle\Controller\PostAdminController'
197
        );
198
199
        $this->assertFalse($admin->hasAccess('made-up'));
200
    }
201
202
    public function testHasAccess(): void
203
    {
204
        $admin = new PostAdmin(
205
            'sonata.post.admin.post',
206
            'Application\Sonata\NewsBundle\Entity\Post',
207
            'Sonata\NewsBundle\Controller\PostAdminController'
208
        );
209
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
210
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
211
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(false);
212
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
213
        $customExtension->getAccessMapping($admin)->willReturn(
214
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
215
        );
216
        $admin->addExtension($customExtension->reveal());
217
        $admin->setSecurityHandler($securityHandler->reveal());
218
219
        $this->assertFalse($admin->hasAccess('custom_action'));
220
    }
221
222
    public function testHasAccessAllowsAccess(): void
223
    {
224
        $admin = new PostAdmin(
225
            'sonata.post.admin.post',
226
            'Application\Sonata\NewsBundle\Entity\Post',
227
            'Sonata\NewsBundle\Controller\PostAdminController'
228
        );
229
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
230
        $securityHandler->isGranted($admin, 'CUSTOM_ROLE', $admin)->willReturn(true);
231
        $securityHandler->isGranted($admin, 'EXTRA_CUSTOM_ROLE', $admin)->willReturn(true);
232
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
233
        $customExtension->getAccessMapping($admin)->willReturn(
234
            ['custom_action' => ['CUSTOM_ROLE', 'EXTRA_CUSTOM_ROLE']]
235
        );
236
        $admin->addExtension($customExtension->reveal());
237
        $admin->setSecurityHandler($securityHandler->reveal());
238
239
        $this->assertTrue($admin->hasAccess('custom_action'));
240
    }
241
242
    public function testHasAccessAllowsAccessEditAction(): void
243
    {
244
        $admin = new PostAdmin(
245
            'sonata.post.admin.post',
246
            'Application\Sonata\NewsBundle\Entity\Post',
247
            'Sonata\NewsBundle\Controller\PostAdminController'
248
        );
249
        $securityHandler = $this->prophesize(SecurityHandlerInterface::class);
250
        $securityHandler->isGranted($admin, 'EDIT_ROLE', $admin)->willReturn(true);
251
        $customExtension = $this->prophesize(AbstractAdminExtension::class);
252
        $customExtension->getAccessMapping($admin)->willReturn(
253
            ['edit_action' => ['EDIT_ROLE']]
254
        );
255
        $admin->addExtension($customExtension->reveal());
256
        $admin->setSecurityHandler($securityHandler->reveal());
257
258
        $this->assertTrue($admin->hasAccess('edit_action'));
259
    }
260
261
    /**
262
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChild
263
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::addChild
264
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChild
265
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::isChild
266
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasChildren
267
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getChildren
268
     */
269
    public function testChildren(): void
270
    {
271
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
272
        $this->assertFalse($postAdmin->hasChildren());
273
        $this->assertFalse($postAdmin->hasChild('comment'));
274
275
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
276
        $postAdmin->addChild($commentAdmin, 'post');
277
278
        $this->assertTrue($postAdmin->hasChildren());
279
        $this->assertTrue($postAdmin->hasChild('sonata.post.admin.comment'));
280
281
        $this->assertSame('sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getCode());
282
        $this->assertSame('sonata.post.admin.post|sonata.post.admin.comment', $postAdmin->getChild('sonata.post.admin.comment')->getBaseCodeRoute());
283
        $this->assertSame($postAdmin, $postAdmin->getChild('sonata.post.admin.comment')->getParent());
284
        $this->assertSame('post', $commentAdmin->getParentAssociationMapping());
285
286
        $this->assertFalse($postAdmin->isChild());
287
        $this->assertTrue($commentAdmin->isChild());
288
289
        $this->assertSame(['sonata.post.admin.comment' => $commentAdmin], $postAdmin->getChildren());
290
    }
291
292
    /**
293
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::configure
294
     */
295
    public function testConfigure(): void
296
    {
297
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
298
        $this->assertNotNull($admin->getUniqid());
299
300
        $admin->initialize();
301
        $this->assertNotNull($admin->getUniqid());
302
        $this->assertSame('Post', $admin->getClassnameLabel());
303
304
        $admin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
305
        $admin->setClassnameLabel('postcomment');
306
307
        $admin->initialize();
308
        $this->assertSame('postcomment', $admin->getClassnameLabel());
309
    }
310
311
    public function testConfigureWithValidParentAssociationMapping(): void
312
    {
313
        $admin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
314
        $admin->setParentAssociationMapping('Category');
315
316
        $admin->initialize();
317
        $this->assertSame('Category', $admin->getParentAssociationMapping());
318
    }
319
320
    public function provideGetBaseRoutePattern()
321
    {
322
        return [
323
            [
324
                'Application\Sonata\NewsBundle\Entity\Post',
325
                '/sonata/news/post',
326
            ],
327
            [
328
                'Application\Sonata\NewsBundle\Document\Post',
329
                '/sonata/news/post',
330
            ],
331
            [
332
                'MyApplication\MyBundle\Entity\Post',
333
                '/myapplication/my/post',
334
            ],
335
            [
336
                'MyApplication\MyBundle\Entity\Post\Category',
337
                '/myapplication/my/post-category',
338
            ],
339
            [
340
                'MyApplication\MyBundle\Entity\Product\Category',
341
                '/myapplication/my/product-category',
342
            ],
343
            [
344
                'MyApplication\MyBundle\Entity\Other\Product\Category',
345
                '/myapplication/my/other-product-category',
346
            ],
347
            [
348
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
349
                '/cmf/foo/menu',
350
            ],
351
            [
352
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
353
                '/cmf/foo/menu',
354
            ],
355
            [
356
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
357
                '/symfony/barbar/menu',
358
            ],
359
            [
360
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
361
                '/symfony/barbar/menu-item',
362
            ],
363
            [
364
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
365
                '/cmf/foo/menu',
366
            ],
367
            [
368
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
369
                '/cmf/foo/menu',
370
            ],
371
            [
372
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
373
                '/cmf/foo/menu',
374
            ],
375
            [
376
                'AppBundle\Entity\User',
377
                '/app/user',
378
            ],
379
            [
380
                'App\Entity\User',
381
                '/app/user',
382
            ],
383
        ];
384
    }
385
386
    /**
387
     * @dataProvider provideGetBaseRoutePattern
388
     */
389
    public function testGetBaseRoutePattern(string $objFqn, string $expected): void
390
    {
391
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
392
        $this->assertSame($expected, $admin->getBaseRoutePattern());
393
    }
394
395
    /**
396
     * @dataProvider provideGetBaseRoutePattern
397
     */
398
    public function testGetBaseRoutePatternWithChildAdmin(string $objFqn, string $expected): void
399
    {
400
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
401
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
402
        $commentAdmin->setParent($postAdmin);
403
404
        $this->assertSame(sprintf('%s/{id}/comment', $expected), $commentAdmin->getBaseRoutePattern());
405
    }
406
407
    /**
408
     * @dataProvider provideGetBaseRoutePattern
409
     */
410
    public function testGetBaseRoutePatternWithTwoNestedChildAdmin(string $objFqn, string $expected): void
411
    {
412
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
413
        $commentAdmin = new CommentAdmin(
414
            'sonata.post.admin.comment',
415
            'Application\Sonata\NewsBundle\Entity\Comment',
416
            'Sonata\NewsBundle\Controller\CommentAdminController'
417
        );
418
        $commentVoteAdmin = new CommentVoteAdmin(
419
            'sonata.post.admin.comment_vote',
420
            'Application\Sonata\NewsBundle\Entity\CommentVote',
421
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
422
        );
423
        $commentAdmin->setParent($postAdmin);
424
        $commentVoteAdmin->setParent($commentAdmin);
425
426
        $this->assertSame(sprintf('%s/{id}/comment/{childId}/commentvote', $expected), $commentVoteAdmin->getBaseRoutePattern());
427
    }
428
429
    public function testGetBaseRoutePatternWithSpecifedPattern(): void
430
    {
431
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostWithCustomRouteAdminController');
432
433
        $this->assertSame('/post-custom', $postAdmin->getBaseRoutePattern());
434
    }
435
436
    public function testGetBaseRoutePatternWithChildAdminAndWithSpecifedPattern(): void
437
    {
438
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
439
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController');
440
        $commentAdmin->setParent($postAdmin);
441
442
        $this->assertSame('/sonata/news/post/{id}/comment-custom', $commentAdmin->getBaseRoutePattern());
443
    }
444
445
    public function testGetBaseRoutePatternWithUnreconizedClassname(): void
446
    {
447
        $this->expectException(\RuntimeException::class);
448
449
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
450
        $admin->getBaseRoutePattern();
451
    }
452
453
    public function provideGetBaseRouteName()
454
    {
455
        return [
456
            [
457
                'Application\Sonata\NewsBundle\Entity\Post',
458
                'admin_sonata_news_post',
459
            ],
460
            [
461
                'Application\Sonata\NewsBundle\Document\Post',
462
                'admin_sonata_news_post',
463
            ],
464
            [
465
                'MyApplication\MyBundle\Entity\Post',
466
                'admin_myapplication_my_post',
467
            ],
468
            [
469
                'MyApplication\MyBundle\Entity\Post\Category',
470
                'admin_myapplication_my_post_category',
471
            ],
472
            [
473
                'MyApplication\MyBundle\Entity\Product\Category',
474
                'admin_myapplication_my_product_category',
475
            ],
476
            [
477
                'MyApplication\MyBundle\Entity\Other\Product\Category',
478
                'admin_myapplication_my_other_product_category',
479
            ],
480
            [
481
                'Symfony\Cmf\Bundle\FooBundle\Document\Menu',
482
                'admin_cmf_foo_menu',
483
            ],
484
            [
485
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Phpcr\Menu',
486
                'admin_cmf_foo_menu',
487
            ],
488
            [
489
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu',
490
                'admin_symfony_barbar_menu',
491
            ],
492
            [
493
                'Symfony\Bundle\BarBarBundle\Doctrine\Phpcr\Menu\Item',
494
                'admin_symfony_barbar_menu_item',
495
            ],
496
            [
497
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\Orm\Menu',
498
                'admin_cmf_foo_menu',
499
            ],
500
            [
501
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\MongoDB\Menu',
502
                'admin_cmf_foo_menu',
503
            ],
504
            [
505
                'Symfony\Cmf\Bundle\FooBundle\Doctrine\CouchDB\Menu',
506
                'admin_cmf_foo_menu',
507
            ],
508
            [
509
                'AppBundle\Entity\User',
510
                'admin_app_user',
511
            ],
512
            [
513
                'App\Entity\User',
514
                'admin_app_user',
515
            ],
516
        ];
517
    }
518
519
    /**
520
     * @dataProvider provideGetBaseRouteName
521
     */
522
    public function testGetBaseRouteName(string $objFqn, string $expected): void
523
    {
524
        $admin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
525
526
        $this->assertSame($expected, $admin->getBaseRouteName());
527
    }
528
529
    /**
530
     * @group legacy
531
     * @expectedDeprecation Calling "addChild" without second argument is deprecated since sonata-project/admin-bundle 3.35 and will not be allowed in 4.0.
532
     * @dataProvider provideGetBaseRouteName
533
     */
534
    public function testGetBaseRouteNameWithChildAdmin(string $objFqn, string $expected): void
535
    {
536
        $routeGenerator = new DefaultRouteGenerator(
537
            $this->createMock(RouterInterface::class),
538
            new RoutesCache($this->cacheTempFolder, true)
539
        );
540
541
        $container = new Container();
542
        $pool = new Pool($container, 'Sonata Admin', '/path/to/pic.png');
543
544
        $pathInfo = new PathInfoBuilder($this->createMock(AuditManagerInterface::class));
545
        $postAdmin = new PostAdmin('sonata.post.admin.post', $objFqn, 'Sonata\NewsBundle\Controller\PostAdminController');
546
        $container->set('sonata.post.admin.post', $postAdmin);
547
        $postAdmin->setConfigurationPool($pool);
548
        $postAdmin->setRouteBuilder($pathInfo);
549
        $postAdmin->setRouteGenerator($routeGenerator);
550
        $postAdmin->initialize();
551
552
        $commentAdmin = new CommentAdmin(
553
            'sonata.post.admin.comment',
554
            'Application\Sonata\NewsBundle\Entity\Comment',
555
            'Sonata\NewsBundle\Controller\CommentAdminController'
556
        );
557
        $container->set('sonata.post.admin.comment', $commentAdmin);
558
        $commentAdmin->setConfigurationPool($pool);
559
        $commentAdmin->setRouteBuilder($pathInfo);
560
        $commentAdmin->setRouteGenerator($routeGenerator);
561
        $commentAdmin->initialize();
562
563
        $postAdmin->addChild($commentAdmin, 'post');
564
565
        $commentVoteAdmin = new CommentVoteAdmin(
566
            'sonata.post.admin.comment_vote',
567
            'Application\Sonata\NewsBundle\Entity\CommentVote',
568
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
569
        );
570
571
        $container->set('sonata.post.admin.comment_vote', $commentVoteAdmin);
572
        $commentVoteAdmin->setConfigurationPool($pool);
573
        $commentVoteAdmin->setRouteBuilder($pathInfo);
574
        $commentVoteAdmin->setRouteGenerator($routeGenerator);
575
        $commentVoteAdmin->initialize();
576
577
        $commentAdmin->addChild($commentVoteAdmin);
578
        $pool->setAdminServiceIds([
579
            'sonata.post.admin.post',
580
            'sonata.post.admin.comment',
581
            'sonata.post.admin.comment_vote',
582
        ]);
583
584
        $this->assertSame(sprintf('%s_comment', $expected), $commentAdmin->getBaseRouteName());
585
586
        $this->assertTrue($postAdmin->hasRoute('show'));
587
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post.show'));
588
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.show'));
589
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment|sonata.post.admin.comment_vote.show'));
590
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment.list'));
591
        $this->assertTrue($postAdmin->hasRoute('sonata.post.admin.comment|sonata.post.admin.comment_vote.list'));
592
        $this->assertFalse($postAdmin->hasRoute('sonata.post.admin.post|sonata.post.admin.comment.edit'));
593
        $this->assertFalse($commentAdmin->hasRoute('edit'));
594
        $this->assertSame('post', $commentAdmin->getParentAssociationMapping());
595
596
        /*
597
         * Test the route name from request
598
         */
599
        $postListRequest = new Request(
600
            [],
601
            [],
602
            [
603
                '_route' => sprintf('%s_list', $postAdmin->getBaseRouteName()),
604
            ]
605
        );
606
607
        $postAdmin->setRequest($postListRequest);
608
        $commentAdmin->setRequest($postListRequest);
609
610
        $this->assertTrue($postAdmin->isCurrentRoute('list'));
611
        $this->assertFalse($postAdmin->isCurrentRoute('create'));
612
        $this->assertFalse($commentAdmin->isCurrentRoute('list'));
613
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('list'));
614
        $this->assertTrue($commentAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
615
        $this->assertFalse($commentAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
616
        $this->assertTrue($commentVoteAdmin->isCurrentRoute('list', 'sonata.post.admin.post'));
617
        $this->assertFalse($commentVoteAdmin->isCurrentRoute('edit', 'sonata.post.admin.post'));
618
    }
619
620
    public function testGetBaseRouteNameWithUnreconizedClassname(): void
621
    {
622
        $this->expectException(\RuntimeException::class);
623
624
        $admin = new PostAdmin('sonata.post.admin.post', 'News\Thing\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
625
        $admin->getBaseRouteName();
626
    }
627
628
    public function testGetBaseRouteNameWithSpecifiedName(): void
629
    {
630
        $postAdmin = new PostWithCustomRouteAdmin('sonata.post.admin.post_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
631
632
        $this->assertSame('post_custom', $postAdmin->getBaseRouteName());
633
    }
634
635
    public function testGetBaseRouteNameWithChildAdminAndWithSpecifiedName(): void
636
    {
637
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'Application\Sonata\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
638
        $commentAdmin = new CommentWithCustomRouteAdmin('sonata.post.admin.comment_with_custom_route', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController');
639
        $commentAdmin->setParent($postAdmin);
640
641
        $this->assertSame('admin_sonata_news_post_comment_custom', $commentAdmin->getBaseRouteName());
642
    }
643
644
    public function testGetBaseRouteNameWithTwoNestedChildAdminAndWithSpecifiedName(): void
645
    {
646
        $postAdmin = new PostAdmin(
647
            'sonata.post.admin.post',
648
            'Application\Sonata\NewsBundle\Entity\Post',
649
            'Sonata\NewsBundle\Controller\PostAdminController'
650
        );
651
        $commentAdmin = new CommentWithCustomRouteAdmin(
652
            'sonata.post.admin.comment_with_custom_route',
653
            'Application\Sonata\NewsBundle\Entity\Comment',
654
            'Sonata\NewsBundle\Controller\CommentWithCustomRouteAdminController'
655
        );
656
        $commentVoteAdmin = new CommentVoteAdmin(
657
            'sonata.post.admin.comment_vote',
658
            'Application\Sonata\NewsBundle\Entity\CommentVote',
659
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
660
        );
661
        $commentAdmin->setParent($postAdmin);
662
        $commentVoteAdmin->setParent($commentAdmin);
663
664
        $this->assertSame('admin_sonata_news_post_comment_custom_commentvote', $commentVoteAdmin->getBaseRouteName());
665
    }
666
667
    /**
668
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setUniqid
669
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getUniqid
670
     */
671
    public function testSetUniqid(): void
672
    {
673
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
674
675
        $uniqid = uniqid();
676
        $admin->setUniqid($uniqid);
677
678
        $this->assertSame($uniqid, $admin->getUniqid());
679
    }
680
681
    public function testToString(): void
682
    {
683
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
684
685
        $s = new \stdClass();
686
687
        $this->assertNotEmpty($admin->toString($s));
688
689
        $s = new FooToString();
690
        $this->assertSame('salut', $admin->toString($s));
691
692
        // To string method is implemented, but returns null
693
        $s = new FooToStringNull();
694
        $this->assertNotEmpty($admin->toString($s));
695
696
        $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...
697
    }
698
699
    public function testIsAclEnabled(): void
700
    {
701
        $postAdmin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
702
703
        $this->assertFalse($postAdmin->isAclEnabled());
704
705
        $commentAdmin = new CommentAdmin('sonata.post.admin.comment', 'Application\Sonata\NewsBundle\Entity\Comment', 'Sonata\NewsBundle\Controller\CommentAdminController');
706
        $commentAdmin->setSecurityHandler($this->createMock(AclSecurityHandlerInterface::class));
707
        $this->assertTrue($commentAdmin->isAclEnabled());
708
    }
709
710
    /**
711
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClasses
712
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getSubClass
713
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::setSubClasses
714
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasSubClass
715
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
716
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubClass
717
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getActiveSubclassCode
718
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::getClass
719
     */
720
    public function testSubClass(): void
721
    {
722
        // NEXT_MAJOR: Remove the "@group" and "@expectedDeprecation" annotations
723
        $admin = new PostAdmin(
724
            'sonata.post.admin.post',
725
            Post::class,
726
            'Sonata\NewsBundle\Controller\PostAdminController'
727
        );
728
        $this->assertFalse($admin->hasSubClass('test'));
729
        $this->assertFalse($admin->hasActiveSubClass());
730
        $this->assertCount(0, $admin->getSubClasses());
731
        $this->assertSame(Post::class, $admin->getClass());
732
733
        // Just for the record, if there is no inheritance set, the getSubject is not used
734
        // the getSubject can also lead to some issue
735
        $admin->setSubject(new BlogPost());
736
        $this->assertSame(BlogPost::class, $admin->getClass());
737
738
        $admin->setSubClasses([
739
            'extended1' => 'NewsBundle\Entity\PostExtended1',
740
            'extended2' => 'NewsBundle\Entity\PostExtended2',
741
        ]);
742
        $this->assertFalse($admin->hasSubClass('test'));
743
        $this->assertTrue($admin->hasSubClass('extended1'));
744
        $this->assertFalse($admin->hasActiveSubClass());
745
        $this->assertCount(2, $admin->getSubClasses());
746
        $this->assertSame(
747
            BlogPost::class,
748
            $admin->getClass(),
749
            'When there is no subclass in the query the class parameter should be returned'
750
        );
751
752
        $request = new Request(['subclass' => 'extended1']);
753
        $admin->setRequest($request);
754
        $this->assertFalse($admin->hasSubClass('test'));
755
        $this->assertTrue($admin->hasSubClass('extended1'));
756
        $this->assertTrue($admin->hasActiveSubClass());
757
        $this->assertCount(2, $admin->getSubClasses());
758
        $this->assertSame(
759
            'NewsBundle\Entity\PostExtended1',
760
            $admin->getActiveSubClass(),
761
            'It should return the curently active sub class.'
762
        );
763
        $this->assertSame('extended1', $admin->getActiveSubclassCode());
764
        $this->assertSame(
765
            'NewsBundle\Entity\PostExtended1',
766
            $admin->getClass(),
767
            'getClass() should return the name of the sub class when passed through a request query parameter.'
768
        );
769
770
        $request->query->set('subclass', 'inject');
771
772
        $this->expectException(\LogicException::class);
773
        $this->expectExceptionMessage(sprintf('Admin "%s" has no active subclass.', PostAdmin::class));
774
775
        $admin->getActiveSubclassCode();
776
    }
777
778
    public function testNonExistantSubclass(): void
779
    {
780
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
781
        $admin->setModelManager($this->getMockForAbstractClass(ModelManagerInterface::class));
782
783
        $admin->setRequest(new Request(['subclass' => 'inject']));
784
785
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1', 'extended2' => 'NewsBundle\Entity\PostExtended2']);
786
787
        $this->assertTrue($admin->hasActiveSubClass());
788
789
        $this->expectException(\LogicException::class);
790
791
        $admin->getActiveSubClass();
792
    }
793
794
    /**
795
     * @covers \Sonata\AdminBundle\Admin\AbstractAdmin::hasActiveSubClass
796
     */
797
    public function testOnlyOneSubclassNeededToBeActive(): void
798
    {
799
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
800
        $admin->setSubClasses(['extended1' => 'NewsBundle\Entity\PostExtended1']);
801
        $request = new Request(['subclass' => 'extended1']);
802
        $admin->setRequest($request);
803
        $this->assertTrue($admin->hasActiveSubClass());
804
    }
805
806
    /**
807
     * @group legacy
808
     * @expectedDeprecation Method "Sonata\AdminBundle\Admin\AbstractAdmin::addSubClass" is deprecated since sonata-project/admin-bundle 3.30 and will be removed in 4.0.
809
     */
810
    public function testAddSubClassIsDeprecated(): void
811
    {
812
        $admin = new PostAdmin(
813
            'sonata.post.admin.post',
814
            Post::class,
815
            'Sonata\NewsBundle\Controller\PostAdminController'
816
        );
817
        $admin->addSubClass('whatever');
818
    }
819
820
    /**
821
     * @group legacy
822
     */
823
    public function testGetPerPageOptions(): void
824
    {
825
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
826
827
        $perPageOptions = $admin->getPerPageOptions();
828
829
        foreach ($perPageOptions as $perPage) {
830
            $this->assertSame(0, $perPage % 4);
831
        }
832
833
        $admin->setPerPageOptions([500, 1000]);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...in::setPerPageOptions() has been deprecated with message: since sonata-project/admin-bundle 3.67, to be removed in 4.0. Set custom per page options.

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

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

Loading history...
834
        $this->assertSame([500, 1000], $admin->getPerPageOptions());
835
    }
836
837
    public function testGetLabelTranslatorStrategy(): void
838
    {
839
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
840
841
        $this->assertNull($admin->getLabelTranslatorStrategy());
842
843
        $labelTranslatorStrategy = $this->createMock(LabelTranslatorStrategyInterface::class);
844
        $admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
845
        $this->assertSame($labelTranslatorStrategy, $admin->getLabelTranslatorStrategy());
846
    }
847
848
    public function testGetRouteBuilder(): void
849
    {
850
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
851
852
        $this->assertNull($admin->getRouteBuilder());
853
854
        $routeBuilder = $this->createMock(RouteBuilderInterface::class);
855
        $admin->setRouteBuilder($routeBuilder);
856
        $this->assertSame($routeBuilder, $admin->getRouteBuilder());
857
    }
858
859
    public function testGetMenuFactory(): void
860
    {
861
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
862
863
        $this->assertNull($admin->getMenuFactory());
864
865
        $menuFactory = $this->createMock(FactoryInterface::class);
866
        $admin->setMenuFactory($menuFactory);
867
        $this->assertSame($menuFactory, $admin->getMenuFactory());
868
    }
869
870
    public function testGetExtensions(): void
871
    {
872
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
873
874
        $this->assertSame([], $admin->getExtensions());
875
876
        $adminExtension1 = $this->createMock(AdminExtensionInterface::class);
877
        $adminExtension2 = $this->createMock(AdminExtensionInterface::class);
878
879
        $admin->addExtension($adminExtension1);
880
        $admin->addExtension($adminExtension2);
881
        $this->assertSame([$adminExtension1, $adminExtension2], $admin->getExtensions());
882
    }
883
884
    public function testGetFilterTheme(): void
885
    {
886
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
887
888
        $this->assertSame([], $admin->getFilterTheme());
889
890
        $admin->setFilterTheme(['FooTheme']);
891
        $this->assertSame(['FooTheme'], $admin->getFilterTheme());
892
    }
893
894
    public function testGetFormTheme(): void
895
    {
896
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
897
898
        $this->assertSame([], $admin->getFormTheme());
899
900
        $admin->setFormTheme(['FooTheme']);
901
902
        $this->assertSame(['FooTheme'], $admin->getFormTheme());
903
    }
904
905
    public function testGetValidator(): void
906
    {
907
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
908
909
        $this->assertNull($admin->getValidator());
910
911
        $validator = $this->getMockForAbstractClass(ValidatorInterface::class);
912
913
        $admin->setValidator($validator);
914
        $this->assertSame($validator, $admin->getValidator());
915
    }
916
917
    public function testGetSecurityHandler(): void
918
    {
919
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
920
921
        $this->assertNull($admin->getSecurityHandler());
922
923
        $securityHandler = $this->createMock(SecurityHandlerInterface::class);
924
        $admin->setSecurityHandler($securityHandler);
925
        $this->assertSame($securityHandler, $admin->getSecurityHandler());
926
    }
927
928
    public function testGetSecurityInformation(): void
929
    {
930
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
931
932
        $this->assertSame([], $admin->getSecurityInformation());
933
934
        $securityInformation = [
935
            'GUEST' => ['VIEW', 'LIST'],
936
            'STAFF' => ['EDIT', 'LIST', 'CREATE'],
937
        ];
938
939
        $admin->setSecurityInformation($securityInformation);
940
        $this->assertSame($securityInformation, $admin->getSecurityInformation());
941
    }
942
943
    public function testGetManagerType(): void
944
    {
945
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
946
947
        $this->assertNull($admin->getManagerType());
948
949
        $admin->setManagerType('foo_orm');
950
        $this->assertSame('foo_orm', $admin->getManagerType());
951
    }
952
953
    public function testGetModelManager(): void
954
    {
955
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
956
957
        $this->assertNull($admin->getModelManager());
958
959
        $modelManager = $this->createMock(ModelManagerInterface::class);
960
961
        $admin->setModelManager($modelManager);
962
        $this->assertSame($modelManager, $admin->getModelManager());
963
    }
964
965
    public function testGetBaseCodeRoute(): void
966
    {
967
        $postAdmin = new PostAdmin(
968
            'sonata.post.admin.post',
969
            'NewsBundle\Entity\Post',
970
            'Sonata\NewsBundle\Controller\PostAdminController'
971
        );
972
        $commentAdmin = new CommentAdmin(
973
            'sonata.post.admin.comment',
974
            'Application\Sonata\NewsBundle\Entity\Comment',
975
            'Sonata\NewsBundle\Controller\CommentAdminController'
976
        );
977
978
        $this->assertSame($postAdmin->getCode(), $postAdmin->getBaseCodeRoute());
979
980
        $postAdmin->addChild($commentAdmin, 'post');
981
982
        $this->assertSame(
983
            'sonata.post.admin.post|sonata.post.admin.comment',
984
            $commentAdmin->getBaseCodeRoute()
985
        );
986
    }
987
988
    public function testGetRouteGenerator(): void
989
    {
990
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
991
992
        $this->assertNull($admin->getRouteGenerator());
993
994
        $routeGenerator = $this->createMock(RouteGeneratorInterface::class);
995
996
        $admin->setRouteGenerator($routeGenerator);
997
        $this->assertSame($routeGenerator, $admin->getRouteGenerator());
998
    }
999
1000
    public function testGetConfigurationPool(): void
1001
    {
1002
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1003
1004
        $this->assertNull($admin->getConfigurationPool());
1005
1006
        $pool = $this->getMockBuilder(Pool::class)
1007
            ->disableOriginalConstructor()
1008
            ->getMock();
1009
1010
        $admin->setConfigurationPool($pool);
1011
        $this->assertSame($pool, $admin->getConfigurationPool());
1012
    }
1013
1014
    public function testGetShowBuilder(): void
1015
    {
1016
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1017
1018
        $this->assertNull($admin->getShowBuilder());
1019
1020
        $showBuilder = $this->createMock(ShowBuilderInterface::class);
1021
1022
        $admin->setShowBuilder($showBuilder);
1023
        $this->assertSame($showBuilder, $admin->getShowBuilder());
1024
    }
1025
1026
    public function testGetListBuilder(): void
1027
    {
1028
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1029
1030
        $this->assertNull($admin->getListBuilder());
1031
1032
        $listBuilder = $this->createMock(ListBuilderInterface::class);
1033
1034
        $admin->setListBuilder($listBuilder);
1035
        $this->assertSame($listBuilder, $admin->getListBuilder());
1036
    }
1037
1038
    public function testGetDatagridBuilder(): void
1039
    {
1040
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1041
1042
        $this->assertNull($admin->getDatagridBuilder());
1043
1044
        $datagridBuilder = $this->createMock(DatagridBuilderInterface::class);
1045
1046
        $admin->setDatagridBuilder($datagridBuilder);
1047
        $this->assertSame($datagridBuilder, $admin->getDatagridBuilder());
1048
    }
1049
1050
    public function testGetFormContractor(): void
1051
    {
1052
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1053
1054
        $this->assertNull($admin->getFormContractor());
1055
1056
        $formContractor = $this->createMock(FormContractorInterface::class);
1057
1058
        $admin->setFormContractor($formContractor);
1059
        $this->assertSame($formContractor, $admin->getFormContractor());
1060
    }
1061
1062
    public function testGetRequest(): void
1063
    {
1064
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1065
1066
        $this->assertFalse($admin->hasRequest());
1067
1068
        $request = new Request();
1069
1070
        $admin->setRequest($request);
1071
        $this->assertSame($request, $admin->getRequest());
1072
        $this->assertTrue($admin->hasRequest());
1073
    }
1074
1075
    public function testGetRequestWithException(): void
1076
    {
1077
        $this->expectException(\RuntimeException::class);
1078
        $this->expectExceptionMessage('The Request object has not been set');
1079
1080
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1081
        $admin->getRequest();
1082
    }
1083
1084
    public function testGetTranslationDomain(): void
1085
    {
1086
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1087
1088
        $this->assertSame('messages', $admin->getTranslationDomain());
1089
1090
        $admin->setTranslationDomain('foo');
1091
        $this->assertSame('foo', $admin->getTranslationDomain());
1092
    }
1093
1094
    /**
1095
     * @group legacy
1096
     */
1097
    public function testGetTranslator(): void
1098
    {
1099
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1100
1101
        $this->assertNull($admin->getTranslator());
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::getTranslator() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

Loading history...
1102
1103
        $translator = $this->createMock(TranslatorInterface::class);
1104
1105
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

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

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

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

Loading history...
1107
    }
1108
1109
    public function testGetShowGroups(): void
1110
    {
1111
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1112
1113
        $this->assertSame([], $admin->getShowGroups());
1114
1115
        $groups = ['foo', 'bar', 'baz'];
1116
1117
        $admin->setShowGroups($groups);
1118
        $this->assertSame($groups, $admin->getShowGroups());
1119
    }
1120
1121
    public function testGetFormGroups(): void
1122
    {
1123
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1124
1125
        $this->assertSame([], $admin->getFormGroups());
1126
1127
        $groups = ['foo', 'bar', 'baz'];
1128
1129
        $admin->setFormGroups($groups);
1130
        $this->assertSame($groups, $admin->getFormGroups());
1131
    }
1132
1133
    public function testGetMaxPageLinks(): void
1134
    {
1135
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1136
1137
        $this->assertSame(25, $admin->getMaxPageLinks());
1138
1139
        $admin->setMaxPageLinks(14);
1140
        $this->assertSame(14, $admin->getMaxPageLinks());
1141
    }
1142
1143
    /**
1144
     * @group legacy
1145
     */
1146
    public function testGetMaxPerPage(): void
1147
    {
1148
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1149
1150
        $this->assertSame(32, $admin->getMaxPerPage());
1151
1152
        $admin->setMaxPerPage(94);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setMaxPerPage() has been deprecated with message: since sonata-project/admin-bundle 3.67, to be removed in 4.0.

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

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

Loading history...
1153
        $this->assertSame(94, $admin->getMaxPerPage());
1154
    }
1155
1156
    public function testGetLabel(): void
1157
    {
1158
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1159
1160
        $this->assertNull($admin->getLabel());
1161
1162
        $admin->setLabel('FooLabel');
1163
        $this->assertSame('FooLabel', $admin->getLabel());
1164
    }
1165
1166
    public function testGetBaseController(): void
1167
    {
1168
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1169
1170
        $this->assertSame('Sonata\NewsBundle\Controller\PostAdminController', $admin->getBaseControllerName());
1171
1172
        $admin->setBaseControllerName('Sonata\NewsBundle\Controller\FooAdminController');
1173
        $this->assertSame('Sonata\NewsBundle\Controller\FooAdminController', $admin->getBaseControllerName());
1174
    }
1175
1176
    public function testGetIdParameter(): void
1177
    {
1178
        $postAdmin = new PostAdmin(
1179
            'sonata.post.admin.post',
1180
            'NewsBundle\Entity\Post',
1181
            'Sonata\NewsBundle\Controller\PostAdminController'
1182
        );
1183
1184
        $this->assertSame('id', $postAdmin->getIdParameter());
1185
        $this->assertFalse($postAdmin->isChild());
1186
1187
        $commentAdmin = new CommentAdmin(
1188
            'sonata.post.admin.comment',
1189
            'Application\Sonata\NewsBundle\Entity\Comment',
1190
            'Sonata\NewsBundle\Controller\CommentAdminController'
1191
        );
1192
        $commentAdmin->setParent($postAdmin);
1193
1194
        $this->assertTrue($commentAdmin->isChild());
1195
        $this->assertSame('childId', $commentAdmin->getIdParameter());
1196
1197
        $commentVoteAdmin = new CommentVoteAdmin(
1198
            'sonata.post.admin.comment_vote',
1199
            'Application\Sonata\NewsBundle\Entity\CommentVote',
1200
            'Sonata\NewsBundle\Controller\CommentVoteAdminController'
1201
        );
1202
        $commentVoteAdmin->setParent($commentAdmin);
1203
1204
        $this->assertTrue($commentVoteAdmin->isChild());
1205
        $this->assertSame('childChildId', $commentVoteAdmin->getIdParameter());
1206
    }
1207
1208
    public function testGetExportFormats(): void
1209
    {
1210
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1211
1212
        $this->assertSame(['json', 'xml', 'csv', 'xls'], $admin->getExportFormats());
1213
    }
1214
1215
    public function testGetUrlsafeIdentifier(): void
1216
    {
1217
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1218
1219
        $model = new \stdClass();
1220
1221
        $modelManager = $this->createMock(ModelManagerInterface::class);
1222
        $modelManager->expects($this->once())
1223
            ->method('getUrlSafeIdentifier')
1224
            ->with($this->equalTo($model))
1225
            ->willReturn('foo');
1226
        $admin->setModelManager($modelManager);
1227
1228
        $this->assertSame('foo', $admin->getUrlSafeIdentifier($model));
1229
    }
1230
1231
    public function testDeterminedPerPageValue(): void
1232
    {
1233
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1234
1235
        $this->assertFalse($admin->determinedPerPageValue(123));
1236
        $this->assertTrue($admin->determinedPerPageValue(16));
1237
    }
1238
1239
    public function testIsGranted(): void
1240
    {
1241
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1242
        $modelManager = $this->createStub(ModelManagerInterface::class);
1243
        $modelManager
1244
            ->method('getNormalizedIdentifier')
1245
            ->willReturnCallback(static function (?object $model = null): ?string {
1246
                return $model ? $model->id : null;
1247
            });
1248
1249
        $admin->setModelManager($modelManager);
1250
1251
        $entity1 = new \stdClass();
1252
        $entity1->id = '1';
1253
1254
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1255
        $securityHandler
1256
            ->expects($this->exactly(6))
1257
            ->method('isGranted')
1258
            ->willReturnCallback(static function (
1259
                AdminInterface $adminIn,
1260
                string $attributes,
1261
                ?object $object = null
1262
            ) use (
1263
                $admin,
1264
                $entity1
1265
            ): bool {
1266
                return $admin === $adminIn && 'FOO' === $attributes &&
1267
                    ($object === $admin || $object === $entity1);
1268
            });
1269
1270
        $admin->setSecurityHandler($securityHandler);
1271
1272
        $this->assertTrue($admin->isGranted('FOO'));
1273
        $this->assertTrue($admin->isGranted('FOO'));
1274
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1275
        $this->assertTrue($admin->isGranted('FOO', $entity1));
1276
        $this->assertFalse($admin->isGranted('BAR'));
1277
        $this->assertFalse($admin->isGranted('BAR'));
1278
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1279
        $this->assertFalse($admin->isGranted('BAR', $entity1));
1280
1281
        $entity2 = new \stdClass();
1282
        $entity2->id = '2';
1283
1284
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1285
        $this->assertFalse($admin->isGranted('BAR', $entity2));
1286
1287
        $entity3 = new \stdClass();
1288
        $entity3->id = '3';
1289
1290
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1291
        $this->assertFalse($admin->isGranted('BAR', $entity3));
1292
    }
1293
1294
    public function testSupportsPreviewMode(): void
1295
    {
1296
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1297
1298
        $this->assertFalse($admin->supportsPreviewMode());
1299
    }
1300
1301
    public function testGetPermissionsShow(): void
1302
    {
1303
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1304
1305
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_DASHBOARD));
1306
        $this->assertSame(['LIST'], $admin->getPermissionsShow(AbstractAdmin::CONTEXT_MENU));
1307
        $this->assertSame(['LIST'], $admin->getPermissionsShow('foo'));
1308
    }
1309
1310
    public function testShowIn(): void
1311
    {
1312
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1313
1314
        $securityHandler = $this->createMock(AclSecurityHandlerInterface::class);
1315
        $securityHandler
1316
            ->method('isGranted')
1317
            ->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...
1318
                return $admin === $adminIn && $attributes === ['LIST'];
1319
            });
1320
1321
        $admin->setSecurityHandler($securityHandler);
1322
1323
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_DASHBOARD));
1324
        $this->assertTrue($admin->showIn(AbstractAdmin::CONTEXT_MENU));
1325
        $this->assertTrue($admin->showIn('foo'));
1326
    }
1327
1328
    public function testGetObjectIdentifier(): void
1329
    {
1330
        $admin = new PostAdmin('sonata.post.admin.post', 'Acme\NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1331
1332
        $this->assertSame('sonata.post.admin.post', $admin->getObjectIdentifier());
1333
    }
1334
1335
    /**
1336
     * @group legacy
1337
     */
1338
    public function testTrans(): void
1339
    {
1340
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1341
        $admin->setTranslationDomain('fooMessageDomain');
1342
1343
        $translator = $this->createMock(TranslatorInterface::class);
1344
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

Loading history...
1345
1346
        $translator->expects($this->once())
1347
            ->method('trans')
1348
            ->with($this->equalTo('foo'), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1349
            ->willReturn('fooTranslated');
1350
1351
        $this->assertSame('fooTranslated', $admin->trans('foo'));
1352
    }
1353
1354
    /**
1355
     * @group legacy
1356
     */
1357
    public function testTransWithMessageDomain(): void
1358
    {
1359
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1360
1361
        $translator = $this->createMock(TranslatorInterface::class);
1362
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

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

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

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

Loading history...
1382
1383
        $translator->expects($this->once())
1384
            ->method('transChoice')
1385
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo([]), $this->equalTo('fooMessageDomain'))
1386
            ->willReturn('fooTranslated');
1387
1388
        $this->assertSame('fooTranslated', $admin->transChoice('foo', 2));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::transChoice() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

Loading history...
1389
    }
1390
1391
    /**
1392
     * @group legacy
1393
     */
1394
    public function testTransChoiceWithMessageDomain(): void
1395
    {
1396
        $admin = new PostAdmin('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'Sonata\NewsBundle\Controller\PostAdminController');
1397
1398
        $translator = $this->createMock(TranslatorInterface::class);
1399
        $admin->setTranslator($translator);
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...tAdmin::setTranslator() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

Loading history...
1400
1401
        $translator->expects($this->once())
1402
            ->method('transChoice')
1403
            ->with($this->equalTo('foo'), $this->equalTo(2), $this->equalTo(['name' => 'Andrej']), $this->equalTo('fooMessageDomain'))
1404
            ->willReturn('fooTranslated');
1405
1406
        $this->assertSame('fooTranslated', $admin->transChoice('foo', 2, ['name' => 'Andrej'], 'fooMessageDomain'));
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...actAdmin::transChoice() has been deprecated with message: since sonata-project/admin-bundle 3.9, to be removed with 4.0

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

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

Loading history...
1407
    }
1408
1409
    public function testSetFilterPersister(): void
1410
    {
1411
        $admin = new class('sonata.post.admin.post', 'NewsBundle\Entity\Post', 'SonataNewsBundle\Controller\PostAdminController') extends PostAdmin {
1412
            public function persistFilters(): bool
1413
            {
1414
                return $this->persistFilters;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\AdminBundle\Admin...tAdmin::$persistFilters has been deprecated with message: since sonata-project/admin-bundle 3.34, to be removed in 4.0.

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

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

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