src/EventSubscriber/TwitterEwsEndEventListner.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Carbon\Carbon;
  4. use Pimcore\Mail;
  5. use Pimcore\Model\DataObject;
  6. use Pimcore\Event\Model\DataObjectEvent;
  7. use Pimcore\Model\DataObject\EwsNotification;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use App\Service\TwitterService;
  10. use App\C2IntegrationBundle\Service\C2Service;
  11. use Pimcore\Log\ApplicationLogger;
  12. class TwitterEwsEndEventListner
  13. {
  14.     private TwitterService $twitterService;
  15.     private C2Service $c2Service;
  16.     private ApplicationLogger $logger;
  17.     /**
  18.      * Alert ids already handled in this request. The listener saves the object after tweeting,
  19.      * which re-fires pimcore.dataobject.postUpdate; without this guard it would re-enter and
  20.      * post a duplicate tweet (rejected by Twitter as duplicate content).
  21.      */
  22.     private static array $processedInRequest = [];
  23.     public function __construct(ApplicationLogger $logger)
  24.     {
  25.         $this->twitterService = new TwitterService();
  26.         $this->c2Service = new C2Service();
  27.         $this->logger $logger;
  28.     }
  29.     public function onObjectUpdate(DataObjectEvent $ewsNotificationObject)
  30.     {
  31.         $ewsNotification $ewsNotificationObject->getObject();
  32.         // DIAGNOSTIC (temporary): log the gate values on every EWS save so we can see
  33.         // why the End tweet is skipped. Remove once the End-tweet issue is resolved.
  34.         if ($ewsNotification instanceof EwsNotification) {
  35.             $this->logger->info(sprintf(
  36.                 '[END-DIAG] EndTweetListener fired for EWS ID %s | published=%s | enableTwitter=%s | status=%s',
  37.                 $ewsNotification->getId(),
  38.                 var_export($ewsNotification->isPublished(true), true),
  39.                 var_export($ewsNotification->getEnableTwitterNotification(), true),
  40.                 var_export($ewsNotification->getStatus(), true)
  41.             ));
  42.         }
  43.         if (
  44.             ($ewsNotification instanceof EwsNotification) &&
  45.             ($ewsNotification->isPublished(true)) &&
  46.             $ewsNotification->getEnableTwitterNotification() == true &&
  47.             $ewsNotification->getStatus() === "ended"
  48.         ) {
  49.             // Prevent re-entry from the $ewsNotification->save() below re-firing postUpdate.
  50.             $ewsId $ewsNotification->getId();
  51.             if (isset(self::$processedInRequest[$ewsId])) {
  52.                 return;
  53.             }
  54.             self::$processedInRequest[$ewsId] = true;
  55.             $this->logger->info("[END-DIAG] Gate passed, entering End tweet flow for EWS ID: {$ewsId}");
  56.             try {
  57.                 // Twitter rejects duplicate status text, so the caption must be unique per alert.
  58.                 // The early-warning URL carries the alert id, guaranteeing uniqueness.
  59.                 $HashTagcontent trim(
  60.                     "#alertEnd\n"
  61.                     . ($ewsNotification->getEwsSearchId('ar') ? $ewsNotification->getEwsSearchId('ar') . "\n" '')
  62.                     . 'https://beta.ncm.gov.sa/en/early-warning/' $ewsId
  63.                 );
  64.                 // Post the browser-rendered image persisted on the alert (endXAttachment, set
  65.                 // from x_img by the end action). If it's missing there is nothing to tweet.
  66.                 $asset $ewsNotification->getEndXAttachment();
  67.                 if (!$asset instanceof \Pimcore\Model\Asset) {
  68.                     $this->logger->error("[END-DIAG] No endXAttachment image for EWS ID: {$ewsId}; skipping tweet.");
  69.                     return;
  70.                 }
  71.                 $this->logger->info("[END-DIAG] Using persisted endXAttachment asset id {$asset->getId()} for EWS ID: {$ewsId}");
  72.                 $asset_path PIMCORE_PROJECT_ROOT '/public/var/assets' $asset->getPath() . $asset->getFileName();
  73.                 $this->logger->info("[END-DIAG] Asset created at {$asset_path} (exists=" var_export(is_file($asset_path), true) . ") for EWS ID: {$ewsId}");
  74.                 $this->logger->info("[END-DIAG] Calling Twitter uploadMedia for EWS ID: {$ewsId}");
  75.                 $tweet $this->twitterService->uploadMedia($asset_path$HashTagcontent);
  76.                 $this->logger->info("[END-DIAG] uploadMedia returned (httpCode=" . ($tweet['httpCode'] ?? 'n/a') . ") for EWS ID: {$ewsId}");
  77.             
  78.                
  79.               
  80.                 if ($tweet) {
  81.                     if (isset($tweet['result']->data)) {
  82.                         $tweet_text $tweet['result']?->data?->text;
  83.                         preg_match('/https?:\/\/\S+/'$tweet_text$matches);
  84.                         $url $matches[0] ?? null;
  85.                         $this->c2Service->addAsset([$asset], $url);
  86.                     }
  87.                     if (!empty($tweet['tweetId'])) {
  88.                         $ewsNotification->setTwitterId($tweet['tweetId']);
  89.                     }
  90.                     $ewsNotification->setTwitterLog($tweet['data']);
  91.                     $ewsNotification->save();
  92.                     $logContext = [
  93.                         'ewsId' => $ewsNotification->getId(),
  94.                         'tweetId' => $tweet['tweetId'] ?? null,
  95.                         'httpCode' => $tweet['httpCode'],
  96.                         'response' => $tweet['data']
  97.                     ];
  98.                     if (in_array($tweet['httpCode'], [200201204])) {
  99.                         $this->logger->info("Twitter post successful for EWS ID: {$ewsNotification->getId()}"$logContext);
  100.                     } elseif ($tweet['httpCode'] === 403) {
  101.                         $responseData json_decode($tweet['data'], true);
  102.                         $errorMessage $responseData['detail'] ?? 'Forbidden';
  103.                         $this->logger->error("Twitter post failed (403) for EWS ID: {$ewsNotification->getId()} - $errorMessage"$logContext);
  104.                     } else {
  105.                         $this->logger->error("Twitter post failed (HTTP {$tweet['httpCode']}) for EWS ID: {$ewsNotification->getId()}"$logContext);
  106.                     }
  107.                 } else {
  108.                     $this->logger->error("No tweet response for EWS ID: {$ewsNotification->getId()}");
  109.                 }
  110.             } catch (\Throwable $e) {
  111.                 $this->logger->error("Exception occurred while posting to Twitter for EWS ID: {$ewsNotification->getId()} - " $e->getMessage(), [
  112.                     'exception' => $e->getTraceAsString()
  113.                 ]);
  114.             }
  115.         }
  116.     }
  117. }