Template.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of phpunit/php-text-template.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  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 SebastianBergmann\Template;
  11. use function array_keys;
  12. use function array_merge;
  13. use function file_get_contents;
  14. use function file_put_contents;
  15. use function is_file;
  16. use function sprintf;
  17. use function str_replace;
  18. final class Template
  19. {
  20. private string $template = '';
  21. private string $openDelimiter;
  22. private string $closeDelimiter;
  23. /**
  24. * @psalm-var array<string,string>
  25. */
  26. private array $values = [];
  27. /**
  28. * @throws InvalidArgumentException
  29. */
  30. public function __construct(string $file = '', string $openDelimiter = '{', string $closeDelimiter = '}')
  31. {
  32. $this->setFile($file);
  33. $this->openDelimiter = $openDelimiter;
  34. $this->closeDelimiter = $closeDelimiter;
  35. }
  36. /**
  37. * @throws InvalidArgumentException
  38. */
  39. public function setFile(string $file): void
  40. {
  41. if (is_file($file)) {
  42. $this->template = file_get_contents($file);
  43. return;
  44. }
  45. $distFile = $file . '.dist';
  46. if (is_file($distFile)) {
  47. $this->template = file_get_contents($distFile);
  48. return;
  49. }
  50. throw new InvalidArgumentException(
  51. sprintf(
  52. 'Failed to load template "%s"',
  53. $file
  54. )
  55. );
  56. }
  57. /**
  58. * @psalm-param array<string,string> $values
  59. */
  60. public function setVar(array $values, bool $merge = true): void
  61. {
  62. if (!$merge || empty($this->values)) {
  63. $this->values = $values;
  64. return;
  65. }
  66. $this->values = array_merge($this->values, $values);
  67. }
  68. public function render(): string
  69. {
  70. $keys = [];
  71. foreach (array_keys($this->values) as $key) {
  72. $keys[] = $this->openDelimiter . $key . $this->closeDelimiter;
  73. }
  74. return str_replace($keys, $this->values, $this->template);
  75. }
  76. /**
  77. * @codeCoverageIgnore
  78. */
  79. public function renderTo(string $target): void
  80. {
  81. if (!@file_put_contents($target, $this->render())) {
  82. throw new RuntimeException(
  83. sprintf(
  84. 'Writing rendered result to "%s" failed',
  85. $target
  86. )
  87. );
  88. }
  89. }
  90. }