HelperControllerTest.php 35 KB

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