subscribersRepository = $subscribersRepository; $this->woocommerce = $woocommerce; $this->woocommerceHelper = $woocommerceHelper; } public function transform(Subject $data): Subject { if ($this->accepts() !== $data->getKey()) { throw new \InvalidArgumentException('Invalid subject type'); } $subscriber = $this->findOrCreateSubscriber($data); if (!$subscriber instanceof SubscriberEntity) { throw new \InvalidArgumentException('Subscriber not found'); } return new Subject(SubscriberSubject::KEY, ['subscriber_id' => $subscriber->getId()]); } public function accepts(): string { return OrderSubject::KEY; } public function returns(): string { return SubscriberSubject::KEY; } private function findOrCreateSubscriber(Subject $order): ?SubscriberEntity { $subscriber = $this->findSubscriber($order); if ($subscriber) { return $subscriber; } $orderId = $order->getArgs()['order_id'] ?? null; if (!$orderId) { return null; } $this->woocommerce->synchronizeGuestCustomer($orderId); return $this->findSubscriber($order); } private function findSubscriber(Subject $order): ?SubscriberEntity { $orderId = $order->getArgs()['order_id'] ?? null; if (!$orderId) { return null; } $wcOrder = $this->woocommerceHelper->wcGetOrder($orderId); if (!$wcOrder instanceof \WC_Order) { return null; } $billingEmail = $wcOrder->get_billing_email(); return $billingEmail ? $this->subscribersRepository->findOneBy(['email' => $billingEmail]) : $this->subscribersRepository->findOneBy(['wpUserId' => $wcOrder->get_user_id()]); } }