Completed
Push — master ( 3a65e8...9f4bbe )
by Grégoire
16s
created

testRetrieveAutocompleteItems()   D

Complexity

Conditions 9
Paths 1

Size

Total Lines 160
Code Lines 128

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 160
rs 4.8196
c 0
b 0
f 0
cc 9
eloc 128
nc 1
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 Sonata\AdminBundle\Admin\AdminHelper;
16
use Sonata\AdminBundle\Admin\AdminInterface;
17
use Sonata\AdminBundle\Admin\Pool;
18
use Sonata\AdminBundle\Controller\HelperController;
19
use Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo;
20
use Sonata\AdminBundle\Twig\Extension\SonataAdminExtension;
21
use Symfony\Bridge\Twig\Extension\FormExtension;
22
use Symfony\Bridge\Twig\Form\TwigRenderer;
23
use Symfony\Component\Form\Command\DebugCommand;
24
use Symfony\Component\Form\FormRenderer;
25
use Symfony\Component\HttpFoundation\Request;
26
use Symfony\Component\HttpFoundation\Response;
27
use Symfony\Component\Validator\ConstraintViolation;
28
use Symfony\Component\Validator\ConstraintViolationList;
29
30
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...
31
{
32
    private $bar;
33
34
    public function getAdminTitle()
35
    {
36
        return 'foo';
37
    }
38
39
    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...
40
    {
41
    }
42
43
    public function setBar(AdminControllerHelper_Bar $bar)
44
    {
45
        $this->bar = $bar;
46
    }
47
48
    public function getBar()
49
    {
50
        return $this->bar;
51
    }
52
}
53
54
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...
55
{
56
    public function getAdminTitle()
57
    {
58
        return 'bar';
59
    }
60
61
    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...
62
    {
63
    }
64
65
    public function getEnabled()
66
    {
67
    }
68
}
69
70
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...
71
{
72
    /**
73
     * @var AdminInterface
74
     */
75
    private $admin;
76
77
    /**
78
     * @var HelperController
79
     */
80
    private $controller;
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    protected function setUp()
86
    {
87
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
88
        $pool = new Pool($container, 'title', 'logo.png');
89
        $pool->setAdminServiceIds(['foo.admin']);
90
91
        $this->admin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
92
93
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
94
        $helper = new AdminHelper($pool);
95
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
96
        $this->controller = new HelperController($twig, $pool, $helper, $validator);
97
98
        // php 5.3 BC
99
        $admin = $this->admin;
100
101
        $container->expects($this->any())
102
            ->method('get')
103
            ->will($this->returnCallback(function ($id) use ($admin) {
104
                switch ($id) {
105
                    case 'foo.admin':
106
                        return $admin;
107
                }
108
            }));
109
    }
110
111
    /**
112
     * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
113
     */
114
    public function testgetShortObjectDescriptionActionInvalidAdmin()
115
    {
116
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
117
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
118
        $request = new Request([
119
            'code' => 'sonata.post.admin',
120
            'objectId' => 42,
121
            'uniqid' => 'asdasd123',
122
        ]);
123
        $pool = new Pool($container, 'title', 'logo');
124
        $pool->setAdminServiceIds(['sonata.post.admin']);
125
        $helper = new AdminHelper($pool);
126
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
127
        $controller = new HelperController($twig, $pool, $helper, $validator);
128
129
        $controller->getShortObjectDescriptionAction($request);
130
    }
131
132
    /**
133
     * @expectedException \RuntimeException
134
     * @exceptionMessage Invalid format
135
     */
136
    public function testgetShortObjectDescriptionActionObjectDoesNotExist()
137
    {
138
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AdminInterface');
139
        $admin->expects($this->once())->method('setUniqid');
140
        $admin->expects($this->once())->method('getObject')->will($this->returnValue(false));
141
142
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
143
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
144
145
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
146
        $request = new Request([
147
            'code' => 'sonata.post.admin',
148
            'objectId' => 42,
149
            'uniqid' => 'asdasd123',
150
        ]);
151
152
        $pool = new Pool($container, 'title', 'logo');
153
        $pool->setAdminServiceIds(['sonata.post.admin']);
154
155
        $helper = new AdminHelper($pool);
156
157
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
158
        $controller = new HelperController($twig, $pool, $helper, $validator);
159
160
        $controller->getShortObjectDescriptionAction($request);
161
    }
162
163
    public function testgetShortObjectDescriptionActionEmptyObjectId()
164
    {
165
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AdminInterface');
166
        $admin->expects($this->once())->method('setUniqid');
167
        $admin->expects($this->once())->method('getObject')->with($this->identicalTo(null))->will($this->returnValue(false));
168
169
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
170
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
171
172
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
173
        $request = new Request([
174
            'code' => 'sonata.post.admin',
175
            'objectId' => '',
176
            'uniqid' => 'asdasd123',
177
            '_format' => 'html',
178
        ]);
179
180
        $pool = new Pool($container, 'title', 'logo');
181
        $pool->setAdminServiceIds(['sonata.post.admin']);
182
183
        $helper = new AdminHelper($pool);
184
185
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
186
        $controller = new HelperController($twig, $pool, $helper, $validator);
187
188
        $controller->getShortObjectDescriptionAction($request);
189
    }
190
191
    public function testgetShortObjectDescriptionActionObject()
192
    {
193
        $mockTemplate = 'AdminHelperTest:mock-short-object-description.html.twig';
194
195
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AdminInterface');
196
        $admin->expects($this->once())->method('setUniqid');
197
        $admin->expects($this->once())->method('getTemplate')->will($this->returnValue($mockTemplate));
198
        $admin->expects($this->once())->method('getObject')->will($this->returnValue(new AdminControllerHelper_Foo()));
199
        $admin->expects($this->once())->method('toString')->will($this->returnValue('bar'));
200
        $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...
201
            if ('edit' != $type) {
202
                return 'invalid name';
203
            }
204
205
            return '/ok/url';
206
        }));
207
208
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
209
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
210
211
        $twig = $this->getMockBuilder('\Twig_Environment')->disableOriginalConstructor()->getMock();
212
213
        $twig->expects($this->once())->method('render')
214
            ->with($mockTemplate)
215
            ->will($this->returnCallback(function ($templateName, $templateParams) {
216
                return sprintf('<a href="%s" target="new">%s</a>', $templateParams['admin']->generateObjectUrl('edit', $templateParams['object']), $templateParams['description']);
217
            }));
218
219
        $request = new Request([
220
            'code' => 'sonata.post.admin',
221
            'objectId' => 42,
222
            'uniqid' => 'asdasd123',
223
            '_format' => 'html',
224
        ]);
225
226
        $pool = new Pool($container, 'title', 'logo');
227
        $pool->setAdminServiceIds(['sonata.post.admin']);
228
229
        $helper = new AdminHelper($pool);
230
231
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
232
233
        $controller = new HelperController($twig, $pool, $helper, $validator);
234
235
        $response = $controller->getShortObjectDescriptionAction($request);
236
237
        $expected = '<a href="/ok/url" target="new">bar</a>';
238
        $this->assertSame($expected, $response->getContent());
239
    }
240
241
    public function testsetObjectFieldValueAction()
242
    {
243
        $object = new AdminControllerHelper_Foo();
244
245
        $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
246
        $fieldDescription->expects($this->once())->method('getOption')->will($this->returnValue(true));
247
248
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
249
        $admin->expects($this->once())->method('getObject')->will($this->returnValue($object));
250
        $admin->expects($this->once())->method('hasAccess')->will($this->returnValue(true));
251
        $admin->expects($this->once())->method('getListFieldDescription')->will($this->returnValue($fieldDescription));
252
        $fieldDescription->expects($this->exactly(2))->method('getAdmin')->will($this->returnValue($admin));
253
254
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
255
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
256
257
        $pool = new Pool($container, 'title', 'logo');
258
        $pool->setAdminServiceIds(['sonata.post.admin']);
259
260
        $adminExtension = new SonataAdminExtension(
261
            $pool,
262
            $this->createMock('Psr\Log\LoggerInterface'),
263
            $this->createMock('Symfony\Component\Translation\TranslatorInterface')
264
        );
265
266
        // NEXT_MAJOR: Remove this check when dropping support for twig < 2
267
        if (method_exists('\Twig_LoaderInterface', 'getSourceContext')) {
268
            $loader = $this->createMock('\Twig_LoaderInterface');
269
        } else {
270
            $loader = $this->createMock(['\Twig_LoaderInterface', 'Twig_SourceContextLoaderInterface']);
271
        }
272
        $loader->method('getSourceContext')->will($this->returnValue(new \Twig_Source('<foo />', 'foo')));
273
274
        $twig = new \Twig_Environment($loader);
275
        $twig->addExtension($adminExtension);
276
        $request = new Request([
277
            'code' => 'sonata.post.admin',
278
            'objectId' => 42,
279
            'field' => 'enabled',
280
            'value' => 1,
281
            'context' => 'list',
282
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
283
284
        $helper = new AdminHelper($pool);
285
286
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
287
288
        $controller = new HelperController($twig, $pool, $helper, $validator);
289
290
        $response = $controller->setObjectFieldValueAction($request);
291
292
        $this->assertEquals(200, $response->getStatusCode());
293
    }
294
295
    public function testappendFormFieldElementAction()
296
    {
297
        $object = new AdminControllerHelper_Foo();
298
299
        $modelManager = $this->createMock('Sonata\AdminBundle\Model\ModelManagerInterface');
300
        $modelManager->expects($this->once())->method('find')->will($this->returnValue($object));
301
302
        $mockTheme = $this->getMockBuilder('Symfony\Component\Form\FormView')
303
            ->disableOriginalConstructor()
304
            ->getMock();
305
306
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AdminInterface');
307
        $admin->expects($this->once())->method('getModelManager')->will($this->returnValue($modelManager));
308
        $admin->expects($this->once())->method('setRequest');
309
        $admin->expects($this->once())->method('setSubject');
310
        $admin->expects($this->once())->method('getFormTheme')->will($this->returnValue($mockTheme));
311
312
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
313
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
314
315
        $mockRenderer = $this->getMockBuilder('Symfony\Bridge\Twig\Form\TwigRendererInterface')
316
            ->disableOriginalConstructor()
317
            ->getMock();
318
319
        $mockRenderer->expects($this->once())
320
            ->method('searchAndRenderBlock')
321
            ->will($this->returnValue(new Response()));
322
323
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
324
325
        // Remove the condition when dropping sf < 3.2
326
        if (method_exists('Symfony\Bridge\Twig\AppVariable', 'getToken')) {
327
            $twig->addExtension(new FormExtension());
328
            $runtimeLoader = $this
329
                ->getMockBuilder('Twig_RuntimeLoaderInterface')
330
                ->getMock();
331
332
            // Remove the condition when dropping sf < 3.4
333
            if (!class_exists(DebugCommand::class)) {
334
                $runtimeLoader->expects($this->once())
335
                    ->method('load')
336
                    ->with($this->equalTo(TwigRenderer::class))
337
                    ->will($this->returnValue($mockRenderer));
338
            } else {
339
                $runtimeLoader->expects($this->once())
340
                    ->method('load')
341
                    ->with($this->equalTo(FormRenderer::class))
342
                    ->will($this->returnValue($mockRenderer));
343
            }
344
345
            $twig->addRuntimeLoader($runtimeLoader);
346
        } else {
347
            $twig->addExtension(new FormExtension($mockRenderer));
348
        }
349
350
        $request = new Request([
351
            'code' => 'sonata.post.admin',
352
            'objectId' => 42,
353
            'field' => 'enabled',
354
            'value' => 1,
355
            'context' => 'list',
356
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST']);
357
358
        $pool = new Pool($container, 'title', 'logo');
359
        $pool->setAdminServiceIds(['sonata.post.admin']);
360
361
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
362
363
        $mockView = $this->getMockBuilder('Symfony\Component\Form\FormView')
364
            ->disableOriginalConstructor()
365
            ->getMock();
366
367
        $mockForm = $this->getMockBuilder('Symfony\Component\Form\Form')
368
            ->disableOriginalConstructor()
369
            ->getMock();
370
        $mockForm->expects($this->once())
371
            ->method('createView')
372
            ->will($this->returnValue($mockView));
373
374
        $helper = $this->getMockBuilder('Sonata\AdminBundle\Admin\AdminHelper')
375
            ->setMethods(['appendFormFieldElement', 'getChildFormView'])
376
            ->setConstructorArgs([$pool])
377
            ->getMock();
378
        $helper->expects($this->once())->method('appendFormFieldElement')->will($this->returnValue([
379
            $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface'),
380
            $mockForm,
381
        ]));
382
        $helper->expects($this->once())->method('getChildFormView')->will($this->returnValue($mockView));
383
384
        $controller = new HelperController($twig, $pool, $helper, $validator);
385
        $response = $controller->appendFormFieldElementAction($request);
386
387
        $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
388
    }
389
390
    public function testRetrieveFormFieldElementAction()
391
    {
392
        $object = new AdminControllerHelper_Foo();
393
394
        $request = new Request([
395
            'code' => 'sonata.post.admin',
396
            'objectId' => 42,
397
            'field' => 'enabled',
398
            'value' => 1,
399
            'context' => 'list',
400
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST']);
401
402
        $modelManager = $this->createMock('Sonata\AdminBundle\Model\ModelManagerInterface');
403
        $modelManager->expects($this->once())->method('find')->will($this->returnValue($object));
404
405
        $mockView = $this->getMockBuilder('Symfony\Component\Form\FormView')
406
            ->disableOriginalConstructor()
407
            ->getMock();
408
409
        $mockForm = $this->getMockBuilder('Symfony\Component\Form\Form')
410
            ->disableOriginalConstructor()
411
            ->getMock();
412
413
        $mockForm->expects($this->once())
414
            ->method('setData')
415
            ->with($object);
416
417
        $mockForm->expects($this->once())
418
            ->method('handleRequest')
419
            ->with($request);
420
421
        $mockForm->expects($this->once())
422
            ->method('createView')
423
            ->will($this->returnValue($mockView));
424
425
        $formBuilder = $this->getMockBuilder('Symfony\Component\Form\FormBuilder')
426
            ->disableOriginalConstructor()
427
            ->getMock();
428
        $formBuilder->expects($this->once())->method('getForm')->will($this->returnValue($mockForm));
429
430
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AdminInterface');
431
        $admin->expects($this->once())->method('getModelManager')->will($this->returnValue($modelManager));
432
        $admin->expects($this->once())->method('getFormBuilder')->will($this->returnValue($formBuilder));
433
434
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
435
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
436
437
        $mockRenderer = $this->getMockBuilder('Symfony\Bridge\Twig\Form\TwigRendererInterface')
438
            ->disableOriginalConstructor()
439
            ->getMock();
440
441
        $mockRenderer->expects($this->once())
442
            ->method('searchAndRenderBlock')
443
            ->will($this->returnValue(new Response()));
444
445
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
446
447
        // Remove the condition when dropping sf < 3.2
448
        if (method_exists('Symfony\Bridge\Twig\AppVariable', 'getToken')) {
449
            $twig->addExtension(new FormExtension());
450
            $runtimeLoader = $this
451
                ->getMockBuilder('Twig_RuntimeLoaderInterface')
452
                ->getMock();
453
454
            // Remove the condition when dropping sf < 3.4
455
            if (!class_exists(DebugCommand::class)) {
456
                $runtimeLoader->expects($this->once())
457
                    ->method('load')
458
                    ->with($this->equalTo(TwigRenderer::class))
459
                    ->will($this->returnValue($mockRenderer));
460
            } else {
461
                $runtimeLoader->expects($this->once())
462
                    ->method('load')
463
                    ->with($this->equalTo(FormRenderer::class))
464
                    ->will($this->returnValue($mockRenderer));
465
            }
466
467
            $twig->addRuntimeLoader($runtimeLoader);
468
        } else {
469
            $twig->addExtension(new FormExtension($mockRenderer));
470
        }
471
472
        $pool = new Pool($container, 'title', 'logo');
473
        $pool->setAdminServiceIds(['sonata.post.admin']);
474
475
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
476
477
        $helper = $this->getMockBuilder('Sonata\AdminBundle\Admin\AdminHelper')
478
            ->setMethods(['getChildFormView'])
479
            ->setConstructorArgs([$pool])
480
            ->getMock();
481
        $helper->expects($this->once())->method('getChildFormView')->will($this->returnValue($mockView));
482
483
        $controller = new HelperController($twig, $pool, $helper, $validator);
484
        $response = $controller->retrieveFormFieldElementAction($request);
485
486
        $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
487
    }
488
489
    public function testSetObjectFieldValueActionWithViolations()
490
    {
491
        $bar = new AdminControllerHelper_Bar();
492
493
        $object = new AdminControllerHelper_Foo();
494
        $object->setBar($bar);
495
496
        $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
497
        $fieldDescription->expects($this->once())->method('getOption')->will($this->returnValue(true));
498
499
        $admin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
500
        $admin->expects($this->once())->method('getObject')->will($this->returnValue($object));
501
        $admin->expects($this->once())->method('hasAccess')->will($this->returnValue(true));
502
        $admin->expects($this->once())->method('getListFieldDescription')->will($this->returnValue($fieldDescription));
503
504
        $container = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
505
        $container->expects($this->any())->method('get')->will($this->returnValue($admin));
506
507
        $twig = new \Twig_Environment($this->createMock('\Twig_LoaderInterface'));
508
        $request = new Request([
509
            'code' => 'sonata.post.admin',
510
            'objectId' => 42,
511
            'field' => 'bar.enabled',
512
            'value' => 1,
513
            'context' => 'list',
514
        ], [], [], [], [], ['REQUEST_METHOD' => 'POST', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
515
516
        $pool = new Pool($container, 'title', 'logo');
517
        $pool->setAdminServiceIds(['sonata.post.admin']);
518
519
        $helper = new AdminHelper($pool);
520
521
        $violations = new ConstraintViolationList([
522
            new ConstraintViolation('error1', null, [], null, 'enabled', null),
523
            new ConstraintViolation('error2', null, [], null, 'enabled', null),
524
        ]);
525
526
        $validator = $this->createMock('Symfony\Component\Validator\Validator\ValidatorInterface');
527
528
        $validator
529
            ->expects($this->once())
530
            ->method('validate')
531
            ->with($bar)
532
            ->will($this->returnValue($violations))
533
        ;
534
535
        $controller = new HelperController($twig, $pool, $helper, $validator);
536
537
        $response = $controller->setObjectFieldValueAction($request);
538
539
        $this->assertEquals(400, $response->getStatusCode());
540
        $this->assertSame(json_encode("error1\nerror2"), $response->getContent());
541
    }
542
543
    /**
544
     * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
545
     * @exceptionMessage Invalid format
546
     */
547
    public function testRetrieveAutocompleteItemsActionNotGranted()
548
    {
549
        $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...
550
            ->method('hasAccess')
551
            ->will($this->returnCallback(function ($operation) {
552
                if ('create' == $operation || 'edit' == $operation) {
553
                    return false;
554
                }
555
556
                return;
557
            }));
558
559
        $request = new Request([
560
            'admin_code' => 'foo.admin',
561
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
562
563
        $this->controller->retrieveAutocompleteItemsAction($request);
564
    }
565
566
    /**
567
     * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
568
     * @exceptionMessage Autocomplete list can`t be retrieved because the form element is disabled or read_only.
569
     */
570
    public function testRetrieveAutocompleteItemsActionDisabledFormelememt()
571
    {
572
        $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...
573
            ->method('hasAccess')
574
            ->with('create')
575
            ->will($this->returnValue(true));
576
577
        $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
578
579
        $fieldDescription->expects($this->once())
580
            ->method('getTargetEntity')
581
            ->will($this->returnValue('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'));
582
583
        $fieldDescription->expects($this->once())
584
            ->method('getName')
585
            ->will($this->returnValue('barField'));
586
587
        $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...
588
            ->method('getFormFieldDescriptions')
589
            ->will($this->returnValue(null));
590
591
        $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...
592
            ->method('getFormFieldDescription')
593
            ->with('barField')
594
            ->will($this->returnValue($fieldDescription));
595
596
        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
597
            ->disableOriginalConstructor()
598
            ->getMock();
599
600
        $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...
601
            ->method('getForm')
602
            ->will($this->returnValue($form));
603
604
        $formType = $this->getMockBuilder('Symfony\Component\Form\Form')
605
            ->disableOriginalConstructor()
606
            ->getMock();
607
608
        $form->expects($this->once())
609
            ->method('get')
610
            ->with('barField')
611
            ->will($this->returnValue($formType));
612
613
        $formConfig = $this->getMockBuilder('Symfony\Component\Form\FormConfigInterface')
614
            ->disableOriginalConstructor()
615
            ->getMock();
616
617
        $formType->expects($this->once())
618
            ->method('getConfig')
619
            ->will($this->returnValue($formConfig));
620
621
        $formConfig->expects($this->once())
622
            ->method('getAttribute')
623
            ->with('disabled')
624
            ->will($this->returnValue(true));
625
626
        $request = new Request([
627
            'admin_code' => 'foo.admin',
628
            'field' => 'barField',
629
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
630
631
        $this->controller->retrieveAutocompleteItemsAction($request);
632
    }
633
634
    public function testRetrieveAutocompleteItemsTooShortSearchString()
635
    {
636
        $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...
637
            ->method('hasAccess')
638
            ->with('create')
639
            ->will($this->returnValue(true));
640
641
        $targetAdmin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
642
        $targetAdmin->expects($this->once())
643
            ->method('checkAccess')
644
            ->with('list')
645
            ->will($this->returnValue(null));
646
647
        $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
648
649
        $fieldDescription->expects($this->once())
650
            ->method('getTargetEntity')
651
            ->will($this->returnValue('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'));
652
653
        $fieldDescription->expects($this->once())
654
            ->method('getName')
655
            ->will($this->returnValue('barField'));
656
657
        $fieldDescription->expects($this->once())
658
            ->method('getAssociationAdmin')
659
            ->will($this->returnValue($targetAdmin));
660
661
        $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...
662
            ->method('getFormFieldDescriptions')
663
            ->will($this->returnValue(null));
664
665
        $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...
666
            ->method('getFormFieldDescription')
667
            ->with('barField')
668
            ->will($this->returnValue($fieldDescription));
669
670
        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
671
            ->disableOriginalConstructor()
672
            ->getMock();
673
674
        $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...
675
            ->method('getForm')
676
            ->will($this->returnValue($form));
677
678
        $formType = $this->getMockBuilder('Symfony\Component\Form\Form')
679
            ->disableOriginalConstructor()
680
            ->getMock();
681
682
        $form->expects($this->once())
683
            ->method('get')
684
            ->with('barField')
685
            ->will($this->returnValue($formType));
686
687
        $formConfig = $this->getMockBuilder('Symfony\Component\Form\FormConfigInterface')
688
            ->disableOriginalConstructor()
689
            ->getMock();
690
691
        $formType->expects($this->once())
692
            ->method('getConfig')
693
            ->will($this->returnValue($formConfig));
694
695
        $formConfig->expects($this->any())
696
            ->method('getAttribute')
697
            ->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...
698
                switch ($name) {
699
                    case 'property':
700
                        return 'foo';
701
                    case 'callback':
702
                        return;
703
                    case 'minimum_input_length':
704
                        return 3;
705
                    case 'items_per_page':
706
                        return 10;
707
                    case 'req_param_name_page_number':
708
                        return '_page';
709
                    case 'to_string_callback':
710
                        return;
711
                    case 'disabled':
712
                        return false;
713
                    case 'target_admin_access_action':
714
                        return 'list';
715
                    default:
716
                        throw new \RuntimeException(sprintf('Unkown parameter "%s" called.', $name));
717
                }
718
            }));
719
720
        $request = new Request([
721
            'admin_code' => 'foo.admin',
722
            'field' => 'barField',
723
            'q' => 'so',
724
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
725
726
        $response = $this->controller->retrieveAutocompleteItemsAction($request);
727
        $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
728
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
729
        $this->assertSame('{"status":"KO","message":"Too short search string."}', $response->getContent());
730
    }
731
732
    public function testRetrieveAutocompleteItems()
733
    {
734
        $entity = new Foo();
735
        $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...
736
            ->method('hasAccess')
737
            ->with('create')
738
            ->will($this->returnValue(true));
739
740
        $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...
741
            ->method('id')
742
            ->with($entity)
743
            ->will($this->returnValue(123));
744
745
        $targetAdmin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
746
        $targetAdmin->expects($this->once())
747
            ->method('checkAccess')
748
            ->with('list')
749
            ->will($this->returnValue(null));
750
751
        $targetAdmin->expects($this->once())
752
            ->method('setPersistFilters')
753
            ->with(false)
754
            ->will($this->returnValue(null));
755
756
        $datagrid = $this->createMock('Sonata\AdminBundle\Datagrid\DatagridInterface');
757
        $targetAdmin->expects($this->once())
758
            ->method('getDatagrid')
759
            ->with()
760
            ->will($this->returnValue($datagrid));
761
762
        $metadata = $this->createMock('Sonata\CoreBundle\Model\Metadata');
763
        $metadata->expects($this->once())
764
            ->method('getTitle')
765
            ->with()
766
            ->will($this->returnValue('FOO'));
767
768
        $targetAdmin->expects($this->once())
769
            ->method('getObjectMetadata')
770
            ->with($entity)
771
            ->will($this->returnValue($metadata));
772
773
        $datagrid->expects($this->once())
774
            ->method('hasFilter')
775
            ->with('foo')
776
            ->will($this->returnValue(true));
777
778
        $datagrid->expects($this->exactly(3))
779
            ->method('setValue')
780
            ->withConsecutive(
781
                [$this->equalTo('foo'), $this->equalTo(null), $this->equalTo('sonata')],
782
                [$this->equalTo('_per_page'), $this->equalTo(null), $this->equalTo(10)],
783
                [$this->equalTo('_page'), $this->equalTo(null), $this->equalTo(1)]
784
               )
785
            ->will($this->returnValue(null));
786
787
        $datagrid->expects($this->once())
788
            ->method('buildPager')
789
            ->with()
790
            ->will($this->returnValue(null));
791
792
        $pager = $this->createMock('Sonata\AdminBundle\Datagrid\Pager');
793
        $datagrid->expects($this->once())
794
            ->method('getPager')
795
            ->with()
796
            ->will($this->returnValue($pager));
797
798
        $pager->expects($this->once())
799
            ->method('getResults')
800
            ->with()
801
            ->will($this->returnValue([$entity]));
802
803
        $pager->expects($this->once())
804
            ->method('isLastPage')
805
            ->with()
806
            ->will($this->returnValue(true));
807
808
        $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
809
810
        $fieldDescription->expects($this->once())
811
            ->method('getTargetEntity')
812
            ->will($this->returnValue('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'));
813
814
        $fieldDescription->expects($this->once())
815
            ->method('getName')
816
            ->will($this->returnValue('barField'));
817
818
        $fieldDescription->expects($this->once())
819
            ->method('getAssociationAdmin')
820
            ->will($this->returnValue($targetAdmin));
821
822
        $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...
823
            ->method('getFormFieldDescriptions')
824
            ->will($this->returnValue(null));
825
826
        $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...
827
            ->method('getFormFieldDescription')
828
            ->with('barField')
829
            ->will($this->returnValue($fieldDescription));
830
831
        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
832
            ->disableOriginalConstructor()
833
            ->getMock();
834
835
        $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...
836
            ->method('getForm')
837
            ->will($this->returnValue($form));
838
839
        $formType = $this->getMockBuilder('Symfony\Component\Form\Form')
840
            ->disableOriginalConstructor()
841
            ->getMock();
842
843
        $form->expects($this->once())
844
            ->method('get')
845
            ->with('barField')
846
            ->will($this->returnValue($formType));
847
848
        $formConfig = $this->getMockBuilder('Symfony\Component\Form\FormConfigInterface')
849
            ->disableOriginalConstructor()
850
            ->getMock();
851
852
        $formType->expects($this->once())
853
            ->method('getConfig')
854
            ->will($this->returnValue($formConfig));
855
856
        $formConfig->expects($this->any())
857
            ->method('getAttribute')
858
            ->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...
859
                switch ($name) {
860
                    case 'property':
861
                        return 'foo';
862
                    case 'callback':
863
                        return;
864
                    case 'minimum_input_length':
865
                        return 3;
866
                    case 'items_per_page':
867
                        return 10;
868
                    case 'req_param_name_page_number':
869
                        return '_page';
870
                    case 'to_string_callback':
871
                        return;
872
                    case 'disabled':
873
                        return false;
874
                    case 'target_admin_access_action':
875
                        return 'list';
876
                    default:
877
                        throw new \RuntimeException(sprintf('Unkown parameter "%s" called.', $name));
878
                }
879
            }));
880
881
        $request = new Request([
882
            'admin_code' => 'foo.admin',
883
            'field' => 'barField',
884
            'q' => 'sonata',
885
        ], [], [], [], [], ['REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
886
887
        $response = $this->controller->retrieveAutocompleteItemsAction($request);
888
        $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
889
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
890
        $this->assertSame('{"status":"OK","more":false,"items":[{"id":123,"label":"FOO"}]}', $response->getContent());
891
    }
892
}
893