1. <?php
  2. /**
  3. * String Constraint Checker for Legacy Project
  4. *
  5. * Performs basic sanity checks on strings.
  6. *
  7. * @param string $string The string to validate.
  8. * @param array $constraints An array of constraints. Each constraint is an associative array with keys:
  9. * - 'min_length' (int, optional): Minimum length of the string.
  10. * - 'max_length' (int, optional): Maximum length of the string.
  11. * - 'allowed_chars' (string, optional): Only allow these characters.
  12. * - 'required' (bool, optional): String must not be empty.
  13. * @return array An array of validation errors. Empty array if no errors.
  14. */
  15. function validateString(string $string, array $constraints): array
  16. {
  17. $errors = [];
  18. if (isset($constraints['min_length']) && strlen($string) < $constraints['min_length']) {
  19. $errors[] = "Minimum length is {$constraints['min_length']} characters.";
  20. }
  21. if (isset($constraints['max_length']) && strlen($string) > $constraints['max_length']) {
  22. $errors[] = "Maximum length is {$constraints['max_length']} characters.";
  23. }
  24. if (isset($constraints['allowed_chars'])) {
  25. if (preg_match('/^' . preg_quote($constraints['allowed_chars'], '/') . '$/', $string)) {
  26. $errors[] = "String contains invalid characters.";
  27. }
  28. }
  29. if (isset($constraints['required']) && empty($string)) {
  30. $errors[] = "String is required.";
  31. }
  32. return $errors;
  33. }
  34. // Example Usage (can be removed for production)
  35. /*
  36. $string = "ValidString";
  37. $constraints = [
  38. 'min_length' => 5,
  39. 'max_length' => 10,
  40. 'allowed_chars' => 'abcdefg123',
  41. 'required' => true,
  42. ];
  43. $errors = validateString($string, $constraints);
  44. if (!empty($errors)) {
  45. echo "Validation Errors:\n";
  46. foreach ($errors as $error) {
  47. echo "- " . $error . "\n";
  48. }
  49. } else {
  50. echo "String is valid.\n";
  51. }
  52. */
  53. ?>

Add your comment