1
0

SimpleSubstitutionTrait.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\Files_External\Config;
  7. /**
  8. * Trait SimpleSubstitutionTrait
  9. *
  10. * @package OCA\Files_External\Config
  11. * @since 16.0.0
  12. */
  13. trait SimpleSubstitutionTrait {
  14. /**
  15. * @var string the placeholder without $ prefix
  16. * @since 16.0.0
  17. */
  18. protected $placeholder;
  19. /** @var string */
  20. protected $sanitizedPlaceholder;
  21. /**
  22. * @param mixed $optionValue
  23. * @param string $replacement
  24. * @return mixed
  25. * @since 16.0.0
  26. */
  27. private function processInput($optionValue, string $replacement) {
  28. $this->checkPlaceholder();
  29. if (is_array($optionValue)) {
  30. foreach ($optionValue as &$value) {
  31. $value = $this->substituteIfString($value, $replacement);
  32. }
  33. } else {
  34. $optionValue = $this->substituteIfString($optionValue, $replacement);
  35. }
  36. return $optionValue;
  37. }
  38. /**
  39. * @throws \RuntimeException
  40. */
  41. protected function checkPlaceholder(): void {
  42. $this->sanitizedPlaceholder = trim(strtolower($this->placeholder));
  43. if (!(bool)\preg_match('/^[a-z0-9]*$/', $this->sanitizedPlaceholder)) {
  44. throw new \RuntimeException(sprintf(
  45. 'Invalid placeholder %s, only [a-z0-9] are allowed', $this->sanitizedPlaceholder
  46. ));
  47. }
  48. if ($this->sanitizedPlaceholder === '') {
  49. throw new \RuntimeException('Invalid empty placeholder');
  50. }
  51. }
  52. /**
  53. * @param mixed $value
  54. * @param string $replacement
  55. * @return mixed
  56. */
  57. protected function substituteIfString($value, string $replacement) {
  58. if (is_string($value)) {
  59. return str_ireplace('$' . $this->sanitizedPlaceholder, $replacement, $value);
  60. }
  61. return $value;
  62. }
  63. }