<?php
/**
* String Constraint Checker for Legacy Project
*
* Performs basic sanity checks on strings.
*
* @param string $string The string to validate.
* @param array $constraints An array of constraints. Each constraint is an associative array with keys:
* - 'min_length' (int, optional): Minimum length of the string.
* - 'max_length' (int, optional): Maximum length of the string.
* - 'allowed_chars' (string, optional): Only allow these characters.
* - 'required' (bool, optional): String must not be empty.
* @return array An array of validation errors. Empty array if no errors.
*/
function validateString(string $string, array $constraints): array
{
$errors = [];
if (isset($constraints['min_length']) && strlen($string) < $constraints['min_length']) {
$errors[] = "Minimum length is {$constraints['min_length']} characters.";
}
if (isset($constraints['max_length']) && strlen($string) > $constraints['max_length']) {
$errors[] = "Maximum length is {$constraints['max_length']} characters.";
}
if (isset($constraints['allowed_chars'])) {
if (preg_match('/^' . preg_quote($constraints['allowed_chars'], '/') . '$/', $string)) {
$errors[] = "String contains invalid characters.";
}
}
if (isset($constraints['required']) && empty($string)) {
$errors[] = "String is required.";
}
return $errors;
}
// Example Usage (can be removed for production)
/*
$string = "ValidString";
$constraints = [
'min_length' => 5,
'max_length' => 10,
'allowed_chars' => 'abcdefg123',
'required' => true,
];
$errors = validateString($string, $constraints);
if (!empty($errors)) {
echo "Validation Errors:\n";
foreach ($errors as $error) {
echo "- " . $error . "\n";
}
} else {
echo "String is valid.\n";
}
*/
?>
Add your comment