SonataAdminExtension.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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\Twig\Extension;
  11. use Doctrine\Common\Util\ClassUtils;
  12. use Psr\Log\LoggerInterface;
  13. use Sonata\AdminBundle\Admin\AdminInterface;
  14. use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
  15. use Sonata\AdminBundle\Admin\Pool;
  16. use Sonata\AdminBundle\Exception\NoValueException;
  17. use Symfony\Component\Translation\TranslatorInterface;
  18. /**
  19. * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  20. */
  21. class SonataAdminExtension extends \Twig_Extension
  22. {
  23. /**
  24. * @var Pool
  25. */
  26. protected $pool;
  27. /**
  28. * @var LoggerInterface
  29. */
  30. protected $logger;
  31. /**
  32. * @var TranslatorInterface|null
  33. */
  34. protected $translator;
  35. /**
  36. * @var string[]
  37. */
  38. private $xEditableTypeMapping = array();
  39. /**
  40. * @param Pool $pool
  41. * @param LoggerInterface $logger
  42. * @param TranslatorInterface $translator
  43. */
  44. public function __construct(Pool $pool, LoggerInterface $logger = null, TranslatorInterface $translator = null)
  45. {
  46. // NEXT_MAJOR: make the translator parameter required
  47. if (null === $translator) {
  48. @trigger_error(
  49. 'The $translator parameter will be required fields with the 4.0 release.',
  50. E_USER_DEPRECATED
  51. );
  52. }
  53. $this->pool = $pool;
  54. $this->logger = $logger;
  55. $this->translator = $translator;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function getFilters()
  61. {
  62. return array(
  63. new \Twig_SimpleFilter(
  64. 'render_list_element',
  65. array($this, 'renderListElement'),
  66. array(
  67. 'is_safe' => array('html'),
  68. 'needs_environment' => true,
  69. )
  70. ),
  71. new \Twig_SimpleFilter(
  72. 'render_view_element',
  73. array($this, 'renderViewElement'),
  74. array(
  75. 'is_safe' => array('html'),
  76. 'needs_environment' => true,
  77. )
  78. ),
  79. new \Twig_SimpleFilter(
  80. 'render_view_element_compare',
  81. array($this, 'renderViewElementCompare'),
  82. array(
  83. 'is_safe' => array('html'),
  84. 'needs_environment' => true,
  85. )
  86. ),
  87. new \Twig_SimpleFilter(
  88. 'render_relation_element',
  89. array($this, 'renderRelationElement')
  90. ),
  91. new \Twig_SimpleFilter(
  92. 'sonata_urlsafeid',
  93. array($this, 'getUrlsafeIdentifier')
  94. ),
  95. new \Twig_SimpleFilter(
  96. 'sonata_xeditable_type',
  97. array($this, 'getXEditableType')
  98. ),
  99. new \Twig_SimpleFilter(
  100. 'sonata_xeditable_choices',
  101. array($this, 'getXEditableChoices')
  102. ),
  103. );
  104. }
  105. /**
  106. * {@inheritdoc}
  107. */
  108. public function getName()
  109. {
  110. return 'sonata_admin';
  111. }
  112. /**
  113. * render a list element from the FieldDescription.
  114. *
  115. * @param mixed $object
  116. * @param FieldDescriptionInterface $fieldDescription
  117. * @param array $params
  118. *
  119. * @return string
  120. */
  121. public function renderListElement(
  122. \Twig_Environment $environment,
  123. $object,
  124. FieldDescriptionInterface $fieldDescription,
  125. $params = array()
  126. ) {
  127. $template = $this->getTemplate(
  128. $fieldDescription,
  129. $fieldDescription->getAdmin()->getTemplate('base_list_field'),
  130. $environment
  131. );
  132. return $this->output($fieldDescription, $template, array_merge($params, array(
  133. 'admin' => $fieldDescription->getAdmin(),
  134. 'object' => $object,
  135. 'value' => $this->getValueFromFieldDescription($object, $fieldDescription),
  136. 'field_description' => $fieldDescription,
  137. )), $environment);
  138. }
  139. /**
  140. * @param FieldDescriptionInterface $fieldDescription
  141. * @param \Twig_Template $template
  142. * @param array $parameters
  143. *
  144. * @return string
  145. */
  146. public function output(
  147. FieldDescriptionInterface $fieldDescription,
  148. \Twig_Template $template,
  149. array $parameters,
  150. \Twig_Environment $environment
  151. ) {
  152. $content = $template->render($parameters);
  153. if ($environment->isDebug()) {
  154. $commentTemplate = <<<'EOT'
  155. <!-- START
  156. fieldName: %s
  157. template: %s
  158. compiled template: %s
  159. -->
  160. %s
  161. <!-- END - fieldName: %s -->
  162. EOT;
  163. return sprintf(
  164. $commentTemplate,
  165. $fieldDescription->getFieldName(),
  166. $fieldDescription->getTemplate(),
  167. $template->getTemplateName(),
  168. $content,
  169. $fieldDescription->getFieldName()
  170. );
  171. }
  172. return $content;
  173. }
  174. /**
  175. * return the value related to FieldDescription, if the associated object does no
  176. * exists => a temporary one is created.
  177. *
  178. * @param object $object
  179. * @param FieldDescriptionInterface $fieldDescription
  180. * @param array $params
  181. *
  182. * @throws \RuntimeException
  183. *
  184. * @return mixed
  185. */
  186. public function getValueFromFieldDescription(
  187. $object,
  188. FieldDescriptionInterface $fieldDescription,
  189. array $params = array()
  190. ) {
  191. if (isset($params['loop']) && $object instanceof \ArrayAccess) {
  192. throw new \RuntimeException('remove the loop requirement');
  193. }
  194. $value = null;
  195. try {
  196. $value = $fieldDescription->getValue($object);
  197. } catch (NoValueException $e) {
  198. if ($fieldDescription->getAssociationAdmin()) {
  199. $value = $fieldDescription->getAssociationAdmin()->getNewInstance();
  200. }
  201. }
  202. return $value;
  203. }
  204. /**
  205. * render a view element.
  206. *
  207. * @param FieldDescriptionInterface $fieldDescription
  208. * @param mixed $object
  209. *
  210. * @return string
  211. */
  212. public function renderViewElement(
  213. \Twig_Environment $environment,
  214. FieldDescriptionInterface $fieldDescription,
  215. $object
  216. ) {
  217. $template = $this->getTemplate(
  218. $fieldDescription,
  219. 'SonataAdminBundle:CRUD:base_show_field.html.twig',
  220. $environment
  221. );
  222. try {
  223. $value = $fieldDescription->getValue($object);
  224. } catch (NoValueException $e) {
  225. $value = null;
  226. }
  227. return $this->output($fieldDescription, $template, array(
  228. 'field_description' => $fieldDescription,
  229. 'object' => $object,
  230. 'value' => $value,
  231. 'admin' => $fieldDescription->getAdmin(),
  232. ), $environment);
  233. }
  234. /**
  235. * render a compared view element.
  236. *
  237. * @param FieldDescriptionInterface $fieldDescription
  238. * @param mixed $baseObject
  239. * @param mixed $compareObject
  240. *
  241. * @return string
  242. */
  243. public function renderViewElementCompare(
  244. \Twig_Environment $environment,
  245. FieldDescriptionInterface $fieldDescription,
  246. $baseObject,
  247. $compareObject
  248. ) {
  249. $template = $this->getTemplate(
  250. $fieldDescription,
  251. 'SonataAdminBundle:CRUD:base_show_field.html.twig',
  252. $environment
  253. );
  254. try {
  255. $baseValue = $fieldDescription->getValue($baseObject);
  256. } catch (NoValueException $e) {
  257. $baseValue = null;
  258. }
  259. try {
  260. $compareValue = $fieldDescription->getValue($compareObject);
  261. } catch (NoValueException $e) {
  262. $compareValue = null;
  263. }
  264. $baseValueOutput = $template->render(array(
  265. 'admin' => $fieldDescription->getAdmin(),
  266. 'field_description' => $fieldDescription,
  267. 'value' => $baseValue,
  268. ));
  269. $compareValueOutput = $template->render(array(
  270. 'field_description' => $fieldDescription,
  271. 'admin' => $fieldDescription->getAdmin(),
  272. 'value' => $compareValue,
  273. ));
  274. // Compare the rendered output of both objects by using the (possibly) overridden field block
  275. $isDiff = $baseValueOutput !== $compareValueOutput;
  276. return $this->output($fieldDescription, $template, array(
  277. 'field_description' => $fieldDescription,
  278. 'value' => $baseValue,
  279. 'value_compare' => $compareValue,
  280. 'is_diff' => $isDiff,
  281. 'admin' => $fieldDescription->getAdmin(),
  282. ), $environment);
  283. }
  284. /**
  285. * @throws \RuntimeException
  286. *
  287. * @param mixed $element
  288. * @param FieldDescriptionInterface $fieldDescription
  289. *
  290. * @return mixed
  291. */
  292. public function renderRelationElement($element, FieldDescriptionInterface $fieldDescription)
  293. {
  294. if (!is_object($element)) {
  295. return $element;
  296. }
  297. $propertyPath = $fieldDescription->getOption('associated_property');
  298. if (null === $propertyPath) {
  299. // For BC kept associated_tostring option behavior
  300. $method = $fieldDescription->getOption('associated_tostring');
  301. if ($method) {
  302. @trigger_error(
  303. 'Option "associated_tostring" is deprecated since version 2.3 and will be removed in 4.0. '
  304. .'Use "associated_property" instead.',
  305. E_USER_DEPRECATED
  306. );
  307. } else {
  308. $method = '__toString';
  309. }
  310. if (!method_exists($element, $method)) {
  311. throw new \RuntimeException(sprintf(
  312. 'You must define an `associated_property` option or '.
  313. 'create a `%s::__toString` method to the field option %s from service %s is ',
  314. get_class($element),
  315. $fieldDescription->getName(),
  316. $fieldDescription->getAdmin()->getCode()
  317. ));
  318. }
  319. return call_user_func(array($element, $method));
  320. }
  321. if (is_callable($propertyPath)) {
  322. return $propertyPath($element);
  323. }
  324. return $this->pool->getPropertyAccessor()->getValue($element, $propertyPath);
  325. }
  326. /**
  327. * Get the identifiers as a string that is save to use in an url.
  328. *
  329. * @param object $model
  330. * @param AdminInterface $admin
  331. *
  332. * @return string string representation of the id that is save to use in an url
  333. */
  334. public function getUrlsafeIdentifier($model, AdminInterface $admin = null)
  335. {
  336. if (is_null($admin)) {
  337. $admin = $this->pool->getAdminByClass(ClassUtils::getClass($model));
  338. }
  339. return $admin->getUrlsafeIdentifier($model);
  340. }
  341. /**
  342. * @param string[] $xEditableTypeMapping
  343. */
  344. public function setXEditableTypeMapping($xEditableTypeMapping)
  345. {
  346. $this->xEditableTypeMapping = $xEditableTypeMapping;
  347. }
  348. /**
  349. * @param $type
  350. *
  351. * @return string|bool
  352. */
  353. public function getXEditableType($type)
  354. {
  355. return isset($this->xEditableTypeMapping[$type]) ? $this->xEditableTypeMapping[$type] : false;
  356. }
  357. /**
  358. * Return xEditable choices based on the field description choices options & catalogue options.
  359. * With the following choice options:
  360. * ['Status1' => 'Alias1', 'Status2' => 'Alias2']
  361. * The method will return:
  362. * [['value' => 'Status1', 'text' => 'Alias1'], ['value' => 'Status2', 'text' => 'Alias2']].
  363. *
  364. * @param FieldDescriptionInterface $fieldDescription
  365. *
  366. * @return array
  367. */
  368. public function getXEditableChoices(FieldDescriptionInterface $fieldDescription)
  369. {
  370. $choices = $fieldDescription->getOption('choices', array());
  371. $catalogue = $fieldDescription->getOption('catalogue');
  372. $xEditableChoices = array();
  373. if (!empty($choices)) {
  374. reset($choices);
  375. $first = current($choices);
  376. // the choices are already in the right format
  377. if (is_array($first) && array_key_exists('value', $first) && array_key_exists('text', $first)) {
  378. $xEditableChoices = $choices;
  379. } else {
  380. foreach ($choices as $value => $text) {
  381. if ($catalogue) {
  382. if (null !== $this->translator) {
  383. $text = $this->translator->trans($text, array(), $catalogue);
  384. // NEXT_MAJOR: Remove this check
  385. } elseif (method_exists($fieldDescription->getAdmin(), 'trans')) {
  386. $text = $fieldDescription->getAdmin()->trans($text, array(), $catalogue);
  387. }
  388. }
  389. $xEditableChoices[] = array(
  390. 'value' => $value,
  391. 'text' => $text,
  392. );
  393. }
  394. }
  395. }
  396. return $xEditableChoices;
  397. }
  398. /**
  399. * Get template.
  400. *
  401. * @param FieldDescriptionInterface $fieldDescription
  402. * @param string $defaultTemplate
  403. *
  404. * @return \Twig_TemplateInterface
  405. */
  406. protected function getTemplate(
  407. FieldDescriptionInterface $fieldDescription,
  408. $defaultTemplate,
  409. \Twig_Environment $environment
  410. ) {
  411. $templateName = $fieldDescription->getTemplate() ?: $defaultTemplate;
  412. try {
  413. $template = $environment->loadTemplate($templateName);
  414. } catch (\Twig_Error_Loader $e) {
  415. @trigger_error(
  416. 'Relying on default template loading on field template loading exception '.
  417. 'is deprecated since 3.1 and will be removed in 4.0. '.
  418. 'A \Twig_Error_Loader exception will be thrown instead',
  419. E_USER_DEPRECATED
  420. );
  421. $template = $environment->loadTemplate($defaultTemplate);
  422. if (null !== $this->logger) {
  423. $this->logger->warning(sprintf(
  424. 'An error occured trying to load the template "%s" for the field "%s", '.
  425. 'the default template "%s" was used instead.',
  426. $templateName,
  427. $fieldDescription->getFieldName(),
  428. $defaultTemplate
  429. ), array('exception' => $e));
  430. }
  431. }
  432. return $template;
  433. }
  434. }