Skip to content

$data->filled() throws "Object could not be converted to string" when attribute holds a non-Stringable object #8

@stevebauman

Description

@stevebauman

Summary

DummyData::filled() (and by extension isNotFilled(), notFilled(), anyFilled()) throws a TypeError when the attribute being checked holds an object that does not implement __toString — for example a DateTime, DateTimeImmutable, or a Carbon CarbonInterface returned from Faker\Generator::dateTimeBetween().

Steps to reproduce

use DirectoryTree\Dummy\DummyData;

$data = new DummyData([
    'dateOfBirth' => new DateTime,
]);

$data->filled('dateOfBirth');

Expected behaviour

filled('dateOfBirth') returns true — the attribute holds a real, non-empty value.

Actual behaviour

A fatal error is thrown:

Error: Object of class DateTime could not be converted to string
  at vendor/directorytree/dummy/src/DummyData.php:317
  at vendor/directorytree/dummy/src/DummyData.php:157

Root cause

DummyData::isEmptyString() guards against bool and array values before casting to string, but does not guard against objects:

return ! is_bool($value)
    && ! is_array($value)
    && trim((string) $value) === '';

Any object without a __toString() method (e.g. DateTime) triggers the cast and crashes.

Impact

Affects any consumer using HasDummyFactory whose toDummyInstance() calls $attributes->filled($key) on a key produced by Faker's dateTimeBetween(), dateTime(), or any factory-defined value that is an object.

Fix

Also exclude objects from the string-coercion check in isEmptyString(); treat objects as filled.

Environment

  • Package: directorytree/dummy
  • PHP: 8.x

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions