How to use Doctrine advanced field values to truncate based on column length?

Viewed 37

I have created my first advanced field value converter correctly. However, I would like to do some some processing based on the column definition of properties.

Entity example:

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class Location
{
    #[ORM\Column(type: "customString", length: 10)]
    public ?string $myString;
}

Type converter snippet:

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class CustomStringType extends Type
{

    /* other methods */

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return $value;
    }

    public function convertToDabaseValue($value, AbstractPlatform $platform)
    {
        /* I don`t know how to get the '10' value here */
        return $value !== null ? substr($value, 0, 10) : null;
    }

}

So if I input $entity->myString = 'My very very long string', when retrieving this value from database, I expect it to be equal to 'My very ve', a 10 length string.

More background:

Read into using getters and setters but that is not an option in this case. Possibly using a custom hydrator would be, but I don't know how to properly do it.

TLDR:

Would like to truncate, model wise, some string properties on my application. I don't know how to do it without re-declaring it across all my entites getters/setters or their logic classes.

0 Answers
Related