public function Subscription::preSave in Mailing List 8
Acts on an entity before the presave hook is invoked.
Used before the entity is saved and before invoking the presave hook. Note that in case of translatable content entities this callback is only fired on their current translation. It is up to the developer to iterate over all translations if needed. This is different from its counterpart in the Field API, FieldItemListInterface::preSave(), which is fired on all field translations automatically. @todo Adjust existing implementations and the documentation according to https://www.drupal.org/node/2577609 to have a consistent API.
Parameters
\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.
Throws
\Exception When there is a problem that should prevent saving the entity.
Overrides ContentEntityBase::preSave
See also
\Drupal\Core\Field\FieldItemListInterface::preSave()
File
- src/
Entity/ Subscription.php, line 378
Class
- Subscription
- Defines the subscription entity class.
Namespace
Drupal\mailing_list\EntityCode
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
// Applies subscription limits on subscription creation or activation.
if ($this
->isNew() && $this
->isActive() || $this
->isActive() && isset($this->original) && !$this->original
->isActive()) {
$list = $this
->getList();
$max_reached = FALSE;
if ($max_per_email = intval($list
->getLimitByEmail())) {
// Count existent subscriptions with the same email.
$query = \Drupal::entityQuery('mailing_list_subscription')
->condition('status', SubscriptionInterface::ACTIVE)
->condition('email', $this
->getEmail())
->count();
// Exclude itself.
if ($this
->id()) {
$query
->condition('sid', $this
->id(), '<>');
}
$max_reached = $query
->execute() >= $max_per_email;
}
if (!$max_reached && ($max_per_user = intval($list
->getLimitByUser()))) {
// Count existent subscriptions with the same email.
$query = \Drupal::entityQuery('mailing_list_subscription')
->condition('status', SubscriptionInterface::ACTIVE)
->condition('uid', \Drupal::currentUser()
->id())
->count();
// Exclude itself.
if ($this
->id()) {
$query
->condition('sid', $this
->id(), '<>');
}
$max_reached = $query
->execute() >= $max_per_user;
}
// Limit reached.
if ($max_reached) {
// Set this as inactive.
$this
->setStatus(SubscriptionInterface::INACTIVE);
// Send notification email to subscriber.
\Drupal::service('plugin.manager.mail')
->mail('mailing_list', 'subscription_limit_reached', $this
->getEmail(), $this
->language(), [
'subscription' => $this,
]);
}
}
}