Skip to content

Conversation

@Kocal
Copy link
Member

@Kocal Kocal commented Dec 2, 2020

Hi 👋

This PR is a proposal for #195 for handling the new value (if nullable) in a OneToOne association.

The following code was not valid, it fails at $user->getUserProfile() if we call UserProfile#setUser(null):

class UserProfile
{
    // ...
    public function setUser(?User $user): self
    {
        $this->user = $user;

        // set (or unset) the owning side of the relation if necessary
        $newUserProfile = null === $user ? null : $this;
        if ($user->getUserProfile() !== $newUserProfile) {
            $user->setUserProfile($newUserProfile);
        }

        return $this;
    }
}

The following code takes care of:

  • unset the user profile of the previous User ($this->user) if we assign a nullable User
  • set the profile to the new user, and prevent an infinite loop with user->getUserProfile() !== $this
class UserProfile 
{
    public function setUser(?User $user): self
    {
        // unset the owning side of the relation if necessary
        if ($user === null && $this->user !== null) {
            $this->user->setUserProfile(null);
        }

        // set the owning side of the relation if necessary
        if ($user !== null && $user->getUserProfile() !== $this) {
            $user->setUserProfile($this);
        }

        $this->user = $user;

        return $this;
    }
}

WDYT? Thanks!

@weaverryan
Copy link
Member

Wonderful work! Thanks for this great fix Hugo!

@weaverryan weaverryan merged commit 2507352 into symfony:main Dec 7, 2020
@Kocal Kocal deleted the GH-195 branch December 7, 2020 14:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants