SonataAdminExtension.php 15 KB

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