I have to check if an Email
entity already exists in the ArrayCollection
but I have to perform the check on the emails as strings (the Entity contains an ID and some relations to other entites, for this reason I use a separate table that persists all emails).
Now, in the first I wrote this code:
/**
* A new Email is adding: check if it already exists.
*
* In a normal scenario we should use $this->emails->contains().
* But it is possible the email comes from the setPrimaryEmail method.
* In this case, the object is created from scratch and so it is possible it contains a string email that is
* already present but that is not recognizable as the Email object that contains it is created from scratch.
*
* So we hav to compare Email by Email the string value to check if it already exists: if it exists, then we use
* the already present Email object, instead we can persist the new one securely.
*
* @var Email $existentEmail
*/
foreach ($this->emails as $existentEmail) {
if ($existentEmail->getEmail()->getEmail() === $email->getEmail()) {
// If the two email compared as strings are equals, set the passed email as the already existent one.
$email = $existentEmail;
}
}
But reading the ArrayCollection
class I seen the method exists
that seems to be a more elgant way of doing the same thing I did.
But I don't know how to use it: can someone explain me how to use this method given the code above?
Of course, in PHP a Closure is a simple Anonymous functions. You could rewrite your code as follow:
$exists = $this->emails->exists(function($key, $element) use ($email){
return $email->getEmail() === $element->getEmail()->getEmail();
});
Hope this help
Thank you @Matteo!
Just for completeness, this is the code with which I came up:
public function addEmail(Email $email)
{
$predictate = function($key, $element) use ($email) {
/** @var Email $element If the two email compared as strings are equals, return true. */
return $element->getEmail()->getEmail() === $email->getEmail();
};
// Create a new Email object and add it to the collection
if (false === $this->emails->exists($predictate)) {
$this->emails->add($email);
}
// Anyway set the email for this store
$email->setForStore($this);
return $this;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With