/src/Mandango/Twig/Mandango.php

https://github.com/brikou/mandango · PHP · 76 lines · 52 code · 11 blank · 13 comment · 0 complexity · 3532b608dad91ca4ac6f06590e2de208 MD5 · raw file

  1. <?php
  2. /*
  3. * This file is part of Mandango.
  4. *
  5. * (c) Pablo Díez <pablodip@gmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Mandango\Twig;
  11. use Mandango\Id\IdGeneratorContainer;
  12. use Mandango\Type\Container as TypeContainer;
  13. /**
  14. * The "mandango" extension for twig (used in the Core Mondator extension).
  15. *
  16. * @author Pablo Díez <pablodip@gmail.com>
  17. */
  18. class Mandango extends \Twig_Extension
  19. {
  20. public function getFilters()
  21. {
  22. return array(
  23. 'ucfirst' => new \Twig_Filter_Function('ucfirst'),
  24. 'var_export' => new \Twig_Filter_Function('var_export'),
  25. );
  26. }
  27. public function getFunctions()
  28. {
  29. return array(
  30. 'mandango_id_generator' => new \Twig_Function_Method($this, 'mandangoIdGenerator'),
  31. 'mandango_type_to_mongo' => new \Twig_Function_Method($this, 'mandangoTypeToMongo'),
  32. 'mandango_type_to_php' => new \Twig_Function_Method($this, 'mandangoTypeToPHP'),
  33. );
  34. }
  35. public function mandangoIdGenerator($configClass, $id, $indent = 8)
  36. {
  37. $idGenerator = IdGeneratorContainer::get($configClass['idGenerator']['name']);
  38. $code = $idGenerator->getCode($configClass['idGenerator']['options']);
  39. $code = str_replace('%id%', $id, $code);
  40. $code = static::indentCode($code, $indent);
  41. return $code;
  42. }
  43. public function mandangoTypeToMongo($type, $from, $to)
  44. {
  45. return strtr(TypeContainer::get($type)->toMongoInString(), array(
  46. '%from%' => $from,
  47. '%to%' => $to,
  48. ));
  49. }
  50. public function mandangoTypeToPHP($type, $from, $to)
  51. {
  52. return strtr(TypeContainer::get($type)->toPHPInString(), array(
  53. '%from%' => $from,
  54. '%to%' => $to,
  55. ));
  56. }
  57. public function getName()
  58. {
  59. return 'mandango';
  60. }
  61. static private function indentCode($code, $indent)
  62. {
  63. return str_replace("\n", "\n".str_repeat(' ', $indent), $code);
  64. }
  65. }