SonataAdminExtension.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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\PropertyAccess\PropertyAccess;
  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 \Twig_Environment
  27. */
  28. protected $environment;
  29. /**
  30. * @var Pool
  31. */
  32. protected $pool;
  33. /**
  34. * @var LoggerInterface
  35. */
  36. protected $logger;
  37. /**
  38. * @param Pool $pool
  39. * @param LoggerInterface $logger
  40. */
  41. public function __construct(Pool $pool, LoggerInterface $logger = null)
  42. {
  43. $this->pool = $pool;
  44. $this->logger = $logger;
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function initRuntime(\Twig_Environment $environment)
  50. {
  51. $this->environment = $environment;
  52. }
  53. /**
  54. * {@inheritDoc}
  55. */
  56. public function getFilters()
  57. {
  58. return array(
  59. 'render_list_element' => new \Twig_Filter_Method($this, 'renderListElement', array('is_safe' => array('html'))),
  60. 'render_view_element' => new \Twig_Filter_Method($this, 'renderViewElement', array('is_safe' => array('html'))),
  61. 'render_view_element_compare' => new \Twig_Filter_Method($this, 'renderViewElementCompare', array('is_safe' => array('html'))),
  62. 'render_relation_element' => new \Twig_Filter_Method($this, 'renderRelationElement'),
  63. 'sonata_urlsafeid' => new \Twig_Filter_Method($this, 'getUrlsafeIdentifier'),
  64. 'sonata_xeditable_type' => new \Twig_Filter_Method($this, 'getXEditableType'),
  65. );
  66. }
  67. /**
  68. * {@inheritDoc}
  69. */
  70. public function getFunctions()
  71. {
  72. return array();
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. public function getTokenParsers()
  78. {
  79. return array();
  80. }
  81. /**
  82. * {@inheritDoc}
  83. */
  84. public function getName()
  85. {
  86. return 'sonata_admin';
  87. }
  88. /**
  89. * Get template.
  90. *
  91. * @param FieldDescriptionInterface $fieldDescription
  92. * @param string $defaultTemplate
  93. *
  94. * @return \Twig_TemplateInterface
  95. */
  96. protected function getTemplate(FieldDescriptionInterface $fieldDescription, $defaultTemplate)
  97. {
  98. $templateName = $fieldDescription->getTemplate() ?: $defaultTemplate;
  99. try {
  100. $template = $this->environment->loadTemplate($templateName);
  101. } catch (\Twig_Error_Loader $e) {
  102. $template = $this->environment->loadTemplate($defaultTemplate);
  103. if (null !== $this->logger) {
  104. $this->logger->warning(sprintf('An error occured trying to load the template "%s" for the field "%s", the default template "%s" was used instead: "%s". ', $templateName, $fieldDescription->getFieldName(), $defaultTemplate, $e->getMessage()));
  105. }
  106. }
  107. return $template;
  108. }
  109. /**
  110. * render a list element from the FieldDescription.
  111. *
  112. * @param mixed $object
  113. * @param FieldDescriptionInterface $fieldDescription
  114. * @param array $params
  115. *
  116. * @return string
  117. */
  118. public function renderListElement($object, FieldDescriptionInterface $fieldDescription, $params = array())
  119. {
  120. $template = $this->getTemplate($fieldDescription, $fieldDescription->getAdmin()->getTemplate('base_list_field'));
  121. return $this->output($fieldDescription, $template, array_merge($params, array(
  122. 'admin' => $fieldDescription->getAdmin(),
  123. 'object' => $object,
  124. 'value' => $this->getValueFromFieldDescription($object, $fieldDescription),
  125. 'field_description' => $fieldDescription,
  126. )));
  127. }
  128. /**
  129. * @param FieldDescriptionInterface $fieldDescription
  130. * @param \Twig_TemplateInterface $template
  131. * @param array $parameters
  132. *
  133. * @return string
  134. */
  135. public function output(FieldDescriptionInterface $fieldDescription, \Twig_TemplateInterface $template, array $parameters = array())
  136. {
  137. $content = $template->render($parameters);
  138. if ($this->environment->isDebug()) {
  139. return sprintf("\n<!-- START \n fieldName: %s\n template: %s\n compiled template: %s\n -->\n%s\n<!-- END - fieldName: %s -->",
  140. $fieldDescription->getFieldName(),
  141. $fieldDescription->getTemplate(),
  142. $template->getTemplateName(),
  143. $content,
  144. $fieldDescription->getFieldName()
  145. );
  146. }
  147. return $content;
  148. }
  149. /**
  150. * return the value related to FieldDescription, if the associated object does no
  151. * exists => a temporary one is created.
  152. *
  153. * @param object $object
  154. * @param FieldDescriptionInterface $fieldDescription
  155. * @param array $params
  156. *
  157. * @throws \RuntimeException
  158. *
  159. * @return mixed
  160. */
  161. public function getValueFromFieldDescription($object, FieldDescriptionInterface $fieldDescription, array $params = array())
  162. {
  163. if (isset($params['loop']) && $object instanceof \ArrayAccess) {
  164. throw new \RuntimeException('remove the loop requirement');
  165. }
  166. $value = null;
  167. try {
  168. $value = $fieldDescription->getValue($object);
  169. } catch (NoValueException $e) {
  170. if ($fieldDescription->getAssociationAdmin()) {
  171. $value = $fieldDescription->getAssociationAdmin()->getNewInstance();
  172. }
  173. }
  174. return $value;
  175. }
  176. /**
  177. * render a view element.
  178. *
  179. * @param FieldDescriptionInterface $fieldDescription
  180. * @param mixed $object
  181. *
  182. * @return string
  183. */
  184. public function renderViewElement(FieldDescriptionInterface $fieldDescription, $object)
  185. {
  186. $template = $this->getTemplate($fieldDescription, 'SonataAdminBundle:CRUD:base_show_field.html.twig');
  187. try {
  188. $value = $fieldDescription->getValue($object);
  189. } catch (NoValueException $e) {
  190. $value = null;
  191. }
  192. return $this->output($fieldDescription, $template, array(
  193. 'field_description' => $fieldDescription,
  194. 'object' => $object,
  195. 'value' => $value,
  196. 'admin' => $fieldDescription->getAdmin(),
  197. ));
  198. }
  199. /**
  200. * render a compared view element.
  201. *
  202. * @param FieldDescriptionInterface $fieldDescription
  203. * @param mixed $baseObject
  204. * @param mixed $compareObject
  205. *
  206. * @return string
  207. */
  208. public function renderViewElementCompare(FieldDescriptionInterface $fieldDescription, $baseObject, $compareObject)
  209. {
  210. $template = $this->getTemplate($fieldDescription, 'SonataAdminBundle:CRUD:base_show_field.html.twig');
  211. try {
  212. $baseValue = $fieldDescription->getValue($baseObject);
  213. } catch (NoValueException $e) {
  214. $baseValue = null;
  215. }
  216. try {
  217. $compareValue = $fieldDescription->getValue($compareObject);
  218. } catch (NoValueException $e) {
  219. $compareValue = null;
  220. }
  221. $baseValueOutput = $template->render(array(
  222. 'admin' => $fieldDescription->getAdmin(),
  223. 'field_description' => $fieldDescription,
  224. 'value' => $baseValue,
  225. ));
  226. $compareValueOutput = $template->render(array(
  227. 'field_description' => $fieldDescription,
  228. 'admin' => $fieldDescription->getAdmin(),
  229. 'value' => $compareValue,
  230. ));
  231. // Compare the rendered output of both objects by using the (possibly) overridden field block
  232. $isDiff = $baseValueOutput !== $compareValueOutput;
  233. return $this->output($fieldDescription, $template, array(
  234. 'field_description' => $fieldDescription,
  235. 'value' => $baseValue,
  236. 'value_compare' => $compareValue,
  237. 'is_diff' => $isDiff,
  238. 'admin' => $fieldDescription->getAdmin(),
  239. ));
  240. }
  241. /**
  242. * @throws \RunTimeException
  243. *
  244. * @param mixed $element
  245. * @param FieldDescriptionInterface $fieldDescription
  246. *
  247. * @return mixed
  248. */
  249. public function renderRelationElement($element, FieldDescriptionInterface $fieldDescription)
  250. {
  251. if (!is_object($element)) {
  252. return $element;
  253. }
  254. $propertyPath = $fieldDescription->getOption('associated_property');
  255. if (null === $propertyPath) {
  256. // For BC kept associated_tostring option behavior
  257. $method = $fieldDescription->getOption('associated_tostring', '__toString');
  258. if (!method_exists($element, $method)) {
  259. throw new \RuntimeException(sprintf(
  260. 'You must define an `associated_property` option or create a `%s::__toString` method to the field option %s from service %s is ',
  261. get_class($element),
  262. $fieldDescription->getName(),
  263. $fieldDescription->getAdmin()->getCode()
  264. ));
  265. }
  266. return call_user_func(array($element, $method));
  267. }
  268. if (is_callable($propertyPath)) {
  269. return $propertyPath($element);
  270. }
  271. return PropertyAccess::createPropertyAccessor()->getValue($element, $propertyPath);
  272. }
  273. /**
  274. * Get the identifiers as a string that is save to use in an url.
  275. *
  276. * @param object $model
  277. * @param AdminInterface $admin
  278. *
  279. * @return string string representation of the id that is save to use in an url
  280. */
  281. public function getUrlsafeIdentifier($model, AdminInterface $admin = null)
  282. {
  283. if (is_null($admin)) {
  284. $admin = $this->pool->getAdminByClass(
  285. ClassUtils::getClass($model)
  286. );
  287. }
  288. return $admin->getUrlsafeIdentifier($model);
  289. }
  290. /**
  291. * @param $type
  292. *
  293. * @return string|bool
  294. */
  295. public function getXEditableType($type)
  296. {
  297. $mapping = array(
  298. 'boolean' => 'select',
  299. 'text' => 'text',
  300. 'textarea' => 'textarea',
  301. 'html' => 'textarea',
  302. 'email' => 'email',
  303. 'string' => 'text',
  304. 'smallint' => 'text',
  305. 'bigint' => 'text',
  306. 'integer' => 'number',
  307. 'decimal' => 'number',
  308. 'currency' => 'number',
  309. 'percent' => 'number',
  310. 'url' => 'url',
  311. );
  312. return isset($mapping[$type]) ? $mapping[$type] : false;
  313. }
  314. }