Skip to content

Replace PostLoad event with property hook #12458

@whataboutpereira

Description

@whataboutpereira

I'm attempting to replace a PostLoad event with a property hook, but it doesn't seem to work.

Calling getFirstDayOfMonth() on the entity after it has been loaded from the database yields Typed property Entity::$firstDayOfMonth must not be accessed before initialization

Is this something that should work or am I doing something wrong?

class Entity
{
    #[ORM\Column(type: Types::DATE_IMMUTABLE, nullable: true)]
    private ?\DateTimeImmutable $date = null {
        set(?\DateTimeImmutable $value) {
            $this->date = $value;
            $this->updateFirstDayOfMonth();
        }
    }

    private \DateTimeImmutable $firstDayOfMonth;

    public function __construct()
    {
        $this->updateFirstDayOfMonth();
    }

    public function getFirstDayOfMonth(): \DateTimeImmutable
    {
        return $this->firstDayOfMonth;
    }

    public function updateFirstDayOfMonth(): void
    {
        if (!$this->date instanceof \DateTimeImmutable) {
            $this->firstDayOfMonth = new \DateTimeImmutable('midnight first day of this month');
            return;
        }

        $year = (int) $this->date->format('Y');
        $month = (int) $this->date->format('n');

        $this->firstDayOfMonth = $this->date
            ->setDate($year, $month, 1)
            ->setTime(0, 0, 0)
        ;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions