PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/sonata-project/admin-bundle/Sonata/AdminBundle/Controller/CRUDController.php

https://bitbucket.org/ingsol/music_sonata
PHP | 587 lines | 347 code | 113 blank | 127 comment | 57 complexity | 184a1e9cc307ebc0fa9ffa59d7176e6a MD5 | raw file
Possible License(s): BSD-2-Clause, LGPL-2.1, Apache-2.0, JSON, LGPL-3.0, BSD-3-Clause
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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\Controller;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  17. use Sonata\AdminBundle\Exception\ModelManagerException;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  20. class CRUDController extends Controller
  21. {
  22. /**
  23. * The related Admin class
  24. *
  25. * @var \Sonata\AdminBundle\Admin\AdminInterface
  26. */
  27. protected $admin;
  28. /**
  29. * @param mixed $data
  30. * @param integer $status
  31. * @param array $headers
  32. *
  33. * @return Response with json encoded data
  34. */
  35. public function renderJson($data, $status = 200, $headers = array())
  36. {
  37. // fake content-type so browser does not show the download popup when this
  38. // response is rendered through an iframe (used by the jquery.form.js plugin)
  39. // => don't know yet if it is the best solution
  40. if ($this->get('request')->get('_xml_http_request')
  41. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  42. $headers['Content-Type'] = 'text/plain';
  43. } else {
  44. $headers['Content-Type'] = 'application/json';
  45. }
  46. return new Response(json_encode($data), $status, $headers);
  47. }
  48. /**
  49. *
  50. * @return boolean true if the request is done by an ajax like query
  51. */
  52. public function isXmlHttpRequest()
  53. {
  54. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  55. }
  56. /**
  57. * Sets the Container associated with this Controller.
  58. *
  59. * @param ContainerInterface $container A ContainerInterface instance
  60. */
  61. public function setContainer(ContainerInterface $container = null)
  62. {
  63. $this->container = $container;
  64. $this->configure();
  65. }
  66. /**
  67. * Contextualize the admin class depends on the current request
  68. *
  69. * @throws \RuntimeException
  70. * @return void
  71. */
  72. public function configure()
  73. {
  74. $adminCode = $this->container->get('request')->get('_sonata_admin');
  75. if (!$adminCode) {
  76. throw new \RuntimeException(sprintf('There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`', get_class($this), $this->container->get('request')->get('_route')));
  77. }
  78. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  79. if (!$this->admin) {
  80. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  81. }
  82. $rootAdmin = $this->admin;
  83. if ($this->admin->isChild()) {
  84. $this->admin->setCurrentChild(true);
  85. $rootAdmin = $rootAdmin->getParent();
  86. }
  87. $request = $this->container->get('request');
  88. $rootAdmin->setRequest($request);
  89. if ($request->get('uniqid')) {
  90. $this->admin->setUniqid($request->get('uniqid'));
  91. }
  92. }
  93. /**
  94. * return the base template name
  95. *
  96. * @return string the template name
  97. */
  98. public function getBaseTemplate()
  99. {
  100. if ($this->isXmlHttpRequest()) {
  101. return $this->admin->getTemplate('ajax');
  102. }
  103. return $this->admin->getTemplate('layout');
  104. }
  105. /**
  106. * @param string $view
  107. * @param array $parameters
  108. * @param null|\Symfony\Component\HttpFoundation\Response $response
  109. *
  110. * @return Response
  111. */
  112. public function render($view, array $parameters = array(), Response $response = null)
  113. {
  114. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  115. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  116. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  117. return parent::render($view, $parameters);
  118. }
  119. /**
  120. * return the Response object associated to the list action
  121. *
  122. * @return Response
  123. */
  124. public function listAction()
  125. {
  126. if (false === $this->admin->isGranted('LIST')) {
  127. throw new AccessDeniedException();
  128. }
  129. $datagrid = $this->admin->getDatagrid();
  130. $formView = $datagrid->getForm()->createView();
  131. // set the theme for the current Admin Form
  132. $this->get('twig')->getExtension('form')->setTheme($formView, $this->admin->getFilterTheme());
  133. return $this->render($this->admin->getListTemplate(), array(
  134. 'action' => 'list',
  135. 'form' => $formView,
  136. 'datagrid' => $datagrid
  137. ));
  138. }
  139. /**
  140. * execute a batch delete
  141. *
  142. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  143. *
  144. * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $query
  145. *
  146. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  147. */
  148. public function batchActionDelete(ProxyQueryInterface $query)
  149. {
  150. if (false === $this->admin->isGranted('DELETE')) {
  151. throw new AccessDeniedException();
  152. }
  153. $modelManager = $this->admin->getModelManager();
  154. try {
  155. $modelManager->batchDelete($this->admin->getClass(), $query);
  156. $this->get('session')->setFlash('sonata_flash_success', 'flash_batch_delete_success');
  157. } catch ( ModelManagerException $e ) {
  158. $this->get('session')->setFlash('sonata_flash_error', 'flash_batch_delete_error');
  159. }
  160. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  161. }
  162. /**
  163. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  164. *
  165. * @param mixed $id
  166. *
  167. * @return Response|RedirectResponse
  168. */
  169. public function deleteAction($id)
  170. {
  171. $id = $this->get('request')->get($this->admin->getIdParameter());
  172. $object = $this->admin->getObject($id);
  173. if (!$object) {
  174. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  175. }
  176. if (false === $this->admin->isGranted('DELETE', $object)) {
  177. throw new AccessDeniedException();
  178. }
  179. if ($this->getRequest()->getMethod() == 'DELETE') {
  180. try {
  181. $this->admin->delete($object);
  182. $this->get('session')->setFlash('sonata_flash_success', 'flash_delete_success');
  183. } catch (ModelManagerException $e) {
  184. $this->get('session')->setFlash('sonata_flash_error', 'flash_delete_error');
  185. }
  186. return new RedirectResponse($this->admin->generateUrl('list'));
  187. }
  188. return $this->render('SonataAdminBundle:CRUD:delete.html.twig', array(
  189. 'object' => $object,
  190. 'action' => 'delete'
  191. ));
  192. }
  193. /**
  194. * return the Response object associated to the edit action
  195. *
  196. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  197. *
  198. * @param mixed $id
  199. *
  200. * @return \Symfony\Component\HttpFoundation\Response
  201. */
  202. public function editAction($id = null)
  203. {
  204. $id = $this->get('request')->get($this->admin->getIdParameter());
  205. $object = $this->admin->getObject($id);
  206. if (!$object) {
  207. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  208. }
  209. if (false === $this->admin->isGranted('EDIT', $object)) {
  210. throw new AccessDeniedException();
  211. }
  212. $this->admin->setSubject($object);
  213. $form = $this->admin->getForm();
  214. $form->setData($object);
  215. if ($this->get('request')->getMethod() == 'POST') {
  216. $form->bindRequest($this->get('request'));
  217. if ($form->isValid()) {
  218. $this->admin->update($object);
  219. $this->get('session')->setFlash('sonata_flash_success', 'flash_edit_success');
  220. if ($this->isXmlHttpRequest()) {
  221. return $this->renderJson(array(
  222. 'result' => 'ok',
  223. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  224. ));
  225. }
  226. // redirect to edit mode
  227. return $this->redirectTo($object);
  228. }
  229. $this->get('session')->setFlash('sonata_flash_error', 'flash_edit_error');
  230. }
  231. $view = $form->createView();
  232. // set the theme for the current Admin Form
  233. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  234. return $this->render($this->admin->getEditTemplate(), array(
  235. 'action' => 'edit',
  236. 'form' => $view,
  237. 'object' => $object,
  238. ));
  239. }
  240. /**
  241. * redirect the user depend on this choice
  242. *
  243. * @param object $object
  244. *
  245. * @return \Symfony\Component\HttpFoundation\Response
  246. */
  247. public function redirectTo($object)
  248. {
  249. $url = false;
  250. if ($this->get('request')->get('btn_update_and_list')) {
  251. $url = $this->admin->generateUrl('list');
  252. }
  253. if ($this->get('request')->get('btn_create_and_create')) {
  254. $url = $this->admin->generateUrl('create');
  255. }
  256. if (!$url) {
  257. $url = $this->admin->generateObjectUrl('edit', $object);
  258. }
  259. return new RedirectResponse($url);
  260. }
  261. /**
  262. * return the Response object associated to the batch action
  263. *
  264. * @throws \RuntimeException
  265. * @return \Symfony\Component\HttpFoundation\Response
  266. */
  267. public function batchAction()
  268. {
  269. if ($this->get('request')->getMethod() != 'POST') {
  270. throw new \RuntimeException('invalid request type, POST expected');
  271. }
  272. $confirmation = $this->get('request')->get('confirmation', false);
  273. if ($data = json_decode($this->get('request')->get('data'), true)) {
  274. $action = $data['action'];
  275. $idx = $data['idx'];
  276. $all_elements = $data['all_elements'];
  277. $this->get('request')->request->replace($data);
  278. } else {
  279. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  280. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  281. $action = $this->get('request')->get('action');
  282. $idx = $this->get('request')->get('idx');
  283. $all_elements = $this->get('request')->get('all_elements');
  284. $data = $this->get('request')->request->all();
  285. }
  286. $batchActions = $this->admin->getBatchActions();
  287. if (!array_key_exists($action, $batchActions)) {
  288. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  289. }
  290. $camelizedAction = \Sonata\AdminBundle\Admin\BaseFieldDescription::camelize($action);
  291. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  292. if (method_exists($this, $isRelevantAction)) {
  293. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  294. } else {
  295. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  296. }
  297. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  298. $nonRelevantMessage = 'flash_batch_empty';
  299. }
  300. if (true !== $nonRelevantMessage) {
  301. $this->get('session')->setFlash('sonata_flash_info', $nonRelevantMessage);
  302. return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
  303. }
  304. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  305. if ($askConfirmation && $confirmation != 'ok') {
  306. $datagrid = $this->admin->getDatagrid();
  307. $formView = $datagrid->getForm()->createView();
  308. return $this->render('SonataAdminBundle:CRUD:batch_confirmation.html.twig', array(
  309. 'action' => 'list',
  310. 'datagrid' => $datagrid,
  311. 'form' => $formView,
  312. 'data' => json_encode($data),
  313. ));
  314. }
  315. // execute the action, batchActionXxxxx
  316. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  317. if (!method_exists($this, $final_action)) {
  318. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  319. }
  320. $datagrid = $this->admin->getDatagrid();
  321. $datagrid->buildPager();
  322. $query = $datagrid->getQuery();
  323. $query->setFirstResult(null);
  324. $query->setMaxResults(null);
  325. if (count($idx) > 0) {
  326. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  327. } else if (!$all_elements) {
  328. $query = null;
  329. }
  330. return call_user_func(array($this, $final_action), $query);
  331. }
  332. /**
  333. * return the Response object associated to the create action
  334. *
  335. * @return \Symfony\Component\HttpFoundation\Response
  336. */
  337. public function createAction()
  338. {
  339. if (false === $this->admin->isGranted('CREATE')) {
  340. throw new AccessDeniedException();
  341. }
  342. $object = $this->admin->getNewInstance();
  343. $this->admin->setSubject($object);
  344. $form = $this->admin->getForm();
  345. $form->setData($object);
  346. if ($this->get('request')->getMethod() == 'POST') {
  347. $form->bindRequest($this->get('request'));
  348. if ($form->isValid()) {
  349. $this->admin->create($object);
  350. if ($this->isXmlHttpRequest()) {
  351. return $this->renderJson(array(
  352. 'result' => 'ok',
  353. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  354. ));
  355. }
  356. $this->get('session')->setFlash('sonata_flash_success','flash_create_success');
  357. // redirect to edit mode
  358. return $this->redirectTo($object);
  359. }
  360. $this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
  361. }
  362. $view = $form->createView();
  363. // set the theme for the current Admin Form
  364. $this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
  365. return $this->render($this->admin->getEditTemplate(), array(
  366. 'action' => 'create',
  367. 'form' => $view,
  368. 'object' => $object,
  369. ));
  370. }
  371. /**
  372. * return the Response object associated to the view action
  373. *
  374. * @return \Symfony\Component\HttpFoundation\Response
  375. */
  376. public function showAction($id = null)
  377. {
  378. $id = $this->get('request')->get($this->admin->getIdParameter());
  379. $object = $this->admin->getObject($id);
  380. if (!$object) {
  381. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  382. }
  383. if (false === $this->admin->isGranted('VIEW', $object)) {
  384. throw new AccessDeniedException();
  385. }
  386. $this->admin->setSubject($object);
  387. return $this->render($this->admin->getShowTemplate(), array(
  388. 'action' => 'show',
  389. 'object' => $object,
  390. 'elements' => $this->admin->getShow(),
  391. ));
  392. }
  393. /**
  394. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  395. *
  396. * @param mixed $id
  397. *
  398. * @return Response
  399. */
  400. public function historyAction($id = null)
  401. {
  402. if (false === $this->admin->isGranted('EDIT')) {
  403. throw new AccessDeniedException();
  404. }
  405. $id = $this->get('request')->get($this->admin->getIdParameter());
  406. $object = $this->admin->getObject($id);
  407. if (!$object) {
  408. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  409. }
  410. $manager = $this->get('sonata.admin.audit.manager');
  411. if (!$manager->hasReader($this->admin->getClass())) {
  412. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  413. }
  414. $reader = $manager->getReader($this->admin->getClass());
  415. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  416. return $this->render($this->admin->getTemplate('history'), array(
  417. 'action' => 'history',
  418. 'object' => $object,
  419. 'revisions' => $revisions,
  420. ));
  421. }
  422. /**
  423. * @param null $id
  424. * @param string $revision
  425. *
  426. * @return Response
  427. */
  428. public function historyViewRevisionAction($id = null, $revision = null)
  429. {
  430. if (false === $this->admin->isGranted('EDIT')) {
  431. throw new AccessDeniedException();
  432. }
  433. $id = $this->get('request')->get($this->admin->getIdParameter());
  434. $object = $this->admin->getObject($id);
  435. if (!$object) {
  436. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  437. }
  438. $manager = $this->get('sonata.admin.audit.manager');
  439. if (!$manager->hasReader($this->admin->getClass())) {
  440. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  441. }
  442. $reader = $manager->getReader($this->admin->getClass());
  443. // retrieve the revisioned object
  444. $object = $reader->find($this->admin->getClass(), $id, $revision);
  445. if (!$object) {
  446. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  447. }
  448. $this->admin->setSubject($object);
  449. return $this->render($this->admin->getShowTemplate(), array(
  450. 'action' => 'show',
  451. 'object' => $object,
  452. 'elements' => $this->admin->getShow(),
  453. ));
  454. }
  455. /**
  456. * @param \Symfony\Component\HttpFoundation\Request $request
  457. * @return \Symfony\Component\HttpFoundation\Response
  458. */
  459. public function exportAction(Request $request)
  460. {
  461. $format = $request->get('format');
  462. $allowedExportFormats = (array) $this->admin->getExportFormats();
  463. if(!in_array($format, $allowedExportFormats) ) {
  464. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  465. }
  466. $filename = sprintf('export_%s_%s.%s',
  467. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  468. date('Y_m_d_H_i_s', strtotime('now')),
  469. $format
  470. );
  471. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  472. }
  473. }