Replace Subscriber and SubscriberSegment models with Doctrine in \MailPoet\Segments\WP
[MAILPOET-5752]
This commit is contained in:
committed by
Aschepikov
parent
01cafdf719
commit
6f98634b94
@@ -6,8 +6,7 @@ use MailPoet\Config\SubscriberChangesNotifier;
|
|||||||
use MailPoet\DI\ContainerWrapper;
|
use MailPoet\DI\ContainerWrapper;
|
||||||
use MailPoet\Entities\SegmentEntity;
|
use MailPoet\Entities\SegmentEntity;
|
||||||
use MailPoet\Entities\SubscriberEntity;
|
use MailPoet\Entities\SubscriberEntity;
|
||||||
use MailPoet\Models\Subscriber;
|
use MailPoet\Entities\SubscriberSegmentEntity;
|
||||||
use MailPoet\Models\SubscriberSegment;
|
|
||||||
use MailPoet\Newsletter\Scheduler\WelcomeScheduler;
|
use MailPoet\Newsletter\Scheduler\WelcomeScheduler;
|
||||||
use MailPoet\Services\Validator;
|
use MailPoet\Services\Validator;
|
||||||
use MailPoet\Settings\SettingsController;
|
use MailPoet\Settings\SettingsController;
|
||||||
@@ -18,7 +17,7 @@ use MailPoet\Subscribers\SubscribersRepository;
|
|||||||
use MailPoet\WooCommerce\Helper as WooCommerceHelper;
|
use MailPoet\WooCommerce\Helper as WooCommerceHelper;
|
||||||
use MailPoet\WP\Functions as WPFunctions;
|
use MailPoet\WP\Functions as WPFunctions;
|
||||||
use MailPoetVendor\Carbon\Carbon;
|
use MailPoetVendor\Carbon\Carbon;
|
||||||
use MailPoetVendor\Idiorm\ORM;
|
use MailPoetVendor\Doctrine\ORM\EntityManager;
|
||||||
|
|
||||||
class WP {
|
class WP {
|
||||||
|
|
||||||
@@ -42,8 +41,18 @@ class WP {
|
|||||||
/** @var Validator */
|
/** @var Validator */
|
||||||
private $validator;
|
private $validator;
|
||||||
|
|
||||||
|
/** @var SegmentsRepository */
|
||||||
private $segmentsRepository;
|
private $segmentsRepository;
|
||||||
|
|
||||||
|
/** @var EntityManager */
|
||||||
|
private $entityManager;
|
||||||
|
|
||||||
|
/** @var string */
|
||||||
|
private $subscribersTable;
|
||||||
|
|
||||||
|
/** @var \MailPoetVendor\Doctrine\DBAL\Connection */
|
||||||
|
private $databaseConnection;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
WPFunctions $wp,
|
WPFunctions $wp,
|
||||||
WelcomeScheduler $welcomeScheduler,
|
WelcomeScheduler $welcomeScheduler,
|
||||||
@@ -52,7 +61,8 @@ class WP {
|
|||||||
SubscriberSegmentRepository $subscriberSegmentRepository,
|
SubscriberSegmentRepository $subscriberSegmentRepository,
|
||||||
SubscriberChangesNotifier $subscriberChangesNotifier,
|
SubscriberChangesNotifier $subscriberChangesNotifier,
|
||||||
Validator $validator,
|
Validator $validator,
|
||||||
SegmentsRepository $segmentsRepository
|
SegmentsRepository $segmentsRepository,
|
||||||
|
EntityManager $entityManager
|
||||||
) {
|
) {
|
||||||
$this->wp = $wp;
|
$this->wp = $wp;
|
||||||
$this->welcomeScheduler = $welcomeScheduler;
|
$this->welcomeScheduler = $welcomeScheduler;
|
||||||
@@ -62,6 +72,9 @@ class WP {
|
|||||||
$this->subscriberChangesNotifier = $subscriberChangesNotifier;
|
$this->subscriberChangesNotifier = $subscriberChangesNotifier;
|
||||||
$this->validator = $validator;
|
$this->validator = $validator;
|
||||||
$this->segmentsRepository = $segmentsRepository;
|
$this->segmentsRepository = $segmentsRepository;
|
||||||
|
$this->entityManager = $entityManager;
|
||||||
|
$this->databaseConnection = $this->entityManager->getConnection();
|
||||||
|
$this->subscribersTable = $this->entityManager->getClassMetadata(SubscriberEntity::class)->getTableName();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -72,45 +85,39 @@ class WP {
|
|||||||
$wpUser = \get_userdata($wpUserId);
|
$wpUser = \get_userdata($wpUserId);
|
||||||
if ($wpUser === false) return;
|
if ($wpUser === false) return;
|
||||||
|
|
||||||
$subscriber = Subscriber::where('wp_user_id', $wpUser->ID)
|
$subscriber = $this->subscribersRepository->findOneBy(['wpUserId' => $wpUserId]);
|
||||||
->findOne();
|
|
||||||
|
|
||||||
$currentFilter = $this->wp->currentFilter();
|
$currentFilter = $this->wp->currentFilter();
|
||||||
// Delete
|
// Delete
|
||||||
if (in_array($currentFilter, ['delete_user', 'deleted_user', 'remove_user_from_blog'])) {
|
if (in_array($currentFilter, ['delete_user', 'deleted_user', 'remove_user_from_blog'])) {
|
||||||
$this->deleteSubscriber($subscriber);
|
if ($subscriber instanceof SubscriberEntity) {
|
||||||
|
$this->deleteSubscriber($subscriber);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$this->createOrUpdateSubscriber($currentFilter, $wpUser, $subscriber, $oldWpUserData);
|
$this->handleCreatingOrUpdatingSubscriber($currentFilter, $wpUser, $subscriber, $oldWpUserData);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private function deleteSubscriber(SubscriberEntity $subscriber): void {
|
||||||
* @param false|Subscriber $subscriber
|
$this->subscribersRepository->remove($subscriber);
|
||||||
*
|
$this->subscribersRepository->flush();
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
private function deleteSubscriber($subscriber) {
|
|
||||||
if ($subscriber !== false) {
|
|
||||||
// unlink subscriber from wp user and delete
|
|
||||||
$subscriber->set('wp_user_id', null);
|
|
||||||
$subscriber->delete();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $currentFilter
|
* @param string $currentFilter
|
||||||
* @param \WP_User $wpUser
|
* @param \WP_User $wpUser
|
||||||
* @param Subscriber|false $subscriber
|
* @param ?SubscriberEntity $subscriber
|
||||||
* @param array|false $oldWpUserData
|
* @param array|false $oldWpUserData
|
||||||
*/
|
*/
|
||||||
private function createOrUpdateSubscriber(string $currentFilter, \WP_User $wpUser, $subscriber = false, $oldWpUserData = false): void {
|
private function handleCreatingOrUpdatingSubscriber(string $currentFilter, \WP_User $wpUser, ?SubscriberEntity $subscriber = null, $oldWpUserData = false): void {
|
||||||
// Add or update
|
// Add or update
|
||||||
$wpSegment = $this->segmentsRepository->getWPUsersSegment();
|
$wpSegment = $this->segmentsRepository->getWPUsersSegment();
|
||||||
|
|
||||||
// find subscriber by email when is false
|
// find subscriber by email when is null
|
||||||
if (!$subscriber) {
|
if (is_null($subscriber)) {
|
||||||
$subscriber = Subscriber::where('email', $wpUser->user_email)->findOne(); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
$subscriber = $this->subscribersRepository->findOneBy(['email' => $wpUser->user_email]); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
||||||
}
|
}
|
||||||
|
|
||||||
// get first name & last name
|
// get first name & last name
|
||||||
$firstName = html_entity_decode($wpUser->first_name); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
$firstName = html_entity_decode($wpUser->first_name); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
||||||
$lastName = html_entity_decode($wpUser->last_name); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
$lastName = html_entity_decode($wpUser->last_name); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
||||||
@@ -118,7 +125,7 @@ class WP {
|
|||||||
$firstName = html_entity_decode($wpUser->display_name); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
$firstName = html_entity_decode($wpUser->display_name); // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
|
||||||
}
|
}
|
||||||
$signupConfirmationEnabled = SettingsController::getInstance()->get('signup_confirmation.enabled');
|
$signupConfirmationEnabled = SettingsController::getInstance()->get('signup_confirmation.enabled');
|
||||||
$status = $signupConfirmationEnabled ? Subscriber::STATUS_UNCONFIRMED : Subscriber::STATUS_SUBSCRIBED;
|
$status = $signupConfirmationEnabled ? SubscriberEntity::STATUS_UNCONFIRMED : SubscriberEntity::STATUS_SUBSCRIBED;
|
||||||
// we want to mark a new subscriber as unsubscribe when the checkbox from registration is unchecked
|
// we want to mark a new subscriber as unsubscribe when the checkbox from registration is unchecked
|
||||||
if (isset($_POST['mailpoet']['subscribe_on_register_active']) && (bool)$_POST['mailpoet']['subscribe_on_register_active'] === true) {
|
if (isset($_POST['mailpoet']['subscribe_on_register_active']) && (bool)$_POST['mailpoet']['subscribe_on_register_active'] === true) {
|
||||||
$status = SubscriberEntity::STATUS_UNSUBSCRIBED;
|
$status = SubscriberEntity::STATUS_UNSUBSCRIBED;
|
||||||
@@ -134,8 +141,8 @@ class WP {
|
|||||||
'source' => Source::WORDPRESS_USER,
|
'source' => Source::WORDPRESS_USER,
|
||||||
];
|
];
|
||||||
|
|
||||||
if ($subscriber !== false) {
|
if (!is_null($subscriber)) {
|
||||||
$data['id'] = $subscriber->id();
|
$data['id'] = $subscriber->getId();
|
||||||
unset($data['status']); // don't override status for existing users
|
unset($data['status']); // don't override status for existing users
|
||||||
unset($data['source']); // don't override status for existing users
|
unset($data['source']); // don't override status for existing users
|
||||||
}
|
}
|
||||||
@@ -144,9 +151,8 @@ class WP {
|
|||||||
|
|
||||||
$otherActiveSegments = [];
|
$otherActiveSegments = [];
|
||||||
if ($subscriber) {
|
if ($subscriber) {
|
||||||
$subscriber = $subscriber->withSegments();
|
$otherActiveSegments = array_filter($subscriber->getSegments()->toArray() ?? [], function (SegmentEntity $segment) {
|
||||||
$otherActiveSegments = array_filter($subscriber->segments ?? [], function ($segment) {
|
return $segment->getType() !== SegmentEntity::TYPE_WP_USERS && $segment->getDeletedAt() === null;
|
||||||
return $segment['type'] !== SegmentEntity::TYPE_WP_USERS && $segment['deleted_at'] === null;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
$isWooCustomer = $this->wooHelper->isWooCommerceActive() && in_array('customer', $wpUser->roles, true);
|
$isWooCustomer = $this->wooHelper->isWooCommerceActive() && in_array('customer', $wpUser->roles, true);
|
||||||
@@ -157,58 +163,86 @@ class WP {
|
|||||||
$data['status'] = SubscriberEntity::STATUS_UNCONFIRMED;
|
$data['status'] = SubscriberEntity::STATUS_UNCONFIRMED;
|
||||||
}
|
}
|
||||||
|
|
||||||
$subscriber = Subscriber::createOrUpdate($data);
|
try {
|
||||||
if ($subscriber->getErrors() === false && $subscriber->id > 0) {
|
$subscriber = $this->createOrUpdateSubscriber($data, $subscriber);
|
||||||
// add subscriber to the WP Users segment
|
} catch (\Exception $e) {
|
||||||
SubscriberSegment::subscribeToSegments(
|
return; // fails silently as this was the behavior of this methods before the Doctrine refactor.
|
||||||
$subscriber,
|
}
|
||||||
[$wpSegment->getId()]
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!$signupConfirmationEnabled && $subscriber->status === Subscriber::STATUS_SUBSCRIBED && $currentFilter === 'user_register') {
|
// add subscriber to the WP Users segment
|
||||||
$subscriberSegment = $this->subscriberSegmentRepository->findOneBy([
|
$this->subscriberSegmentRepository->subscribeToSegments(
|
||||||
'subscriber' => $subscriber->id(),
|
$subscriber,
|
||||||
'segment' => $wpSegment->getId(),
|
[$wpSegment]
|
||||||
]);
|
);
|
||||||
|
|
||||||
if (!is_null($subscriberSegment)) {
|
if (!$signupConfirmationEnabled && $subscriber->getStatus() === SubscriberEntity::STATUS_SUBSCRIBED && $currentFilter === 'user_register') {
|
||||||
$this->wp->doAction('mailpoet_segment_subscribed', $subscriberSegment);
|
$subscriberSegment = $this->subscriberSegmentRepository->findOneBy([
|
||||||
}
|
'subscriber' => $subscriber->getId(),
|
||||||
}
|
'segment' => $wpSegment->getId(),
|
||||||
|
]);
|
||||||
|
|
||||||
$subscribeOnRegisterEnabled = SettingsController::getInstance()->get('subscribe.on_register.enabled');
|
if (!is_null($subscriberSegment)) {
|
||||||
$sendConfirmationEmail =
|
$this->wp->doAction('mailpoet_segment_subscribed', $subscriberSegment);
|
||||||
$signupConfirmationEnabled
|
|
||||||
&& $subscribeOnRegisterEnabled
|
|
||||||
&& $currentFilter !== 'profile_update'
|
|
||||||
&& !$addingNewUserToDisabledWPSegment;
|
|
||||||
|
|
||||||
if ($sendConfirmationEmail && ($subscriber->status === Subscriber::STATUS_UNCONFIRMED)) {
|
|
||||||
/** @var ConfirmationEmailMailer $confirmationEmailMailer */
|
|
||||||
$confirmationEmailMailer = ContainerWrapper::getInstance()->get(ConfirmationEmailMailer::class);
|
|
||||||
$subscriberEntity = $this->subscribersRepository->findOneById($subscriber->id);
|
|
||||||
if ($subscriberEntity instanceof SubscriberEntity) {
|
|
||||||
try {
|
|
||||||
$confirmationEmailMailer->sendConfirmationEmailOnce($subscriberEntity);
|
|
||||||
} catch (\Exception $e) {
|
|
||||||
// ignore errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// welcome email
|
|
||||||
$scheduleWelcomeNewsletter = false;
|
|
||||||
if (in_array($currentFilter, ['profile_update', 'user_register', 'add_user_role', 'set_user_role'])) {
|
|
||||||
$scheduleWelcomeNewsletter = true;
|
|
||||||
}
|
|
||||||
if ($scheduleWelcomeNewsletter === true) {
|
|
||||||
$this->welcomeScheduler->scheduleWPUserWelcomeNotification(
|
|
||||||
$subscriber->id,
|
|
||||||
(array)$wpUser,
|
|
||||||
(array)$oldWpUserData
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$subscribeOnRegisterEnabled = SettingsController::getInstance()->get('subscribe.on_register.enabled');
|
||||||
|
$sendConfirmationEmail =
|
||||||
|
$signupConfirmationEnabled
|
||||||
|
&& $subscribeOnRegisterEnabled
|
||||||
|
&& $currentFilter !== 'profile_update'
|
||||||
|
&& !$addingNewUserToDisabledWPSegment;
|
||||||
|
|
||||||
|
if ($sendConfirmationEmail && ($subscriber->getStatus() === SubscriberEntity::STATUS_UNCONFIRMED)) {
|
||||||
|
/** @var ConfirmationEmailMailer $confirmationEmailMailer */
|
||||||
|
$confirmationEmailMailer = ContainerWrapper::getInstance()->get(ConfirmationEmailMailer::class);
|
||||||
|
try {
|
||||||
|
$confirmationEmailMailer->sendConfirmationEmailOnce($subscriber);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
// ignore errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// welcome email
|
||||||
|
$scheduleWelcomeNewsletter = false;
|
||||||
|
if (in_array($currentFilter, ['profile_update', 'user_register', 'add_user_role', 'set_user_role'])) {
|
||||||
|
$scheduleWelcomeNewsletter = true;
|
||||||
|
}
|
||||||
|
if ($scheduleWelcomeNewsletter === true) {
|
||||||
|
$this->welcomeScheduler->scheduleWPUserWelcomeNotification(
|
||||||
|
$subscriber->getId(),
|
||||||
|
(array)$wpUser,
|
||||||
|
(array)$oldWpUserData
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createOrUpdateSubscriber(array $data, ?SubscriberEntity $subscriber = null): SubscriberEntity {
|
||||||
|
if (is_null($subscriber)) {
|
||||||
|
$subscriber = new SubscriberEntity();
|
||||||
|
}
|
||||||
|
|
||||||
|
$subscriber->setWpUserId($data['wp_user_id']);
|
||||||
|
$subscriber->setEmail($data['email']);
|
||||||
|
$subscriber->setFirstName($data['first_name']);
|
||||||
|
$subscriber->setLastName($data['last_name']);
|
||||||
|
|
||||||
|
if (isset($data['status'])) {
|
||||||
|
$subscriber->setStatus($data['status']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['source'])) {
|
||||||
|
$subscriber->setSource($data['source']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['deleted_at'])) {
|
||||||
|
$subscriber->setDeletedAt($data['deleted_at']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->subscribersRepository->persist($subscriber);
|
||||||
|
$this->subscribersRepository->flush();
|
||||||
|
|
||||||
|
return $subscriber;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function synchronizeUsers(): bool {
|
public function synchronizeUsers(): bool {
|
||||||
@@ -243,25 +277,32 @@ class WP {
|
|||||||
if (!$invalidWpUserIds) {
|
if (!$invalidWpUserIds) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ORM::for_table(Subscriber::$_table)->whereIn('wp_user_id', $invalidWpUserIds)->delete_many();
|
|
||||||
|
$this->subscribersRepository->removeByWpUserIds($invalidWpUserIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function updateSubscribersEmails(): array {
|
private function updateSubscribersEmails(): array {
|
||||||
global $wpdb;
|
global $wpdb;
|
||||||
Subscriber::rawExecute('SELECT NOW();');
|
|
||||||
$startTime = Subscriber::getLastStatement()->fetch(\PDO::FETCH_COLUMN);
|
|
||||||
|
|
||||||
$subscribersTable = Subscriber::$_table;
|
$stmt = $this->databaseConnection->executeQuery('SELECT NOW();');
|
||||||
Subscriber::rawExecute(sprintf('
|
$startTime = $stmt->fetchOne();
|
||||||
UPDATE IGNORE %1$s
|
|
||||||
INNER JOIN %2$s as wu ON %1$s.wp_user_id = wu.id
|
|
||||||
SET %1$s.email = wu.user_email;
|
|
||||||
', $subscribersTable, $wpdb->users));
|
|
||||||
|
|
||||||
return ORM::for_table(Subscriber::$_table)->raw_query(sprintf(
|
if (!is_string($startTime)) {
|
||||||
'SELECT wp_user_id as id, email FROM %s
|
throw new \RuntimeException("Failed to fetch the current time.");
|
||||||
WHERE updated_at >= \'%s\';
|
}
|
||||||
', $subscribersTable, $startTime))->findArray();
|
|
||||||
|
$updateSql =
|
||||||
|
"UPDATE IGNORE {$this->subscribersTable} s
|
||||||
|
INNER JOIN {$wpdb->users} as wu ON s.wp_user_id = wu.id
|
||||||
|
SET s.email = wu.user_email";
|
||||||
|
$this->databaseConnection->executeStatement($updateSql);
|
||||||
|
|
||||||
|
$selectSql =
|
||||||
|
"SELECT wp_user_id as id, email FROM {$this->subscribersTable}
|
||||||
|
WHERE updated_at >= '{$startTime}'";
|
||||||
|
$updatedEmails = $this->databaseConnection->fetchAllAssociative($selectSql);
|
||||||
|
|
||||||
|
return $updatedEmails;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function insertSubscribers(): array {
|
private function insertSubscribers(): array {
|
||||||
@@ -276,78 +317,82 @@ class WP {
|
|||||||
$subscriberStatus = $signupConfirmationEnabled ? SubscriberEntity::STATUS_UNCONFIRMED : SubscriberEntity::STATUS_SUBSCRIBED;
|
$subscriberStatus = $signupConfirmationEnabled ? SubscriberEntity::STATUS_UNCONFIRMED : SubscriberEntity::STATUS_SUBSCRIBED;
|
||||||
$deletedAt = 'null';
|
$deletedAt = 'null';
|
||||||
}
|
}
|
||||||
$subscribersTable = Subscriber::$_table;
|
|
||||||
$insertedUserIds = ORM::for_table($wpdb->users)->raw_query(sprintf(
|
|
||||||
'SELECT %2$s.id, %2$s.user_email as email FROM %2$s
|
|
||||||
LEFT JOIN %1$s AS mps ON mps.wp_user_id = %2$s.id
|
|
||||||
WHERE mps.wp_user_id IS NULL AND %2$s.user_email != ""
|
|
||||||
', $subscribersTable, $wpdb->users))->findArray();
|
|
||||||
|
|
||||||
Subscriber::rawExecute(sprintf(
|
// Fetch users that are not in the subscribers table
|
||||||
'
|
$selectSql =
|
||||||
INSERT IGNORE INTO %1$s(wp_user_id, email, status, created_at, `source`, deleted_at)
|
"SELECT u.id, u.user_email as email
|
||||||
SELECT wu.id, wu.user_email, "%4$s", CURRENT_TIMESTAMP(), "%3$s", %5$s FROM %2$s wu
|
FROM {$wpdb->users} u
|
||||||
LEFT JOIN %1$s mps ON wu.id = mps.wp_user_id
|
LEFT JOIN {$this->subscribersTable} AS s ON s.wp_user_id = u.id
|
||||||
WHERE mps.wp_user_id IS NULL AND wu.user_email != ""
|
WHERE s.wp_user_id IS NULL AND u.user_email != ''";
|
||||||
ON DUPLICATE KEY UPDATE wp_user_id = wu.id
|
$insertedUserIds = $this->databaseConnection->fetchAllAssociative($selectSql);
|
||||||
',
|
|
||||||
$subscribersTable,
|
// Insert new users into the subscribers table
|
||||||
$wpdb->users,
|
$insertSql =
|
||||||
Source::WORDPRESS_USER,
|
"INSERT IGNORE INTO {$this->subscribersTable} (wp_user_id, email, status, created_at, `source`, deleted_at)
|
||||||
$subscriberStatus,
|
SELECT wu.id, wu.user_email, :subscriberStatus, CURRENT_TIMESTAMP(), :source, {$deletedAt}
|
||||||
$deletedAt
|
FROM {$wpdb->users} wu
|
||||||
));
|
LEFT JOIN {$this->subscribersTable} s ON wu.id = s.wp_user_id
|
||||||
|
WHERE s.wp_user_id IS NULL AND wu.user_email != ''
|
||||||
|
ON DUPLICATE KEY UPDATE wp_user_id = wu.id";
|
||||||
|
$stmt = $this->databaseConnection->prepare($insertSql);
|
||||||
|
$stmt->bindValue('subscriberStatus', $subscriberStatus);
|
||||||
|
$stmt->bindValue('source', Source::WORDPRESS_USER);
|
||||||
|
$stmt->executeStatement();
|
||||||
|
|
||||||
return $insertedUserIds;
|
return $insertedUserIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function updateFirstNames(): void {
|
private function updateFirstNames(): void {
|
||||||
global $wpdb;
|
global $wpdb;
|
||||||
$subscribersTable = Subscriber::$_table;
|
|
||||||
Subscriber::rawExecute(sprintf('
|
$sql =
|
||||||
UPDATE %1$s
|
"UPDATE {$this->subscribersTable} s
|
||||||
JOIN %2$s as wpum ON %1$s.wp_user_id = wpum.user_id AND wpum.meta_key = "first_name"
|
JOIN {$wpdb->usermeta} as wpum ON s.wp_user_id = wpum.user_id AND wpum.meta_key = 'first_name'
|
||||||
SET %1$s.first_name = SUBSTRING(wpum.meta_value, 1, 255)
|
SET s.first_name = SUBSTRING(wpum.meta_value, 1, 255)
|
||||||
WHERE %1$s.first_name = ""
|
WHERE s.first_name = ''
|
||||||
AND %1$s.wp_user_id IS NOT NULL
|
AND s.wp_user_id IS NOT NULL
|
||||||
AND wpum.meta_value IS NOT NULL
|
AND wpum.meta_value IS NOT NULL";
|
||||||
', $subscribersTable, $wpdb->usermeta));
|
|
||||||
|
$this->databaseConnection->executeStatement($sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function updateLastNames(): void {
|
private function updateLastNames(): void {
|
||||||
global $wpdb;
|
global $wpdb;
|
||||||
$subscribersTable = Subscriber::$_table;
|
|
||||||
Subscriber::rawExecute(sprintf('
|
$sql =
|
||||||
UPDATE %1$s
|
"UPDATE {$this->subscribersTable} s
|
||||||
JOIN %2$s as wpum ON %1$s.wp_user_id = wpum.user_id AND wpum.meta_key = "last_name"
|
JOIN {$wpdb->usermeta} as wpum ON s.wp_user_id = wpum.user_id AND wpum.meta_key = 'last_name'
|
||||||
SET %1$s.last_name = SUBSTRING(wpum.meta_value, 1, 255)
|
SET s.last_name = SUBSTRING(wpum.meta_value, 1, 255)
|
||||||
WHERE %1$s.last_name = ""
|
WHERE s.last_name = ''
|
||||||
AND %1$s.wp_user_id IS NOT NULL
|
AND s.wp_user_id IS NOT NULL
|
||||||
AND wpum.meta_value IS NOT NULL
|
AND wpum.meta_value IS NOT NULL";
|
||||||
', $subscribersTable, $wpdb->usermeta));
|
|
||||||
|
$this->databaseConnection->executeStatement($sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function updateFirstNameIfMissing(): void {
|
private function updateFirstNameIfMissing(): void {
|
||||||
global $wpdb;
|
global $wpdb;
|
||||||
$subscribersTable = Subscriber::$_table;
|
|
||||||
Subscriber::rawExecute(sprintf('
|
$sql =
|
||||||
UPDATE %1$s
|
"UPDATE {$this->subscribersTable} s
|
||||||
JOIN %2$s wu ON %1$s.wp_user_id = wu.id
|
JOIN {$wpdb->users} wu ON s.wp_user_id = wu.id
|
||||||
SET %1$s.first_name = wu.display_name
|
SET s.first_name = wu.display_name
|
||||||
WHERE %1$s.first_name = ""
|
WHERE s.first_name = ''
|
||||||
AND %1$s.wp_user_id IS NOT NULL
|
AND s.wp_user_id IS NOT NULL";
|
||||||
', $subscribersTable, $wpdb->users));
|
|
||||||
|
$this->databaseConnection->executeStatement($sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function insertUsersToSegment(): void {
|
private function insertUsersToSegment(): void {
|
||||||
$wpSegment = $this->segmentsRepository->getWPUsersSegment();
|
$wpSegment = $this->segmentsRepository->getWPUsersSegment();
|
||||||
$subscribersTable = Subscriber::$_table;
|
$subscribersSegmentTable = $this->entityManager->getClassMetadata(SubscriberSegmentEntity::class)->getTableName();
|
||||||
$wpMailpoetSubscriberSegmentTable = SubscriberSegment::$_table;
|
|
||||||
Subscriber::rawExecute(sprintf('
|
$sql =
|
||||||
INSERT IGNORE INTO %s(subscriber_id, segment_id, created_at)
|
"INSERT IGNORE INTO {$subscribersSegmentTable} (subscriber_id, segment_id, created_at)
|
||||||
SELECT mps.id, "%s", CURRENT_TIMESTAMP() FROM %s mps
|
SELECT s.id, '{$wpSegment->getId()}', CURRENT_TIMESTAMP() FROM {$this->subscribersTable} s
|
||||||
WHERE mps.wp_user_id > 0
|
WHERE s.wp_user_id > 0";
|
||||||
', $wpMailpoetSubscriberSegmentTable, $wpSegment->getId(), $subscribersTable));
|
|
||||||
|
$this->databaseConnection->executeStatement($sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function removeOrphanedSubscribers(): void {
|
private function removeOrphanedSubscribers(): void {
|
||||||
|
@@ -577,6 +577,17 @@ class SubscribersRepository extends Repository {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function removeByWpUserIds(array $wpUserIds) {
|
||||||
|
$queryBuilder = $this->entityManager->createQueryBuilder();
|
||||||
|
|
||||||
|
$queryBuilder
|
||||||
|
->delete(SubscriberEntity::class, 's')
|
||||||
|
->where('s.wpUserId IN (:wpUserIds)')
|
||||||
|
->setParameter('wpUserIds', $wpUserIds);
|
||||||
|
|
||||||
|
return $queryBuilder->getQuery()->execute();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return int - number of processed ids
|
* @return int - number of processed ids
|
||||||
*/
|
*/
|
||||||
|
@@ -580,11 +580,6 @@ parameters:
|
|||||||
count: 1
|
count: 1
|
||||||
path: ../../lib/Segments/SegmentsSimpleListRepository.php
|
path: ../../lib/Segments/SegmentsSimpleListRepository.php
|
||||||
|
|
||||||
-
|
|
||||||
message: "#^Parameter \\#3 \\.\\.\\.\\$values of function sprintf expects bool\\|float\\|int\\|string\\|null, mixed given\\.$#"
|
|
||||||
count: 1
|
|
||||||
path: ../../lib/Segments/WP.php
|
|
||||||
|
|
||||||
-
|
-
|
||||||
message: "#^Cannot cast mixed to int\\.$#"
|
message: "#^Cannot cast mixed to int\\.$#"
|
||||||
count: 1
|
count: 1
|
||||||
|
@@ -570,11 +570,6 @@ parameters:
|
|||||||
count: 1
|
count: 1
|
||||||
path: ../../lib/Segments/SegmentsSimpleListRepository.php
|
path: ../../lib/Segments/SegmentsSimpleListRepository.php
|
||||||
|
|
||||||
-
|
|
||||||
message: "#^Parameter \\#3 \\.\\.\\.\\$values of function sprintf expects bool\\|float\\|int\\|string\\|null, mixed given\\.$#"
|
|
||||||
count: 1
|
|
||||||
path: ../../lib/Segments/WP.php
|
|
||||||
|
|
||||||
-
|
-
|
||||||
message: "#^Cannot cast mixed to int\\.$#"
|
message: "#^Cannot cast mixed to int\\.$#"
|
||||||
count: 1
|
count: 1
|
||||||
|
@@ -620,6 +620,28 @@ class WPTest extends \MailPoetTest {
|
|||||||
remove_role('customer');
|
remove_role('customer');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testItDoesntCreateSubscriberForWPUserWithInvalidEmail() {
|
||||||
|
$userId = wp_create_user(
|
||||||
|
'invalid-email',
|
||||||
|
'password',
|
||||||
|
'editor@localhost'
|
||||||
|
);
|
||||||
|
$subscriber = $this->subscribersRepository->findOneBy(['wpUserId' => $userId]);
|
||||||
|
$this->assertNull($subscriber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testItCreatesSubscriberWhenWpUserIsCreated() {
|
||||||
|
$userId = wp_create_user(
|
||||||
|
'editor',
|
||||||
|
'password',
|
||||||
|
'editor@email.com'
|
||||||
|
);
|
||||||
|
$subscriber = $this->subscribersRepository->findOneBy(['wpUserId' => $userId]);
|
||||||
|
$this->assertInstanceOf(SubscriberEntity::class, $subscriber);
|
||||||
|
$this->assertSame('editor', $subscriber->getFirstName());
|
||||||
|
$this->assertSame('editor@email.com', $subscriber->getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
public function _after(): void {
|
public function _after(): void {
|
||||||
parent::_after();
|
parent::_after();
|
||||||
$this->cleanData();
|
$this->cleanData();
|
||||||
|
@@ -415,6 +415,20 @@ class SubscribersRepositoryTest extends \MailPoetTest {
|
|||||||
$this->assertSame($subscribers[1], $subscriber3);
|
$this->assertSame($subscribers[1], $subscriber3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testRemoveByWpUserIds(): void {
|
||||||
|
$wpUserId1 = $this->tester->createWordPressUser('subscriber1@email.com', 'author');
|
||||||
|
$wpUserId2 = $this->tester->createWordPressUser('subscriber2@email.com', 'author');
|
||||||
|
$wpUserId3 = $this->tester->createWordPressUser('subscriber3@email.com', 'author');
|
||||||
|
$subscriber3 = $this->repository->findOneBy(['wpUserId' => $wpUserId3]);
|
||||||
|
|
||||||
|
$deletedRows = $this->repository->removeByWpUserIds([$wpUserId1, $wpUserId2]);
|
||||||
|
|
||||||
|
$this->assertSame(2, $deletedRows);
|
||||||
|
$subscribers = $this->repository->findAll();
|
||||||
|
$this->assertCount(1, $subscribers);
|
||||||
|
$this->assertSame($subscribers[0], $subscriber3);
|
||||||
|
}
|
||||||
|
|
||||||
private function createSubscriber(string $email, ?DateTimeImmutable $deletedAt = null): SubscriberEntity {
|
private function createSubscriber(string $email, ?DateTimeImmutable $deletedAt = null): SubscriberEntity {
|
||||||
$subscriber = new SubscriberEntity();
|
$subscriber = new SubscriberEntity();
|
||||||
$subscriber->setEmail($email);
|
$subscriber->setEmail($email);
|
||||||
|
Reference in New Issue
Block a user