Skip to main content

CleanStringMapper

Maps an input value to a cleaned string (or null).

Accepts the following input types:

  • string.
  • Any Stringable object.
  • null — left as null, subject to validation.

Non-null values are cleaned before validation: StringUtils::clean() trims, collapses repeated whitespace and strips non-printable control characters. With $simpleWhitespacesOnly = true (the default, used by Mappers::cleanString()) all whitespace is normalized to single spaces. Mappers::cleanMultilineString() passes false, which preserves line breaks so multi-line text keeps its structure.

Validation possibilities​

ParameterTypeDefaultDescription
$mandatoryboolfalseRejects null input.
$minlengthint?1Rejects strings shorter than this.
$maxlengthint?255Rejects strings longer than this.
$simpleWhitespacesOnlybooltrueWhitespace normalization mode (see above).

Example: basic cleaning​

$result = Bind::values(' Hello World ', null)->map(Mappers::cleanString())->toArray()->exec();
var_dump($result->get());

Output:

array(2) {
[0]=>
string(11) "Hello World"
[1]=>
NULL
}

Example: mandatory and length validation​

$result = Bind::attrs(['title' => str_repeat('A', 256), 'name' => 'a', 'missing' => null])
->props(['title', 'name', 'missing'], Mappers::cleanString(true, 11, 255))
->toArray()
->exec();

// result will be invalid with error messages provided for all properties.
var_dump($result->isValid()); // false
var_dump($result->getErrorMap()->getChild('title')->isEmpty()); // false due to maxlength
var_dump($result->getErrorMap()->getChild('name')->isEmpty()); // false due to minlength
var_dump($result->getErrorMap()->getChild('missing')->isEmpty()); // false because mandatory