PageRenderTime 43ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/PHPParser/Template.php

https://bitbucket.org/nilopc_repo/sf2_backup-php-parser
PHP | 72 lines | 40 code | 10 blank | 22 comment | 5 complexity | 172a3a5df5eceec1710496cfda705abc MD5 | raw file
Possible License(s): BSD-3-Clause
  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. }