RichTextFormatter.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\RichObjectStrings;
  8. use OCP\RichObjectStrings\IRichTextFormatter;
  9. class RichTextFormatter implements IRichTextFormatter {
  10. /**
  11. * @throws \InvalidArgumentException if a parameter has no name or no type
  12. */
  13. public function richToParsed(string $message, array $parameters): string {
  14. $placeholders = [];
  15. $replacements = [];
  16. foreach ($parameters as $placeholder => $parameter) {
  17. $placeholders[] = '{' . $placeholder . '}';
  18. foreach (['name','type'] as $requiredField) {
  19. if (!isset($parameter[$requiredField]) || !is_string($parameter[$requiredField])) {
  20. throw new \InvalidArgumentException("Invalid rich object, {$requiredField} field is missing");
  21. }
  22. }
  23. $replacements[] = match($parameter['type']) {
  24. 'user' => '@' . $parameter['name'],
  25. 'file' => $parameter['path'] ?? $parameter['name'],
  26. default => $parameter['name'],
  27. };
  28. }
  29. return str_replace($placeholders, $replacements, $message);
  30. }
  31. }