HelperControllerTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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->assertSame('{"status":"OK","content":"\u003Cfoo \/\u003E"}', $response->getContent());
  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->assertSame('{"status":"KO","message":"error1\nerror2"}', $response->getContent());
  426. }
  427. /**
  428. * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
  429. * @exceptionMessage Invalid format
  430. */
  431. public function testRetrieveAutocompleteItemsActionNotGranted()
  432. {
  433. $this->admin->expects($this->exactly(2))
  434. ->method('hasAccess')
  435. ->will($this->returnCallback(function ($operation) {
  436. if ($operation == 'create' || $operation == 'edit') {
  437. return false;
  438. }
  439. return;
  440. }));
  441. $request = new Request(array(
  442. 'admin_code' => 'foo.admin',
  443. ), array(), array(), array(), array(), array('REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'));
  444. $this->controller->retrieveAutocompleteItemsAction($request);
  445. }
  446. /**
  447. * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
  448. * @exceptionMessage Autocomplete list can`t be retrieved because the form element is disabled or read_only.
  449. */
  450. public function testRetrieveAutocompleteItemsActionDisabledFormelememt()
  451. {
  452. $this->admin->expects($this->once())
  453. ->method('hasAccess')
  454. ->with('create')
  455. ->will($this->returnValue(true));
  456. $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
  457. $fieldDescription->expects($this->once())
  458. ->method('getTargetEntity')
  459. ->will($this->returnValue('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'));
  460. $fieldDescription->expects($this->once())
  461. ->method('getName')
  462. ->will($this->returnValue('barField'));
  463. $this->admin->expects($this->once())
  464. ->method('getFormFieldDescriptions')
  465. ->will($this->returnValue(null));
  466. $this->admin->expects($this->once())
  467. ->method('getFormFieldDescription')
  468. ->with('barField')
  469. ->will($this->returnValue($fieldDescription));
  470. $form = $this->getMockBuilder('Symfony\Component\Form\Form')
  471. ->disableOriginalConstructor()
  472. ->getMock();
  473. $this->admin->expects($this->once())
  474. ->method('getForm')
  475. ->will($this->returnValue($form));
  476. $formType = $this->getMockBuilder('Symfony\Component\Form\Form')
  477. ->disableOriginalConstructor()
  478. ->getMock();
  479. $form->expects($this->once())
  480. ->method('get')
  481. ->with('barField')
  482. ->will($this->returnValue($formType));
  483. $formConfig = $this->getMockBuilder('Symfony\Component\Form\FormConfigInterface')
  484. ->disableOriginalConstructor()
  485. ->getMock();
  486. $formType->expects($this->once())
  487. ->method('getConfig')
  488. ->will($this->returnValue($formConfig));
  489. $formConfig->expects($this->once())
  490. ->method('getAttribute')
  491. ->with('disabled')
  492. ->will($this->returnValue(true));
  493. $request = new Request(array(
  494. 'admin_code' => 'foo.admin',
  495. 'field' => 'barField',
  496. ), array(), array(), array(), array(), array('REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'));
  497. $this->controller->retrieveAutocompleteItemsAction($request);
  498. }
  499. public function testRetrieveAutocompleteItemsTooShortSearchString()
  500. {
  501. $this->admin->expects($this->once())
  502. ->method('hasAccess')
  503. ->with('create')
  504. ->will($this->returnValue(true));
  505. $targetAdmin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
  506. $targetAdmin->expects($this->once())
  507. ->method('checkAccess')
  508. ->with('list')
  509. ->will($this->returnValue(null));
  510. $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
  511. $fieldDescription->expects($this->once())
  512. ->method('getTargetEntity')
  513. ->will($this->returnValue('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'));
  514. $fieldDescription->expects($this->once())
  515. ->method('getName')
  516. ->will($this->returnValue('barField'));
  517. $fieldDescription->expects($this->once())
  518. ->method('getAssociationAdmin')
  519. ->will($this->returnValue($targetAdmin));
  520. $this->admin->expects($this->once())
  521. ->method('getFormFieldDescriptions')
  522. ->will($this->returnValue(null));
  523. $this->admin->expects($this->once())
  524. ->method('getFormFieldDescription')
  525. ->with('barField')
  526. ->will($this->returnValue($fieldDescription));
  527. $form = $this->getMockBuilder('Symfony\Component\Form\Form')
  528. ->disableOriginalConstructor()
  529. ->getMock();
  530. $this->admin->expects($this->once())
  531. ->method('getForm')
  532. ->will($this->returnValue($form));
  533. $formType = $this->getMockBuilder('Symfony\Component\Form\Form')
  534. ->disableOriginalConstructor()
  535. ->getMock();
  536. $form->expects($this->once())
  537. ->method('get')
  538. ->with('barField')
  539. ->will($this->returnValue($formType));
  540. $formConfig = $this->getMockBuilder('Symfony\Component\Form\FormConfigInterface')
  541. ->disableOriginalConstructor()
  542. ->getMock();
  543. $formType->expects($this->once())
  544. ->method('getConfig')
  545. ->will($this->returnValue($formConfig));
  546. $formConfig->expects($this->any())
  547. ->method('getAttribute')
  548. ->will($this->returnCallback(function ($name, $default = null) {
  549. switch ($name) {
  550. case 'property':
  551. return 'foo';
  552. case 'callback':
  553. return;
  554. case 'minimum_input_length':
  555. return 3;
  556. case 'items_per_page':
  557. return 10;
  558. case 'req_param_name_page_number':
  559. return '_page';
  560. case 'to_string_callback':
  561. return;
  562. case 'disabled':
  563. return false;
  564. case 'target_admin_access_action':
  565. return 'list';
  566. default:
  567. throw new \RuntimeException(sprintf('Unkown parameter "%s" called.', $name));
  568. }
  569. }));
  570. $request = new Request(array(
  571. 'admin_code' => 'foo.admin',
  572. 'field' => 'barField',
  573. 'q' => 'so',
  574. ), array(), array(), array(), array(), array('REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'));
  575. $response = $this->controller->retrieveAutocompleteItemsAction($request);
  576. $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
  577. $this->assertSame('application/json', $response->headers->get('Content-Type'));
  578. $this->assertSame('{"status":"KO","message":"Too short search string."}', $response->getContent());
  579. }
  580. public function testRetrieveAutocompleteItems()
  581. {
  582. $entity = new Foo();
  583. $this->admin->expects($this->once())
  584. ->method('hasAccess')
  585. ->with('create')
  586. ->will($this->returnValue(true));
  587. $this->admin->expects($this->once())
  588. ->method('id')
  589. ->with($entity)
  590. ->will($this->returnValue(123));
  591. $targetAdmin = $this->createMock('Sonata\AdminBundle\Admin\AbstractAdmin');
  592. $targetAdmin->expects($this->once())
  593. ->method('checkAccess')
  594. ->with('list')
  595. ->will($this->returnValue(null));
  596. $targetAdmin->expects($this->once())
  597. ->method('setPersistFilters')
  598. ->with(false)
  599. ->will($this->returnValue(null));
  600. $datagrid = $this->createMock('Sonata\AdminBundle\Datagrid\DatagridInterface');
  601. $targetAdmin->expects($this->once())
  602. ->method('getDatagrid')
  603. ->with()
  604. ->will($this->returnValue($datagrid));
  605. $metadata = $this->createMock('Sonata\CoreBundle\Model\Metadata');
  606. $metadata->expects($this->once())
  607. ->method('getTitle')
  608. ->with()
  609. ->will($this->returnValue('FOO'));
  610. $targetAdmin->expects($this->once())
  611. ->method('getObjectMetadata')
  612. ->with($entity)
  613. ->will($this->returnValue($metadata));
  614. $datagrid->expects($this->once())
  615. ->method('hasFilter')
  616. ->with('foo')
  617. ->will($this->returnValue(true));
  618. $datagrid->expects($this->exactly(3))
  619. ->method('setValue')
  620. ->withConsecutive(
  621. array($this->equalTo('foo'), $this->equalTo(null), $this->equalTo('sonata')),
  622. array($this->equalTo('_per_page'), $this->equalTo(null), $this->equalTo(10)),
  623. array($this->equalTo('_page'), $this->equalTo(null), $this->equalTo(1))
  624. )
  625. ->will($this->returnValue(null));
  626. $datagrid->expects($this->once())
  627. ->method('buildPager')
  628. ->with()
  629. ->will($this->returnValue(null));
  630. $pager = $this->createMock('Sonata\AdminBundle\Datagrid\Pager');
  631. $datagrid->expects($this->once())
  632. ->method('getPager')
  633. ->with()
  634. ->will($this->returnValue($pager));
  635. $pager->expects($this->once())
  636. ->method('getResults')
  637. ->with()
  638. ->will($this->returnValue(array($entity)));
  639. $pager->expects($this->once())
  640. ->method('isLastPage')
  641. ->with()
  642. ->will($this->returnValue(true));
  643. $fieldDescription = $this->createMock('Sonata\AdminBundle\Admin\FieldDescriptionInterface');
  644. $fieldDescription->expects($this->once())
  645. ->method('getTargetEntity')
  646. ->will($this->returnValue('Sonata\AdminBundle\Tests\Fixtures\Bundle\Entity\Foo'));
  647. $fieldDescription->expects($this->once())
  648. ->method('getName')
  649. ->will($this->returnValue('barField'));
  650. $fieldDescription->expects($this->once())
  651. ->method('getAssociationAdmin')
  652. ->will($this->returnValue($targetAdmin));
  653. $this->admin->expects($this->once())
  654. ->method('getFormFieldDescriptions')
  655. ->will($this->returnValue(null));
  656. $this->admin->expects($this->once())
  657. ->method('getFormFieldDescription')
  658. ->with('barField')
  659. ->will($this->returnValue($fieldDescription));
  660. $form = $this->getMockBuilder('Symfony\Component\Form\Form')
  661. ->disableOriginalConstructor()
  662. ->getMock();
  663. $this->admin->expects($this->once())
  664. ->method('getForm')
  665. ->will($this->returnValue($form));
  666. $formType = $this->getMockBuilder('Symfony\Component\Form\Form')
  667. ->disableOriginalConstructor()
  668. ->getMock();
  669. $form->expects($this->once())
  670. ->method('get')
  671. ->with('barField')
  672. ->will($this->returnValue($formType));
  673. $formConfig = $this->getMockBuilder('Symfony\Component\Form\FormConfigInterface')
  674. ->disableOriginalConstructor()
  675. ->getMock();
  676. $formType->expects($this->once())
  677. ->method('getConfig')
  678. ->will($this->returnValue($formConfig));
  679. $formConfig->expects($this->any())
  680. ->method('getAttribute')
  681. ->will($this->returnCallback(function ($name, $default = null) {
  682. switch ($name) {
  683. case 'property':
  684. return 'foo';
  685. case 'callback':
  686. return;
  687. case 'minimum_input_length':
  688. return 3;
  689. case 'items_per_page':
  690. return 10;
  691. case 'req_param_name_page_number':
  692. return '_page';
  693. case 'to_string_callback':
  694. return;
  695. case 'disabled':
  696. return false;
  697. case 'target_admin_access_action':
  698. return 'list';
  699. default:
  700. throw new \RuntimeException(sprintf('Unkown parameter "%s" called.', $name));
  701. }
  702. }));
  703. $request = new Request(array(
  704. 'admin_code' => 'foo.admin',
  705. 'field' => 'barField',
  706. 'q' => 'sonata',
  707. ), array(), array(), array(), array(), array('REQUEST_METHOD' => 'GET', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'));
  708. $response = $this->controller->retrieveAutocompleteItemsAction($request);
  709. $this->isInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
  710. $this->assertSame('application/json', $response->headers->get('Content-Type'));
  711. $this->assertSame('{"status":"OK","more":false,"items":[{"id":123,"label":"FOO"}]}', $response->getContent());
  712. }
  713. /**
  714. * Symfony Validator has 2 API version (2.4 and 2.5)
  715. * This data provider ensure tests pass on each one.
  716. */
  717. public function getValidatorInterfaces()
  718. {
  719. $data = array();
  720. // For Symfony <= 2.8
  721. if (interface_exists('Symfony\Component\Validator\ValidatorInterface')) {
  722. $data['2.4'] = array('Symfony\Component\Validator\ValidatorInterface');
  723. }
  724. // For Symfony >= 2.5
  725. if (interface_exists('Symfony\Component\Validator\Validator\ValidatorInterface')) {
  726. $data['2.5'] = array('Symfony\Component\Validator\Validator\ValidatorInterface');
  727. }
  728. return $data;
  729. }
  730. }