Completed
Pull Request — master (#4831)
by Jordi Sala
10:38 queued 05:56
created

HelperControllerTest::setUp()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
cc 2
eloc 15
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\AdminBundle\Tests\Controller;
13
14
use PHPUnit\Framework\TestCase;
15
use Psr\Log\LoggerInterface;
16
use Sonata\AdminBundle\Admin\AbstractAdmin;
17
use Sonata\AdminBundle\Admin\AdminHelper;
18
use Sonata\AdminBundle\Admin\AdminInterface;
19
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
20
use Sonata\AdminBundle\Admin\Pool;
21
use Sonata\AdminBundle\Controller\HelperController;
22
use Sonata\AdminBundle\Datagrid\DatagridInterface;
23
use Sonata\AdminBundle\Datagrid\Pager;
24
use Sonata\AdminBundle\Model\ModelManagerInterface;
25
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo;
26
use Sonata\AdminBundle\Twig\Extension\SonataAdminExtension;
27
use Sonata\CoreBundle\Model\Metadata;
28
use Symfony\Bridge\Twig\AppVariable;
29
use Symfony\Bridge\Twig\Extension\FormExtension;
30
use Symfony\Bridge\Twig\Form\TwigRenderer;
31
use Symfony\Bridge\Twig\Form\TwigRendererInterface;
32
use Symfony\Component\DependencyInjection\ContainerInterface;
33
use Symfony\Component\Form\Command\DebugCommand;
34
use Symfony\Component\Form\Form;
35
use Symfony\Component\Form\FormBuilder;
36
use Symfony\Component\Form\FormConfigInterface;
37
use Symfony\Component\Form\FormRenderer;
38
use Symfony\Component\Form\FormView;
39
use Symfony\Component\HttpFoundation\Request;
40
use Symfony\Component\HttpFoundation\Response;
41
use Symfony\Component\Translation\TranslatorInterface;
42
use Symfony\Component\Validator\ConstraintViolation;
43
use Symfony\Component\Validator\ConstraintViolationList;
44
use Symfony\Component\Validator\Validator\ValidatorInterface;
45
46
class AdminControllerHelper_Foo
0 ignored issues
show
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
47
{
48
    private $bar;
49
50
    public function getAdminTitle()
51
    {
52
        return 'foo';
53
    }
54
55
    public function setEnabled($value)
0 ignored issues
show
Unused Code introduced by
The parameter $value 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...
56
    {
57
    }
58
59
    public function setBar(AdminControllerHelper_Bar $bar)
60
    {
61
        $this->bar = $bar;
62
    }
63
64
    public function getBar()
65
    {
66
        return $this->bar;
67
    }
68
}
69
70
class AdminControllerHelper_Bar
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
71
{
72
    public function getAdminTitle()
73
    {
74
        return 'bar';
75
    }
76
77
    public function setEnabled($value)
0 ignored issues
show
Unused Code introduced by
The parameter $value 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...
78
    {
79
    }
80
81
    public function getEnabled()
82
    {
83
    }
84
}
85
86
class HelperControllerTest extends TestCase
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
87
{
88
    /**
89
     * @var AdminInterface
90
     */
91
    private $admin;
92
93
    /**
94
     * @var HelperController
95
     */
96
    private $controller;
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    protected function setUp()
102
    {
103
        $container = $this->createMock(ContainerInterface::class);
104
        $pool = new Pool($container, 'title', 'logo.png');
105
        $pool->setAdminServiceIds(['foo.admin']);
106
107
        $this->admin = $this->createMock(AbstractAdmin::class);
108
109
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
110
        $helper = new AdminHelper($pool);
111
        $validator = $this->createMock(ValidatorInterface::class);
112
        $this->controller = new HelperController($twig, $pool, $helper, $validator);
113
114
        $container->expects($this->any())
115
            ->method('get')
116
            ->will($this->returnCallback(function ($id) {
117
                switch ($id) {
118
                    case 'foo.admin':
119
                        return $this->admin;
120
                }
121
            }));
122
    }
123
124
    public function testgetShortObjectDescriptionActionInvalidAdmin()
125
    {
126
        $this->expectException(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class);
127
128
        $container = $this->createMock(ContainerInterface::class);
129
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
130
        $request = new Request([
131
            'code' => 'sonata.post.admin',
132
            'objectId' => 42,
133
            'uniqid' => 'asdasd123',
134
        ]);
135
        $pool = new Pool($container, 'title', 'logo');
136
        $pool->setAdminServiceIds(['sonata.post.admin']);
137
        $helper = new AdminHelper($pool);
138
        $validator = $this->createMock(ValidatorInterface::class);
139
        $controller = new HelperController($twig, $pool, $helper, $validator);
140
141
        $controller->getShortObjectDescriptionAction($request);
142
    }
143
144
    /**
145
     * @exceptionMessage Invalid format
146
     */
147
    public function testgetShortObjectDescriptionActionObjectDoesNotExist()
148
    {
149
        $this->expectException(\RuntimeException::class);
150
151
        $admin = $this->createMock(AdminInterface::class);
152
        $admin->expects($this->once())->method('setUniqid');
153
        $admin->expects($this->once())->method('getObject')->will($this->returnValue(false));
154
155
        $container = $this->createMock(ContainerInterface::class);
156
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
157
158
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
159
        $request = new Request([
160
            'code' => 'sonata.post.admin',
161
            'objectId' => 42,
162
            'uniqid' => 'asdasd123',
163
        ]);
164
165
        $pool = new Pool($container, 'title', 'logo');
166
        $pool->setAdminServiceIds(['sonata.post.admin']);
167
168
        $helper = new AdminHelper($pool);
169
170
        $validator = $this->createMock(ValidatorInterface::class);
171
        $controller = new HelperController($twig, $pool, $helper, $validator);
172
173
        $controller->getShortObjectDescriptionAction($request);
174
    }
175
176
    public function testgetShortObjectDescriptionActionEmptyObjectId()
177
    {
178
        $admin = $this->createMock(AdminInterface::class);
179
        $admin->expects($this->once())->method('setUniqid');
180
        $admin->expects($this->once())->method('getObject')->with($this->identicalTo(null))->will($this->returnValue(false));
181
182
        $container = $this->createMock(ContainerInterface::class);
183
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
184
185
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
186
        $request = new Request([
187
            'code' => 'sonata.post.admin',
188
            'objectId' => '',
189
            'uniqid' => 'asdasd123',
190
            '_format' => 'html',
191
        ]);
192
193
        $pool = new Pool($container, 'title', 'logo');
194
        $pool->setAdminServiceIds(['sonata.post.admin']);
195
196
        $helper = new AdminHelper($pool);
197
198
        $validator = $this->createMock(ValidatorInterface::class);
199
        $controller = new HelperController($twig, $pool, $helper, $validator);
200
201
        $controller->getShortObjectDescriptionAction($request);
202
    }
203
204
    public function testgetShortObjectDescriptionActionObject()
205
    {
206
        $mockTemplate = 'AdminHelperTest:mock-short-object-description.html.twig';
207
208
        $admin = $this->createMock(AdminInterface::class);
209
        $admin->expects($this->once())->method('setUniqid');
210
        $admin->expects($this->once())->method('getTemplate')->will($this->returnValue($mockTemplate));
211
        $admin->expects($this->once())->method('getObject')->will($this->returnValue(new AdminControllerHelper_Foo()));
212
        $admin->expects($this->once())->method('toString')->will($this->returnValue('bar'));
213
        $admin->expects($this->once())->method('generateObjectUrl')->will($this->returnCallback(function ($type, $object, $parameters = []) {
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...
Unused Code introduced by
The parameter $parameters 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...
214
            if ('edit' != $type) {
215
                return 'invalid name';
216
            }
217
218
            return '/ok/url';
219
        }));
220
221
        $container = $this->createMock(ContainerInterface::class);
222
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
223
224
        $twig = $this->getMockBuilder(\Twig_Environment::class)->disableOriginalConstructor()->getMock();
225
226
        $twig->expects($this->once())->method('render')
227
            ->with($mockTemplate)
228
            ->will($this->returnCallback(function ($templateName, $templateParams) {
229
                return sprintf('<a href="%s" target="new">%s</a>', $templateParams['admin']->generateObjectUrl('edit', $templateParams['object']), $templateParams['description']);
230
            }));
231
232
        $request = new Request([
233
            'code' => 'sonata.post.admin',
234
            'objectId' => 42,
235
            'uniqid' => 'asdasd123',
236
            '_format' => 'html',
237
        ]);
238
239
        $pool = new Pool($container, 'title', 'logo');
240
        $pool->setAdminServiceIds(['sonata.post.admin']);
241
242
        $helper = new AdminHelper($pool);
243
244
        $validator = $this->createMock(ValidatorInterface::class);
245
246
        $controller = new HelperController($twig, $pool, $helper, $validator);
247
248
        $response = $controller->getShortObjectDescriptionAction($request);
249
250
        $expected = '<a href="/ok/url" target="new">bar</a>';
251
        $this->assertSame($expected, $response->getContent());
252
    }
253
254
    public function testsetObjectFieldValueAction()
255
    {
256
        $object = new AdminControllerHelper_Foo();
257
258
        $fieldDescription = $this->createMock(FieldDescriptionInterface::class);
259
        $fieldDescription->expects($this->once())->method('getOption')->will($this->returnValue(true));
260
261
        $admin = $this->createMock(AbstractAdmin::class);
262
        $admin->expects($this->once())->method('getObject')->will($this->returnValue($object));
263
        $admin->expects($this->once())->method('hasAccess')->will($this->returnValue(true));
264
        $admin->expects($this->once())->method('getListFieldDescription')->will($this->returnValue($fieldDescription));
265
        $fieldDescription->expects($this->exactly(2))->method('getAdmin')->will($this->returnValue($admin));
266
267
        $container = $this->createMock(ContainerInterface::class);
268
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
269
270
        $pool = new Pool($container, 'title', 'logo');
271
        $pool->setAdminServiceIds(['sonata.post.admin']);
272
273
        $adminExtension = new SonataAdminExtension(
274
            $pool,
275
            $this->createMock(LoggerInterface::class),
276
            $this->createMock(TranslatorInterface::class)
277
        );
278
279
        // NEXT_MAJOR: Remove this check when dropping support for twig < 2
280
        if (method_exists(\Twig_LoaderInterface::class, 'getSourceContext')) {
281
            $loader = $this->createMock(\Twig_LoaderInterface::class);
282
        } else {
283
            $loader = $this->createMock([\Twig_LoaderInterface::class, \Twig_SourceContextLoaderInterface::class]);
284
        }
285
        $loader->method('getSourceContext')->will($this->returnValue(new \Twig_Source('<foo />', 'foo')));
286
287
        $twig = new \Twig_Environment($loader);
288
        $twig->addExtension($adminExtension);
289
        $request = new Request([
290
            'code' => 'sonata.post.admin',
291
            'objectId' => 42,
292
            'field' => 'enabled',
293
            'value' => 1,
294
            'context' => 'list',
295
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
296
297
        $helper = new AdminHelper($pool);
298
299
        $validator = $this->createMock(ValidatorInterface::class);
300
301
        $validator
302
            ->expects($this->once())
303
            ->method('validate')
304
            ->with($object)
305
            ->will($this->returnValue(new ConstraintViolationList([])))
306
        ;
307
308
        $controller = new HelperController($twig, $pool, $helper, $validator);
309
310
        $response = $controller->setObjectFieldValueAction($request);
311
312
        $this->assertEquals(200, $response->getStatusCode());
313
    }
314
315
    public function testappendFormFieldElementAction()
316
    {
317
        $object = new AdminControllerHelper_Foo();
318
319
        $modelManager = $this->createMock(ModelManagerInterface::class);
320
        $modelManager->expects($this->once())->method('find')->will($this->returnValue($object));
321
322
        $mockTheme = $this->getMockBuilder(FormView::class)
323
            ->disableOriginalConstructor()
324
            ->getMock();
325
326
        $admin = $this->createMock(AdminInterface::class);
327
        $admin->expects($this->once())->method('getModelManager')->will($this->returnValue($modelManager));
328
        $admin->expects($this->once())->method('setRequest');
329
        $admin->expects($this->once())->method('setSubject');
330
        $admin->expects($this->once())->method('getFormTheme')->will($this->returnValue($mockTheme));
331
332
        $container = $this->createMock(ContainerInterface::class);
333
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
334
335
        $mockRenderer = $this->getMockBuilder(TwigRendererInterface::class)
336
            ->disableOriginalConstructor()
337
            ->getMock();
338
339
        $mockRenderer->expects($this->once())
340
            ->method('searchAndRenderBlock')
341
            ->will($this->returnValue(new Response()));
342
343
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
344
345
        // Remove the condition when dropping sf < 3.2
346
        if (method_exists(AppVariable::class, 'getToken')) {
347
            $twig->addExtension(new FormExtension());
348
            $runtimeLoader = $this
349
                ->getMockBuilder(\Twig_RuntimeLoaderInterface::class)
350
                ->getMock();
351
352
            // Remove the condition when dropping sf < 3.4
353
            if (!class_exists(DebugCommand::class)) {
354
                $runtimeLoader->expects($this->once())
355
                    ->method('load')
356
                    ->with($this->equalTo(TwigRenderer::class))
357
                    ->will($this->returnValue($mockRenderer));
358
            } else {
359
                $runtimeLoader->expects($this->once())
360
                    ->method('load')
361
                    ->with($this->equalTo(FormRenderer::class))
362
                    ->will($this->returnValue($mockRenderer));
363
            }
364
365
            $twig->addRuntimeLoader($runtimeLoader);
366
        } else {
367
            $twig->addExtension(new FormExtension($mockRenderer));
0 ignored issues
show
Unused Code introduced by
The call to FormExtension::__construct() has too many arguments starting with $mockRenderer.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
368
        }
369
370
        $request = new Request([
371
            'code' => 'sonata.post.admin',
372
            'objectId' => 42,
373
            'field' => 'enabled',
374
            'value' => 1,
375
            'context' => 'list',
376
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST']);
377
378
        $pool = new Pool($container, 'title', 'logo');
379
        $pool->setAdminServiceIds(['sonata.post.admin']);
380
381
        $validator = $this->createMock(ValidatorInterface::class);
382
383
        $mockView = $this->getMockBuilder(FormView::class)
384
            ->disableOriginalConstructor()
385
            ->getMock();
386
387
        $mockForm = $this->getMockBuilder(Form::class)
388
            ->disableOriginalConstructor()
389
            ->getMock();
390
        $mockForm->expects($this->once())
391
            ->method('createView')
392
            ->will($this->returnValue($mockView));
393
394
        $helper = $this->getMockBuilder(AdminHelper::class)
395
            ->setMethods(['appendFormFieldElement', 'getChildFormView'])
396
            ->setConstructorArgs([$pool])
397
            ->getMock();
398
        $helper->expects($this->once())->method('appendFormFieldElement')->will($this->returnValue([
399
            $this->createMock(FieldDescriptionInterface::class),
400
            $mockForm,
401
        ]));
402
        $helper->expects($this->once())->method('getChildFormView')->will($this->returnValue($mockView));
403
404
        $controller = new HelperController($twig, $pool, $helper, $validator);
405
        $response = $controller->appendFormFieldElementAction($request);
406
407
        $this->isInstanceOf(Response::class, $response);
408
    }
409
410
    public function testRetrieveFormFieldElementAction()
411
    {
412
        $object = new AdminControllerHelper_Foo();
413
414
        $request = new Request([
415
            'code' => 'sonata.post.admin',
416
            'objectId' => 42,
417
            'field' => 'enabled',
418
            'value' => 1,
419
            'context' => 'list',
420
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST']);
421
422
        $modelManager = $this->createMock(ModelManagerInterface::class);
423
        $modelManager->expects($this->once())->method('find')->will($this->returnValue($object));
424
425
        $mockView = $this->getMockBuilder(FormView::class)
426
            ->disableOriginalConstructor()
427
            ->getMock();
428
429
        $mockForm = $this->getMockBuilder(Form::class)
430
            ->disableOriginalConstructor()
431
            ->getMock();
432
433
        $mockForm->expects($this->once())
434
            ->method('setData')
435
            ->with($object);
436
437
        $mockForm->expects($this->once())
438
            ->method('handleRequest')
439
            ->with($request);
440
441
        $mockForm->expects($this->once())
442
            ->method('createView')
443
            ->will($this->returnValue($mockView));
444
445
        $formBuilder = $this->getMockBuilder(FormBuilder::class)
446
            ->disableOriginalConstructor()
447
            ->getMock();
448
        $formBuilder->expects($this->once())->method('getForm')->will($this->returnValue($mockForm));
449
450
        $admin = $this->createMock(AdminInterface::class);
451
        $admin->expects($this->once())->method('getModelManager')->will($this->returnValue($modelManager));
452
        $admin->expects($this->once())->method('getFormBuilder')->will($this->returnValue($formBuilder));
453
454
        $container = $this->createMock(ContainerInterface::class);
455
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
456
457
        $mockRenderer = $this->getMockBuilder(TwigRendererInterface::class)
458
            ->disableOriginalConstructor()
459
            ->getMock();
460
461
        $mockRenderer->expects($this->once())
462
            ->method('searchAndRenderBlock')
463
            ->will($this->returnValue(new Response()));
464
465
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
466
467
        // Remove the condition when dropping sf < 3.2
468
        if (method_exists(AppVariable::class, 'getToken')) {
469
            $twig->addExtension(new FormExtension());
470
            $runtimeLoader = $this
471
                ->getMockBuilder(\Twig_RuntimeLoaderInterface::class)
472
                ->getMock();
473
474
            // Remove the condition when dropping sf < 3.4
475
            if (!class_exists(DebugCommand::class)) {
476
                $runtimeLoader->expects($this->once())
477
                    ->method('load')
478
                    ->with($this->equalTo(TwigRenderer::class))
479
                    ->will($this->returnValue($mockRenderer));
480
            } else {
481
                $runtimeLoader->expects($this->once())
482
                    ->method('load')
483
                    ->with($this->equalTo(FormRenderer::class))
484
                    ->will($this->returnValue($mockRenderer));
485
            }
486
487
            $twig->addRuntimeLoader($runtimeLoader);
488
        } else {
489
            $twig->addExtension(new FormExtension($mockRenderer));
0 ignored issues
show
Unused Code introduced by
The call to FormExtension::__construct() has too many arguments starting with $mockRenderer.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
490
        }
491
492
        $pool = new Pool($container, 'title', 'logo');
493
        $pool->setAdminServiceIds(['sonata.post.admin']);
494
495
        $validator = $this->createMock(ValidatorInterface::class);
496
497
        $helper = $this->getMockBuilder(AdminHelper::class)
498
            ->setMethods(['getChildFormView'])
499
            ->setConstructorArgs([$pool])
500
            ->getMock();
501
        $helper->expects($this->once())->method('getChildFormView')->will($this->returnValue($mockView));
502
503
        $controller = new HelperController($twig, $pool, $helper, $validator);
504
        $response = $controller->retrieveFormFieldElementAction($request);
505
506
        $this->isInstanceOf(Response::class, $response);
507
    }
508
509
    public function testSetObjectFieldValueActionWithViolations()
510
    {
511
        $bar = new AdminControllerHelper_Bar();
512
513
        $object = new AdminControllerHelper_Foo();
514
        $object->setBar($bar);
515
516
        $fieldDescription = $this->createMock(FieldDescriptionInterface::class);
517
        $fieldDescription->expects($this->once())->method('getOption')->will($this->returnValue(true));
518
519
        $admin = $this->createMock(AbstractAdmin::class);
520
        $admin->expects($this->once())->method('getObject')->will($this->returnValue($object));
521
        $admin->expects($this->once())->method('hasAccess')->will($this->returnValue(true));
522
        $admin->expects($this->once())->method('getListFieldDescription')->will($this->returnValue($fieldDescription));
523
524
        $container = $this->createMock(ContainerInterface::class);
525
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
526
527
        $twig = new \Twig_Environment($this->createMock(\Twig_LoaderInterface::class));
528
        $request = new Request([
529
            'code' => 'sonata.post.admin',
530
            'objectId' => 42,
531
            'field' => 'bar.enabled',
532
            'value' => 1,
533
            'context' => 'list',
534
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
535
536
        $pool = new Pool($container, 'title', 'logo');
537
        $pool->setAdminServiceIds(['sonata.post.admin']);
538
539
        $helper = new AdminHelper($pool);
540
541
        $violations = new ConstraintViolationList([
542
            new ConstraintViolation('error1', null, [], null, 'enabled', null),
543
            new ConstraintViolation('error2', null, [], null, 'enabled', null),
544
        ]);
545
546
        $validator = $this->createMock(ValidatorInterface::class);
547
548
        $validator
549
            ->expects($this->once())
550
            ->method('validate')
551
            ->with($bar)
552
            ->will($this->returnValue($violations))
553
        ;
554
555
        $controller = new HelperController($twig, $pool, $helper, $validator);
556
557
        $response = $controller->setObjectFieldValueAction($request);
558
559
        $this->assertEquals(400, $response->getStatusCode());
560
        $this->assertSame(json_encode("error1\nerror2"), $response->getContent());
561
    }
562
563
    /**
564
     * @exceptionMessage Invalid format
565
     */
566
    public function testRetrieveAutocompleteItemsActionNotGranted()
567
    {
568
        $this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class);
569
570
        $this->admin->expects($this->exactly(2))
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
571
            ->method('hasAccess')
572
            ->will($this->returnCallback(function ($operation) {
573
                if ('create' == $operation || 'edit' == $operation) {
574
                    return false;
575
                }
576
            }));
577
578
        $request = new Request([
579
            'admin_code' => 'foo.admin',
580
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
581
582
        $this->controller->retrieveAutocompleteItemsAction($request);
583
    }
584
585
    /**
586
     * @exceptionMessage Autocomplete list can`t be retrieved because the form element is disabled or read_only.
587
     */
588
    public function testRetrieveAutocompleteItemsActionDisabledFormelememt()
589
    {
590
        $this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class);
591
592
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
593
            ->method('hasAccess')
594
            ->with('create')
595
            ->will($this->returnValue(true));
596
597
        $fieldDescription = $this->createMock(FieldDescriptionInterface::class);
598
599
        $fieldDescription->expects($this->once())
600
            ->method('getTargetEntity')
601
            ->will($this->returnValue(Foo::class));
602
603
        $fieldDescription->expects($this->once())
604
            ->method('getName')
605
            ->will($this->returnValue('barField'));
606
607
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
608
            ->method('getFormFieldDescriptions')
609
            ->will($this->returnValue(null));
610
611
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
612
            ->method('getFormFieldDescription')
613
            ->with('barField')
614
            ->will($this->returnValue($fieldDescription));
615
616
        $form = $this->getMockBuilder(Form::class)
617
            ->disableOriginalConstructor()
618
            ->getMock();
619
620
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
621
            ->method('getForm')
622
            ->will($this->returnValue($form));
623
624
        $formType = $this->getMockBuilder(Form::class)
625
            ->disableOriginalConstructor()
626
            ->getMock();
627
628
        $form->expects($this->once())
629
            ->method('get')
630
            ->with('barField')
631
            ->will($this->returnValue($formType));
632
633
        $formConfig = $this->getMockBuilder(FormConfigInterface::class)
634
            ->disableOriginalConstructor()
635
            ->getMock();
636
637
        $formType->expects($this->once())
638
            ->method('getConfig')
639
            ->will($this->returnValue($formConfig));
640
641
        $formConfig->expects($this->once())
642
            ->method('getAttribute')
643
            ->with('disabled')
644
            ->will($this->returnValue(true));
645
646
        $request = new Request([
647
            'admin_code' => 'foo.admin',
648
            'field' => 'barField',
649
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
650
651
        $this->controller->retrieveAutocompleteItemsAction($request);
652
    }
653
654
    public function testRetrieveAutocompleteItemsTooShortSearchString()
655
    {
656
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
657
            ->method('hasAccess')
658
            ->with('create')
659
            ->will($this->returnValue(true));
660
661
        $targetAdmin = $this->createMock(AbstractAdmin::class);
662
        $targetAdmin->expects($this->once())
663
            ->method('checkAccess')
664
            ->with('list')
665
            ->will($this->returnValue(null));
666
667
        $fieldDescription = $this->createMock(FieldDescriptionInterface::class);
668
669
        $fieldDescription->expects($this->once())
670
            ->method('getTargetEntity')
671
            ->will($this->returnValue(Foo::class));
672
673
        $fieldDescription->expects($this->once())
674
            ->method('getName')
675
            ->will($this->returnValue('barField'));
676
677
        $fieldDescription->expects($this->once())
678
            ->method('getAssociationAdmin')
679
            ->will($this->returnValue($targetAdmin));
680
681
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
682
            ->method('getFormFieldDescriptions')
683
            ->will($this->returnValue(null));
684
685
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
686
            ->method('getFormFieldDescription')
687
            ->with('barField')
688
            ->will($this->returnValue($fieldDescription));
689
690
        $form = $this->getMockBuilder(Form::class)
691
            ->disableOriginalConstructor()
692
            ->getMock();
693
694
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
695
            ->method('getForm')
696
            ->will($this->returnValue($form));
697
698
        $formType = $this->getMockBuilder(Form::class)
699
            ->disableOriginalConstructor()
700
            ->getMock();
701
702
        $form->expects($this->once())
703
            ->method('get')
704
            ->with('barField')
705
            ->will($this->returnValue($formType));
706
707
        $formConfig = $this->getMockBuilder(FormConfigInterface::class)
708
            ->disableOriginalConstructor()
709
            ->getMock();
710
711
        $formType->expects($this->once())
712
            ->method('getConfig')
713
            ->will($this->returnValue($formConfig));
714
715
        $formConfig->expects($this->any())
716
            ->method('getAttribute')
717
            ->will($this->returnCallback(function ($name, $default = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $default 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...
718
                switch ($name) {
719
                    case 'property':
720
                        return 'foo';
721
                    case 'callback':
722
                        return;
723
                    case 'minimum_input_length':
724
                        return 3;
725
                    case 'items_per_page':
726
                        return 10;
727
                    case 'req_param_name_page_number':
728
                        return '_page';
729
                    case 'to_string_callback':
730
                        return;
731
                    case 'disabled':
732
                        return false;
733
                    case 'target_admin_access_action':
734
                        return 'list';
735
                    default:
736
                        throw new \RuntimeException(sprintf('Unkown parameter "%s" called.', $name));
737
                }
738
            }));
739
740
        $request = new Request([
741
            'admin_code' => 'foo.admin',
742
            'field' => 'barField',
743
            'q' => 'so',
744
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
745
746
        $response = $this->controller->retrieveAutocompleteItemsAction($request);
747
        $this->isInstanceOf(Response::class, $response);
748
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
749
        $this->assertSame('{"status":"KO","message":"Too short search string."}', $response->getContent());
750
    }
751
752
    public function testRetrieveAutocompleteItems()
753
    {
754
        $entity = new Foo();
755
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
756
            ->method('hasAccess')
757
            ->with('create')
758
            ->will($this->returnValue(true));
759
760
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
761
            ->method('id')
762
            ->with($entity)
763
            ->will($this->returnValue(123));
764
765
        $targetAdmin = $this->createMock(AbstractAdmin::class);
766
        $targetAdmin->expects($this->once())
767
            ->method('checkAccess')
768
            ->with('list')
769
            ->will($this->returnValue(null));
770
771
        $targetAdmin->expects($this->once())
772
            ->method('setPersistFilters')
773
            ->with(false)
774
            ->will($this->returnValue(null));
775
776
        $datagrid = $this->createMock(DatagridInterface::class);
777
        $targetAdmin->expects($this->once())
778
            ->method('getDatagrid')
779
            ->with()
780
            ->will($this->returnValue($datagrid));
781
782
        $metadata = $this->createMock(Metadata::class);
783
        $metadata->expects($this->once())
784
            ->method('getTitle')
785
            ->with()
786
            ->will($this->returnValue('FOO'));
787
788
        $targetAdmin->expects($this->once())
789
            ->method('getObjectMetadata')
790
            ->with($entity)
791
            ->will($this->returnValue($metadata));
792
793
        $datagrid->expects($this->once())
794
            ->method('hasFilter')
795
            ->with('foo')
796
            ->will($this->returnValue(true));
797
798
        $datagrid->expects($this->exactly(3))
799
            ->method('setValue')
800
            ->withConsecutive(
801
                [$this->equalTo('foo'), $this->equalTo(null), $this->equalTo('sonata')],
802
                [$this->equalTo('_per_page'), $this->equalTo(null), $this->equalTo(10)],
803
                [$this->equalTo('_page'), $this->equalTo(null), $this->equalTo(1)]
804
               )
805
            ->will($this->returnValue(null));
806
807
        $datagrid->expects($this->once())
808
            ->method('buildPager')
809
            ->with()
810
            ->will($this->returnValue(null));
811
812
        $pager = $this->createMock(Pager::class);
813
        $datagrid->expects($this->once())
814
            ->method('getPager')
815
            ->with()
816
            ->will($this->returnValue($pager));
817
818
        $pager->expects($this->once())
819
            ->method('getResults')
820
            ->with()
821
            ->will($this->returnValue([$entity]));
822
823
        $pager->expects($this->once())
824
            ->method('isLastPage')
825
            ->with()
826
            ->will($this->returnValue(true));
827
828
        $fieldDescription = $this->createMock(FieldDescriptionInterface::class);
829
830
        $fieldDescription->expects($this->once())
831
            ->method('getTargetEntity')
832
            ->will($this->returnValue(Foo::class));
833
834
        $fieldDescription->expects($this->once())
835
            ->method('getName')
836
            ->will($this->returnValue('barField'));
837
838
        $fieldDescription->expects($this->once())
839
            ->method('getAssociationAdmin')
840
            ->will($this->returnValue($targetAdmin));
841
842
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
843
            ->method('getFormFieldDescriptions')
844
            ->will($this->returnValue(null));
845
846
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
847
            ->method('getFormFieldDescription')
848
            ->with('barField')
849
            ->will($this->returnValue($fieldDescription));
850
851
        $form = $this->getMockBuilder(Form::class)
852
            ->disableOriginalConstructor()
853
            ->getMock();
854
855
        $this->admin->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects() does not seem to exist on object<Sonata\AdminBundle\Admin\AdminInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
856
            ->method('getForm')
857
            ->will($this->returnValue($form));
858
859
        $formType = $this->getMockBuilder(Form::class)
860
            ->disableOriginalConstructor()
861
            ->getMock();
862
863
        $form->expects($this->once())
864
            ->method('get')
865
            ->with('barField')
866
            ->will($this->returnValue($formType));
867
868
        $formConfig = $this->getMockBuilder(FormConfigInterface::class)
869
            ->disableOriginalConstructor()
870
            ->getMock();
871
872
        $formType->expects($this->once())
873
            ->method('getConfig')
874
            ->will($this->returnValue($formConfig));
875
876
        $formConfig->expects($this->any())
877
            ->method('getAttribute')
878
            ->will($this->returnCallback(function ($name, $default = null) {
0 ignored issues
show
Unused Code introduced by
The parameter $default 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...
879
                switch ($name) {
880
                    case 'property':
881
                        return 'foo';
882
                    case 'callback':
883
                        return;
884
                    case 'minimum_input_length':
885
                        return 3;
886
                    case 'items_per_page':
887
                        return 10;
888
                    case 'req_param_name_page_number':
889
                        return '_page';
890
                    case 'to_string_callback':
891
                        return;
892
                    case 'disabled':
893
                        return false;
894
                    case 'target_admin_access_action':
895
                        return 'list';
896
                    default:
897
                        throw new \RuntimeException(sprintf('Unkown parameter "%s" called.', $name));
898
                }
899
            }));
900
901
        $request = new Request([
902
            'admin_code' => 'foo.admin',
903
            'field' => 'barField',
904
            'q' => 'sonata',
905
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
906
907
        $response = $this->controller->retrieveAutocompleteItemsAction($request);
908
        $this->isInstanceOf(Response::class, $response);
909
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
910
        $this->assertSame('{"status":"OK","more":false,"items":[{"id":123,"label":"FOO"}]}', $response->getContent());
911
    }
912
}
913