DynamicSegments
2 days ago
RestApi
1 week ago
SegmentDependencyValidator.php
3 years ago
SegmentListingRepository.php
2 weeks ago
SegmentSaveController.php
2 weeks ago
SegmentSubscribersRepository.php
4 weeks ago
SegmentsFinder.php
3 years ago
SegmentsRepository.php
2 weeks ago
SegmentsSimpleListRepository.php
4 weeks ago
SubscribersFinder.php
4 weeks ago
WP.php
3 weeks ago
WooCommerce.php
4 weeks ago
index.php
3 years ago
SegmentsRepository.php
387 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Segments; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use DateTime; |
| 9 | use MailPoet\ConflictException; |
| 10 | use MailPoet\Doctrine\Repository; |
| 11 | use MailPoet\Entities\DynamicSegmentFilterData; |
| 12 | use MailPoet\Entities\DynamicSegmentFilterEntity; |
| 13 | use MailPoet\Entities\NewsletterSegmentEntity; |
| 14 | use MailPoet\Entities\SegmentEntity; |
| 15 | use MailPoet\Entities\SubscriberSegmentEntity; |
| 16 | use MailPoet\Form\FormsRepository; |
| 17 | use MailPoet\InvalidStateException; |
| 18 | use MailPoet\Logging\LoggerFactory; |
| 19 | use MailPoet\Newsletter\Segment\NewsletterSegmentRepository; |
| 20 | use MailPoet\NotFoundException; |
| 21 | use MailPoet\WP\Functions as WPFunctions; |
| 22 | use MailPoetVendor\Carbon\Carbon; |
| 23 | use MailPoetVendor\Doctrine\DBAL\ArrayParameterType; |
| 24 | use MailPoetVendor\Doctrine\DBAL\ParameterType; |
| 25 | use MailPoetVendor\Doctrine\ORM\EntityManager; |
| 26 | use MailPoetVendor\Doctrine\ORM\ORMException; |
| 27 | |
| 28 | /** |
| 29 | * @extends Repository<SegmentEntity> |
| 30 | */ |
| 31 | class SegmentsRepository extends Repository { |
| 32 | |
| 33 | /** @var NewsletterSegmentRepository */ |
| 34 | private $newsletterSegmentRepository; |
| 35 | |
| 36 | /** @var FormsRepository */ |
| 37 | private $formsRepository; |
| 38 | |
| 39 | /** @var WPFunctions */ |
| 40 | private $wp; |
| 41 | |
| 42 | /** @var LoggerFactory */ |
| 43 | private $loggerFactory; |
| 44 | |
| 45 | public function __construct( |
| 46 | EntityManager $entityManager, |
| 47 | NewsletterSegmentRepository $newsletterSegmentRepository, |
| 48 | FormsRepository $formsRepository, |
| 49 | WPFunctions $wp, |
| 50 | LoggerFactory $loggerFactory |
| 51 | ) { |
| 52 | parent::__construct($entityManager); |
| 53 | $this->newsletterSegmentRepository = $newsletterSegmentRepository; |
| 54 | $this->formsRepository = $formsRepository; |
| 55 | $this->wp = $wp; |
| 56 | $this->loggerFactory = $loggerFactory; |
| 57 | } |
| 58 | |
| 59 | protected function getEntityClassName() { |
| 60 | return SegmentEntity::class; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * @param string[] $types |
| 65 | * @return SegmentEntity[] |
| 66 | */ |
| 67 | public function findByTypeNotIn(array $types): array { |
| 68 | return $this->doctrineRepository->createQueryBuilder('s') |
| 69 | ->select('s') |
| 70 | ->where('s.type NOT IN (:types)') |
| 71 | ->setParameter('types', $types) |
| 72 | ->getQuery() |
| 73 | ->getResult(); |
| 74 | } |
| 75 | |
| 76 | public function getWPUsersSegment(): SegmentEntity { |
| 77 | $cached = current( |
| 78 | array_filter( |
| 79 | $this->getAllFromIdentityMap(), |
| 80 | fn(SegmentEntity $segment) => $segment->getType() === SegmentEntity::TYPE_WP_USERS |
| 81 | ) |
| 82 | ); |
| 83 | |
| 84 | if ($cached) { |
| 85 | return $cached; |
| 86 | } |
| 87 | |
| 88 | $segment = $this->findOneBy(['type' => SegmentEntity::TYPE_WP_USERS]); |
| 89 | if (!$segment) { |
| 90 | // create the wp users segment |
| 91 | $segment = new SegmentEntity( |
| 92 | __('WordPress Users', 'mailpoet'), |
| 93 | SegmentEntity::TYPE_WP_USERS, |
| 94 | __('This list contains all of your WordPress users.', 'mailpoet') |
| 95 | ); |
| 96 | $this->entityManager->persist($segment); |
| 97 | $this->entityManager->flush(); |
| 98 | } |
| 99 | return $segment; |
| 100 | } |
| 101 | |
| 102 | public function getWooCommerceSegment(): SegmentEntity { |
| 103 | $cached = current( |
| 104 | array_filter( |
| 105 | $this->getAllFromIdentityMap(), |
| 106 | fn(SegmentEntity $segment) => $segment->getType() === SegmentEntity::TYPE_WC_USERS |
| 107 | ) |
| 108 | ); |
| 109 | |
| 110 | if ($cached) { |
| 111 | return $cached; |
| 112 | } |
| 113 | |
| 114 | $segment = $this->findOneBy(['type' => SegmentEntity::TYPE_WC_USERS]); |
| 115 | if (!$segment) { |
| 116 | // create the WooCommerce customers segment |
| 117 | $segment = new SegmentEntity( |
| 118 | __('WooCommerce Customers', 'mailpoet'), |
| 119 | SegmentEntity::TYPE_WC_USERS, |
| 120 | __('This list contains all of your WooCommerce customers.', 'mailpoet') |
| 121 | ); |
| 122 | $this->entityManager->persist($segment); |
| 123 | $this->entityManager->flush(); |
| 124 | } |
| 125 | return $segment; |
| 126 | } |
| 127 | |
| 128 | public function getCountsPerType(): array { |
| 129 | $results = $this->doctrineRepository->createQueryBuilder('s') |
| 130 | ->select('s.type, COUNT(s) as cnt') |
| 131 | ->where('s.deletedAt IS NULL') |
| 132 | ->groupBy('s.type') |
| 133 | ->getQuery() |
| 134 | ->getResult(); |
| 135 | |
| 136 | $countMap = []; |
| 137 | foreach ($results as $result) { |
| 138 | $countMap[$result['type']] = (int)$result['cnt']; |
| 139 | } |
| 140 | return $countMap; |
| 141 | } |
| 142 | |
| 143 | public function isNameUnique(string $name, ?int $id): bool { |
| 144 | $qb = $this->doctrineRepository->createQueryBuilder('s') |
| 145 | ->select('s') |
| 146 | ->where('s.name = :name') |
| 147 | ->setParameter('name', $name); |
| 148 | |
| 149 | if ($id !== null) { |
| 150 | $qb->andWhere('s.id != :id') |
| 151 | ->setParameter('id', $id); |
| 152 | } |
| 153 | |
| 154 | $results = $qb->getQuery() |
| 155 | ->getResult(); |
| 156 | |
| 157 | return count($results) === 0; |
| 158 | } |
| 159 | |
| 160 | /** |
| 161 | * @throws ConflictException |
| 162 | */ |
| 163 | public function verifyNameIsUnique(string $name, ?int $id): void { |
| 164 | if (!$this->isNameUnique($name, $id)) { |
| 165 | throw new ConflictException("Could not create new segment with name [{$name}] because a segment with that name already exists."); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * @param int $id |
| 171 | * |
| 172 | * @return SegmentEntity |
| 173 | * @throws InvalidStateException |
| 174 | */ |
| 175 | public function verifyDynamicSegmentExists(int $id): SegmentEntity { |
| 176 | try { |
| 177 | $dynamicSegment = $this->findOneById($id); |
| 178 | if (!$dynamicSegment instanceof SegmentEntity) { |
| 179 | throw InvalidStateException::create()->withMessage(sprintf("Could not find segment with ID '%s'.", $id)); |
| 180 | } |
| 181 | if ($dynamicSegment->getType() !== SegmentEntity::TYPE_DYNAMIC) { |
| 182 | throw InvalidStateException::create()->withMessage(sprintf("Segment with ID '%s' is not a dynamic segment. Its type is %s.", $id, $dynamicSegment->getType())); |
| 183 | } |
| 184 | } catch (InvalidStateException $exception) { |
| 185 | $this->loggerFactory->getLogger(LoggerFactory::TOPIC_SEGMENTS)->error(sprintf("Could not verify existence of dynamic segment: %s", $exception->getMessage())); |
| 186 | throw $exception; |
| 187 | } |
| 188 | return $dynamicSegment; |
| 189 | } |
| 190 | |
| 191 | /** |
| 192 | * @param DynamicSegmentFilterData[] $filtersData |
| 193 | * @throws ConflictException |
| 194 | * @throws NotFoundException |
| 195 | * @throws ORMException |
| 196 | */ |
| 197 | public function createOrUpdate( |
| 198 | string $name, |
| 199 | string $description = '', |
| 200 | string $type = SegmentEntity::TYPE_DEFAULT, |
| 201 | array $filtersData = [], |
| 202 | ?int $id = null, |
| 203 | bool $displayInManageSubscriptionPage = true, |
| 204 | ?int $confirmationEmailId = null, |
| 205 | ?int $confirmationPageId = null, |
| 206 | ?string $publicDescription = null |
| 207 | ): SegmentEntity { |
| 208 | if ($confirmationEmailId !== null && $confirmationEmailId <= 0) { |
| 209 | $confirmationEmailId = null; |
| 210 | } |
| 211 | if ($confirmationPageId !== null && $confirmationPageId <= 0) { |
| 212 | $confirmationPageId = null; |
| 213 | } |
| 214 | $displayInManageSubPage = $type === SegmentEntity::TYPE_DEFAULT ? $displayInManageSubscriptionPage : false; |
| 215 | |
| 216 | if ($id) { |
| 217 | $segment = $this->findOneById($id); |
| 218 | if (!$segment instanceof SegmentEntity) { |
| 219 | throw new NotFoundException("Segment with ID [{$id}] was not found."); |
| 220 | } |
| 221 | if ($name !== $segment->getName()) { |
| 222 | $this->verifyNameIsUnique($name, $id); |
| 223 | $segment->setName($name); |
| 224 | } |
| 225 | $segment->setDescription($description); |
| 226 | $segment->setDisplayInManageSubscriptionPage($displayInManageSubPage); |
| 227 | $segment->setConfirmationEmailId($confirmationEmailId); |
| 228 | $segment->setConfirmationPageId($confirmationPageId); |
| 229 | if ($publicDescription !== null) { |
| 230 | $segment->setPublicDescription($publicDescription); |
| 231 | } |
| 232 | } else { |
| 233 | $this->verifyNameIsUnique($name, $id); |
| 234 | $segment = new SegmentEntity($name, $type, $description); |
| 235 | $segment->setDisplayInManageSubscriptionPage($displayInManageSubPage); |
| 236 | $segment->setConfirmationEmailId($confirmationEmailId); |
| 237 | $segment->setConfirmationPageId($confirmationPageId); |
| 238 | $segment->setPublicDescription($publicDescription ?? ''); |
| 239 | $this->persist($segment); |
| 240 | } |
| 241 | |
| 242 | // We want to remove redundant filters before update |
| 243 | while ($segment->getDynamicFilters()->count() > count($filtersData)) { |
| 244 | $filterEntity = $segment->getDynamicFilters()->last(); |
| 245 | if ($filterEntity) { |
| 246 | $segment->getDynamicFilters()->removeElement($filterEntity); |
| 247 | $this->entityManager->remove($filterEntity); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | $createOrUpdateFilter = function ($filterData, $key) use ($segment) { |
| 252 | if ($filterData instanceof DynamicSegmentFilterData) { |
| 253 | $filterEntity = $segment->getDynamicFilters()->get($key); |
| 254 | if (!$filterEntity instanceof DynamicSegmentFilterEntity) { |
| 255 | $filterEntity = new DynamicSegmentFilterEntity($segment, $filterData); |
| 256 | $segment->getDynamicFilters()->add($filterEntity); |
| 257 | $this->entityManager->persist($filterEntity); |
| 258 | } else { |
| 259 | $filterEntity->setFilterData($filterData); |
| 260 | } |
| 261 | } |
| 262 | }; |
| 263 | |
| 264 | $wpActionName = 'mailpoet_dynamic_segments_filters_save'; |
| 265 | if ($this->wp->hasAction($wpActionName)) { |
| 266 | $this->wp->doAction($wpActionName, $createOrUpdateFilter, $filtersData); |
| 267 | } else { |
| 268 | $filterData = reset($filtersData); |
| 269 | $key = key($filtersData); |
| 270 | $createOrUpdateFilter($filterData, $key); |
| 271 | } |
| 272 | |
| 273 | $this->flush(); |
| 274 | return $segment; |
| 275 | } |
| 276 | |
| 277 | public function bulkDelete(array $ids, string $type = SegmentEntity::TYPE_DEFAULT): int { |
| 278 | if (empty($ids)) { |
| 279 | return 0; |
| 280 | } |
| 281 | |
| 282 | $count = 0; |
| 283 | $this->entityManager->transactional(function (EntityManager $entityManager) use ($ids, $type, &$count) { |
| 284 | $subscriberSegmentTable = $entityManager->getClassMetadata(SubscriberSegmentEntity::class)->getTableName(); |
| 285 | $segmentTable = $entityManager->getClassMetadata(SegmentEntity::class)->getTableName(); |
| 286 | $segmentFiltersTable = $entityManager->getClassMetadata(DynamicSegmentFilterEntity::class)->getTableName(); |
| 287 | |
| 288 | $entityManager->getConnection()->executeStatement(" |
| 289 | DELETE ss FROM $subscriberSegmentTable ss |
| 290 | JOIN $segmentTable s ON ss.`segment_id` = s.`id` |
| 291 | WHERE ss.`segment_id` IN (:ids) |
| 292 | AND s.`type` = :type |
| 293 | ", [ |
| 294 | 'ids' => $ids, |
| 295 | 'type' => $type, |
| 296 | ], ['ids' => ArrayParameterType::INTEGER]); |
| 297 | |
| 298 | $entityManager->getConnection()->executeStatement(" |
| 299 | DELETE df FROM $segmentFiltersTable df |
| 300 | WHERE df.`segment_id` IN (:ids) |
| 301 | ", [ |
| 302 | 'ids' => $ids, |
| 303 | ], ['ids' => ArrayParameterType::INTEGER]); |
| 304 | |
| 305 | $queryBuilder = $entityManager->createQueryBuilder(); |
| 306 | $count = $queryBuilder->delete(SegmentEntity::class, 's') |
| 307 | ->where('s.id IN (:ids)') |
| 308 | ->andWhere('s.type = :type') |
| 309 | ->setParameter('ids', $ids, ArrayParameterType::INTEGER) |
| 310 | ->setParameter('type', $type, ParameterType::STRING) |
| 311 | ->getQuery()->execute(); |
| 312 | |
| 313 | $queryBuilder = $entityManager->createQueryBuilder(); |
| 314 | $queryBuilder->delete(NewsletterSegmentEntity::class, 'ns') |
| 315 | ->where('ns.segment IN (:ids)') |
| 316 | ->setParameter('ids', $ids, ArrayParameterType::INTEGER) |
| 317 | ->getQuery()->execute(); |
| 318 | }); |
| 319 | return $count; |
| 320 | } |
| 321 | |
| 322 | public function bulkTrash(array $ids, string $type = SegmentEntity::TYPE_DEFAULT): int { |
| 323 | $activelyUsedInNewsletters = $this->newsletterSegmentRepository->getSubjectsOfActivelyUsedEmailsForSegments($ids); |
| 324 | $activelyUsedInForms = $this->formsRepository->getNamesOfFormsForSegments(); |
| 325 | $activelyUsed = array_unique(array_merge(array_keys($activelyUsedInNewsletters), array_keys($activelyUsedInForms))); |
| 326 | $ids = array_diff($ids, $activelyUsed); |
| 327 | return $this->updateDeletedAt($ids, new Carbon(), $type); |
| 328 | } |
| 329 | |
| 330 | public function doTrash(array $ids, string $type = SegmentEntity::TYPE_DEFAULT): int { |
| 331 | return $this->updateDeletedAt($ids, new Carbon(), $type); |
| 332 | } |
| 333 | |
| 334 | public function bulkRestore(array $ids, string $type = SegmentEntity::TYPE_DEFAULT): int { |
| 335 | return $this->updateDeletedAt($ids, null, $type); |
| 336 | } |
| 337 | |
| 338 | private function updateDeletedAt(array $ids, ?DateTime $deletedAt, string $type): int { |
| 339 | if (empty($ids)) { |
| 340 | return 0; |
| 341 | } |
| 342 | |
| 343 | $rows = $this->entityManager->createQueryBuilder()->update(SegmentEntity::class, 's') |
| 344 | ->set('s.deletedAt', ':deletedAt') |
| 345 | ->where('s.id IN (:ids)') |
| 346 | ->andWhere('s.type IN (:type)') |
| 347 | ->setParameter('deletedAt', $deletedAt) |
| 348 | ->setParameter('ids', $ids) |
| 349 | ->setParameter('type', $type) |
| 350 | ->getQuery()->execute(); |
| 351 | |
| 352 | return $rows; |
| 353 | } |
| 354 | |
| 355 | public function findByUpdatedScoreNotInLastDay(int $limit): array { |
| 356 | $dateTime = (new Carbon())->subDay(); |
| 357 | return $this->entityManager->createQueryBuilder() |
| 358 | ->select('s') |
| 359 | ->from(SegmentEntity::class, 's') |
| 360 | ->where('s.averageEngagementScoreUpdatedAt IS NULL') |
| 361 | ->orWhere('s.averageEngagementScoreUpdatedAt < :dateTime') |
| 362 | ->setParameter('dateTime', $dateTime) |
| 363 | ->getQuery() |
| 364 | ->setMaxResults($limit) |
| 365 | ->getResult(); |
| 366 | } |
| 367 | |
| 368 | /** |
| 369 | * Returns count of segments that have more than one dynamic filter |
| 370 | */ |
| 371 | public function getSegmentCountWithMultipleFilters(): int { |
| 372 | $segmentFiltersTable = $this->entityManager->getClassMetadata(DynamicSegmentFilterEntity::class)->getTableName(); |
| 373 | $qbInner = $this->entityManager->getConnection()->createQueryBuilder() |
| 374 | ->select('COUNT(DISTINCT sf.id) AS segmentCount') |
| 375 | ->from($segmentFiltersTable, 'sf') |
| 376 | ->groupBy('sf.segment_id') |
| 377 | ->having('COUNT(sf.id) > 1'); |
| 378 | /** @var null|int $result */ |
| 379 | $result = $this->entityManager->getConnection()->createQueryBuilder() |
| 380 | ->select('count(*)') |
| 381 | ->from(sprintf('(%s) as subCounts', $qbInner->getSQL())) |
| 382 | ->execute() |
| 383 | ->fetchOne(); |
| 384 | return (int)$result; |
| 385 | } |
| 386 | } |
| 387 |