StringExtension.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) Fabien Potencier
  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 Twig\Extra\String;
  11. use Symfony\Component\String\AbstractUnicodeString;
  12. use Symfony\Component\String\Slugger\SluggerInterface;
  13. use Symfony\Component\String\Slugger\AsciiSlugger;
  14. use Symfony\Component\String\UnicodeString;
  15. use Twig\Extension\AbstractExtension;
  16. use Twig\TwigFilter;
  17. final class StringExtension extends AbstractExtension
  18. {
  19. private $slugger;
  20. public function __construct(SluggerInterface $slugger = null)
  21. {
  22. $this->slugger = $slugger ?: new AsciiSlugger();
  23. }
  24. public function getFilters()
  25. {
  26. return [
  27. new TwigFilter('u', [$this, 'createUnicodeString']),
  28. new TwigFilter('slug', [$this, 'createSlug']),
  29. ];
  30. }
  31. public function createUnicodeString(?string $text): UnicodeString
  32. {
  33. return new UnicodeString($text ?? '');
  34. }
  35. public function createSlug(string $string, string $separator = '-', ?string $locale = null): AbstractUnicodeString
  36. {
  37. return $this->slugger->slug($string, $separator, $locale);
  38. }
  39. }