<?php
namespace App\EventSubscriber;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Model\DataObject\Report;
use App\Service\TwitterService;
use App\C2IntegrationBundle\Service\C2Service;
use Symfony\Contracts\Translation\TranslatorInterface;
class TodayWeatherReportTwitterEventListner
{
private TwitterService $twitterService;
private C2Service $c2Service;
public function __construct(private TranslatorInterface $translator)
{
$this->twitterService = new TwitterService();
$this->c2Service = new C2Service();
}
public function onObjectCreate(DataObjectEvent $reportObject): void
{
$report = $reportObject->getObject();
if ($this->shouldHandleReport($report)) {
$this->handleTodayWeatherReport($report);
}
}
public function onObjectUpdate(DataObjectEvent $reportObject): void
{
$report = $reportObject->getObject();
if ($this->shouldHandleReport($report)) {
$this->handleTodayWeatherReport($report);
}
}
private function shouldHandleReport($report): bool
{
return ($report instanceof Report) &&
$report->isPublished(true) &&
$report->getReportType()?->getReportKey() === 'today-weather-report' &&
$report->getForTwitterChannel() == true;
}
private function handleTodayWeatherReport(Report $report): void
{
$assetsToPost = $this->collectAssets($report);
foreach ($assetsToPost as $assetData) {
$assetObj = $assetData['asset'];
$assetPath = PIMCORE_PROJECT_ROOT . '/public/var/assets' . $assetObj->getPath() . $assetObj->getFileName();
if (!file_exists($assetPath)) {
continue;
}
if ($report->getIsMarine() === true) {
$tweetText = (string) $report->getTwitterDescription();
} elseif ($assetData['lang'] == 'ar') {
$tweetText = $this->translator->trans('Today\'s Weather Report', [], null, 'ar');
} else {
$tweetText = $this->translator->trans('Today\'s Weather Report', [], null, 'en');
}
$tweet = $this->twitterService->uploadMedia($assetPath, $tweetText);
if ($tweet && !isset($tweet['error'])) {
$this->processTweetResponse($tweet, $assetObj, $report);
} elseif ($tweet && isset($tweet['error'])) {
// Log the error but continue processing other assets
$report->setTwitterLog($tweet['data']);
}
}
$report->save();
}
private function collectAssets(Report $report): array
{
$assetAr = $report->getAssetAr();
if (!$assetAr) {
return [];
}
return [['asset' => $assetAr, 'lang' => 'ar']];
}
private function processTweetResponse(array $tweet, $assetObj, Report $report): void
{
if (isset($tweet['result']->data)) {
$tweetText = $tweet['result']?->data?->text;
preg_match('/https?:\/\/\S+/', $tweetText, $matches);
$url = $matches[0] ?? null;
if ($url) {
$this->c2Service->addAsset([$assetObj], $url);
}
}
if (!empty($tweet['tweetId'])) {
$report->setTwitterId($tweet['tweetId']);
}
$report->setTwitterLog($tweet['data']);
}
}