Skip to main content

PathPartMapper

Maps an input value to a URL-safe path part string (or null).

Accepts the following input types:

  • string.
  • Any Stringable object.
  • null — left as null, subject to validation (or used as the trigger for generation, see below).

Non-null values are normalized before validation: StringUtils::clean() trims and collapses whitespace, then mb_strtolower() lowercases the result.

Generation​

When the input value is null and a $generationIfNullBaseName is provided, the mapper generates a path part from that base name instead of failing: special characters are stripped, the result is lowercased, padded with -<fillStr> (default path) up to $minlength, and truncated to $maxlength. If a $uniqueTester closure is also given, -N (from 2 up to 9999) is appended until the tester returns true. If no unique value is found, the value becomes null and a Mandatory error is raised.

Validation possibilities​

ParameterTypeDefaultDescription
$uniqueTesterClosure?nullfn(string $v): bool returning true if $v is available.
$generationIfNullBaseNamestring?nullBase name to generate from when the input is null (requires $maxlength≥6).
$mandatoryboolfalseRejects null input (unless generation produces a value).
$minlengthint?3Rejects strings shorter than this.
$maxlengthint?150Rejects strings longer than this.

noSpecialChars validation is always applied, regardless of $mandatory.

Example: basic normalization​

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

Output:

array(2) {
[0]=>
string(4) "asdf"
[1]=>
NULL
}

Example: generating from a base name​

$result = Bind::values(null)->map(Mappers::pathPart(fn ($v) => true, 'Blubb', minlength: 8, maxlength: 12))
->toArray()->exec();
var_dump($result->get());

Output:

array(1) {
[0]=>
string(10) "blubb-path"
}

null triggers generation from Blubb; the result is lowercased and padded with -path to reach the minimum length of 8.