SonataAdminExtension.php 11 KB

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