TemplateExtension.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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\CoreBundle\Twig\Extension;
  11. use Sonata\CoreBundle\Model\Adapter\AdapterInterface;
  12. use Sonata\CoreBundle\Twig\TokenParser\TemplateBoxTokenParser;
  13. use Symfony\Component\Translation\TranslatorInterface;
  14. class TemplateExtension extends \Twig_Extension
  15. {
  16. /**
  17. * @var bool
  18. */
  19. protected $debug;
  20. /**
  21. * @var AdapterInterface
  22. */
  23. protected $modelAdapter;
  24. /**
  25. * @var TranslatorInterface
  26. */
  27. protected $translator;
  28. /**
  29. * @param bool $debug Is Symfony debug enabled?
  30. * @param TranslatorInterface $translator Symfony Translator service
  31. * @param AdapterInterface $modelAdapter A Sonata model adapter
  32. */
  33. public function __construct($debug, TranslatorInterface $translator, AdapterInterface $modelAdapter)
  34. {
  35. $this->debug = $debug;
  36. $this->translator = $translator;
  37. $this->modelAdapter = $modelAdapter;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function getFilters()
  43. {
  44. return array(
  45. new \Twig_SimpleFilter('sonata_slugify', array($this, 'slugify'), array('deprecated' => true, 'alternative' => 'slugify')),
  46. new \Twig_SimpleFilter('sonata_urlsafeid', array($this, 'getUrlsafeIdentifier')),
  47. );
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function getTokenParsers()
  53. {
  54. return array(
  55. new TemplateBoxTokenParser($this->debug, $this->translator),
  56. );
  57. }
  58. /**
  59. * Slugify a text.
  60. *
  61. * @param $text
  62. *
  63. * @return string
  64. */
  65. public function slugify($text)
  66. {
  67. // replace non letter or digits by -
  68. $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
  69. // trim
  70. $text = trim($text, '-');
  71. // transliterate
  72. if (function_exists('iconv')) {
  73. $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
  74. }
  75. // lowercase
  76. $text = strtolower($text);
  77. // remove unwanted characters
  78. $text = preg_replace('~[^-\w]+~', '', $text);
  79. return $text;
  80. }
  81. /**
  82. * @param $model
  83. *
  84. * @return string
  85. */
  86. public function getUrlsafeIdentifier($model)
  87. {
  88. return $this->modelAdapter->getUrlsafeIdentifier($model);
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function getName()
  94. {
  95. return 'sonata_core_template';
  96. }
  97. }