TwigLanguageExtension.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Typemill\Extensions;
  3. use Typemill\Models\WriteYaml;
  4. class TwigLanguageExtension extends \Twig_Extension
  5. {
  6. protected $labels;
  7. public function __construct($labels)
  8. {
  9. $this->labels = $labels;
  10. }
  11. public function getFilters()
  12. {
  13. return [
  14. new \Twig_SimpleFilter('__', [$this,'translate'] ),
  15. ];
  16. }
  17. public function getFunctions()
  18. {
  19. return [
  20. new \Twig_SimpleFunction('__', array($this, 'translate' ))
  21. ];
  22. }
  23. public function translate( $label, $labels_from_plugin = NULL )
  24. {
  25. // replaces spaces, dots, comma and dash with underscores
  26. $string = str_replace(" ", "_", $label);
  27. $string = str_replace(".", "_", $string);
  28. $string = str_replace(",", "_", $string);
  29. $string = str_replace("-", "_", $string);
  30. // transforms to uppercase
  31. $string = strtoupper( $string );
  32. //translates the string
  33. if(isset($labels_from_plugin)){
  34. $translated_label = isset($labels_from_plugin[$string]) ? $labels_from_plugin[$string] : null;
  35. } else {
  36. $translated_label = isset($this->labels[$string]) ? $this->labels[$string] : null;
  37. }
  38. // if the string is not present, set the original string
  39. if( empty($translated_label) ){
  40. $translated_label = $label;
  41. }
  42. // returns the string in the set language
  43. return $translated_label;
  44. }
  45. }