Skip to content

scalar casters ignore nullability - empty string becomes 0/false instead of null #2106

@laylatichy

Description

@laylatichy

Tempest version

3.9

PHP version

8.5

Operating system

Windows, macOS

Description

when i have a request like this:

final class MyRequest implements Request {
    use IsRequest;

    public ?int $user_id = null;
    public ?float $price = null;
    public ?bool $featured = null;
}

and the form sends empty values (which browsers do when a field is cleared):

$request = map(['user_id' => '', 'price' => '', 'featured' => ''])
    ->to(MyRequest::class);

i expected $request->user_id to be null, $request->price to be null, etc - since the properties are nullable and the input is empty.

what actually happens

  • $request->user_id is 0 (not null)
  • $request->price is 0.0 (not null)
  • $request->featured is false (not null)

the casters use intval(), floatval(), (bool) without checking if the property is nullable

// IntegerCaster
public function cast(mixed $input): int
{
    return intval($input); // intval("") === 0
}

// FloatCaster
public function cast(mixed $input): float
{
    return floatval($input); // floatval("") === 0.0
}

ArrayToObjectMapper::resolveValue() does check for null:

if ($property->isNullable() && $value === null) {
    return null;
}

but this is === null, so empty strings fall through to the casters.

i'm working around it with hooked property getters for now but it would be nice if plain nullable properties just worked.

i'll file a pr with a fix later if this makes sense.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions