serviceFactory = $serviceFactory; $this->entityManager = $entityManager; } public function run(string $targetType, string $targetId, StdClass $data): void { if (!$targetId) { throw new Error(); } $service = $this->serviceFactory->create('InboundEmail'); $entity = $this->entityManager->getEntity('InboundEmail', $targetId); if (!$entity) { throw new Error("Job CheckInboundEmails '".$targetId."': InboundEmail does not exist.", -1); } if ($entity->get('status') !== 'Active') { throw new Error("Job CheckInboundEmails '".$targetId."': InboundEmail is not active.", -1); } try { $service->fetchFromMailServer($entity); } catch (Throwable $e) { throw new Error('Job CheckInboundEmails '.$entity->id.': [' . $e->getCode() . '] ' .$e->getMessage()); } } public function prepare(ScheduledJob $scheduledJob, string $executeTime): void { $collection = $this->entityManager ->getRepository('InboundEmail') ->where([ 'status' => 'Active', 'useImap' => true, ]) ->find(); foreach ($collection as $entity) { $running = $this->entityManager ->getRepository('Job') ->where([ 'scheduledJobId' => $scheduledJob->id, 'status' => [JobManager::RUNNING, JobManager::READY], 'targetType' => 'InboundEmail', 'targetId' => $entity->id, ]) ->findOne(); if ($running) { continue; } $countPending = $this->entityManager ->getRepository('Job') ->where([ 'scheduledJobId' => $scheduledJob->id, 'status' => JobManager::PENDING, 'targetType' => 'InboundEmail', 'targetId' => $entity->id, ]) ->count(); if ($countPending > 1) { continue; } $jobEntity = $this->entityManager->getEntity('Job'); $jobEntity->set([ 'name' => $scheduledJob->get('name'), 'scheduledJobId' => $scheduledJob->id, 'executeTime' => $executeTime, 'targetType' => 'InboundEmail', 'targetId' => $entity->id, ]); $this->entityManager->saveEntity($jobEntity); } } }