ValidationRuleDescriptionParser.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Knuckles\Scribe\Extracting;
  3. class ValidationRuleDescriptionParser
  4. {
  5. private $rule;
  6. private $arguments = [];
  7. /**
  8. * @param string $rule
  9. */
  10. public function __construct(string $rule = null)
  11. {
  12. $this->rule = $rule;
  13. }
  14. public static function getDescription(string $rule, array $arguments = [], $type = 'string'): string
  15. {
  16. $instance = new self($rule);
  17. $instance->arguments = $arguments;
  18. return $instance->makeDescription($type);
  19. }
  20. protected function makeDescription($baseType = 'string'): string
  21. {
  22. $description = trans("validation.{$this->rule}");
  23. // For rules that can apply to multiple types (eg 'max' rule), Laravel returns an array of possible messages
  24. // 'numeric' => 'The :attribute must not be greater than :max'
  25. // 'file' => 'The :attribute must have a size less than :max kilobytes'
  26. if (is_array($description)) {
  27. $description = $description[$baseType];
  28. }
  29. // Convert messages from failure type ("The value is not a valid date.") to info ("The value must be a valid date.")
  30. $description = str_replace(['is not', 'does not'], ['must be', 'must'], $description);
  31. return $this->replaceArguments($description);
  32. }
  33. protected function replaceArguments(string $description): string
  34. {
  35. foreach ($this->arguments as $placeholder => $argument) {
  36. $description = str_replace($placeholder, $argument, $description);
  37. }
  38. $description = str_replace("The :attribute", "The value", $description);
  39. return $description;
  40. }
  41. }