Template.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. class PHPParser_Template
  3. {
  4. protected $parser;
  5. protected $template;
  6. /**
  7. * Creates a new code template from a template string.
  8. *
  9. * @param PHPParser_Parser $parser A parser instance
  10. * @param string $template The template string
  11. */
  12. public function __construct(PHPParser_Parser $parser, $template) {
  13. $this->parser = $parser;
  14. $this->template = $template;
  15. }
  16. /**
  17. * Get the statements of the template with the passed in placeholders
  18. * replaced.
  19. *
  20. * @param array $placeholders Placeholders
  21. *
  22. * @return PHPParser_Node[] Statements
  23. */
  24. public function getStmts(array $placeholders) {
  25. return $this->parser->parse(
  26. $this->getTemplateWithPlaceholdersReplaced($placeholders)
  27. );
  28. }
  29. protected function getTemplateWithPlaceholdersReplaced(array $placeholders) {
  30. if (empty($placeholders)) {
  31. return $this->template;
  32. }
  33. return strtr($this->template, $this->preparePlaceholders($placeholders));
  34. }
  35. /*
  36. * Prepare the placeholders for replacement. This means that
  37. * a) all placeholders will be surrounded with __.
  38. * b) ucfirst/lcfirst variations of the placeholders are generated.
  39. *
  40. * E.g. for an input array of ['foo' => 'bar'] the result will be
  41. * ['__foo__' => 'bar', '__Foo__' => 'Bar'].
  42. */
  43. protected function preparePlaceholders(array $placeholders) {
  44. $preparedPlaceholders = array();
  45. foreach ($placeholders as $name => $value) {
  46. $preparedPlaceholders['__' . $name . '__'] = $value;
  47. if (ctype_lower($name[0])) {
  48. $ucfirstName = ucfirst($name);
  49. if (!isset($placeholders[$ucfirstName])) {
  50. $preparedPlaceholders['__' . $ucfirstName . '__'] = ucfirst($value);
  51. }
  52. }
  53. if (ctype_upper($name[0])) {
  54. $lcfirstName = lcfirst($name);
  55. if (!isset($placeholders[$lcfirstName])) {
  56. $preparedPlaceholders['__' . $lcfirstName . '__'] = lcfirst($value);
  57. }
  58. }
  59. }
  60. return $preparedPlaceholders;
  61. }
  62. }