Params.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Services\Markup\Ir;
  3. /**
  4. * 模板参数表。
  5. *
  6. * 命名参数 `name=value` 与位置参数并存;位置序号按全部参数的顺序计(命名参数也占位),
  7. * 与 v2 一致:`{{note|text=a|①}}` 里 ① 是第 2 个参数。
  8. */
  9. final class Params
  10. {
  11. /**
  12. * @param array<string, string> $named
  13. * @param array<int, string> $positional 1 起
  14. */
  15. public function __construct(
  16. public array $named = [],
  17. public array $positional = [],
  18. ) {}
  19. public function get(string $name, ?int $position, ?string $default = ''): ?string
  20. {
  21. if (array_key_exists($name, $this->named)) {
  22. return trim($this->named[$name]);
  23. }
  24. if ($position !== null && array_key_exists($position, $this->positional)) {
  25. return trim($this->positional[$position]);
  26. }
  27. return $default;
  28. }
  29. /**
  30. * 原值(不 trim),给 markdown 参数用。
  31. */
  32. public function raw(string $name, ?int $position): ?string
  33. {
  34. if (array_key_exists($name, $this->named)) {
  35. return $this->named[$name];
  36. }
  37. if ($position !== null && array_key_exists($position, $this->positional)) {
  38. return $this->positional[$position];
  39. }
  40. return null;
  41. }
  42. public function with(string $name, string $value): self
  43. {
  44. $copy = clone $this;
  45. $copy->named[$name] = $value;
  46. return $copy;
  47. }
  48. /**
  49. * 全部参数,命名的用名字、位置的用序号字符串作键(Tpl 模板交给 Mustache 用)。
  50. *
  51. * @return array<string, string>
  52. */
  53. public function all(): array
  54. {
  55. $all = [];
  56. foreach ($this->positional as $position => $value) {
  57. $all[(string) $position] = trim($value);
  58. }
  59. foreach ($this->named as $name => $value) {
  60. $all[$name] = trim($value);
  61. }
  62. return $all;
  63. }
  64. }