src/Timeline/EventSubscriber/TimelinePostTranslationSubscriber.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Timeline\EventSubscriber;
  3. use App\Core\Service\GoogleTranslateClient;
  4. use App\Timeline\Event\TimelinePostEvents;
  5. use App\Timeline\Event\TimelinePostPublishedEvent;
  6. use Pimcore\Event\DataObjectEvents;
  7. use Pimcore\Event\Model\DataObjectEvent;
  8. use Pimcore\Model\DataObject\TimelinePost;
  9. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class TimelinePostTranslationSubscriber implements EventSubscriberInterface
  12. {
  13.   public function __construct(
  14.     protected GoogleTranslateClient $googleTranslateClient,
  15.     protected ContainerBagInterface $params
  16.   ) {
  17.   }
  18.   public static function getSubscribedEvents()
  19.   {
  20.     return [
  21.       DataObjectEvents::PRE_UPDATE => 'onPreUpdate',
  22.       TimelinePostEvents::PUBLISHED => 'postPublished',
  23.     ];
  24.   }
  25.   public function onPreUpdate(DataObjectEvent $event)
  26.   {
  27.     $object $event->getObject();
  28.     $className = (new \ReflectionClass($object))->getShortName();
  29.     if (!in_array($className, ['TimelinePost'])) {
  30.       return;
  31.     }
  32.     if (!$object instanceof TimelinePost) {
  33.       throw new \Exception('Field is not a TimelinePost'1);
  34.     }
  35.     if (!$event->hasArgument('saveVersionOnly') && !$object->getDetectedLanguage()) {
  36.       $this->updateTextLocale($object);
  37.     }
  38.   }
  39.   public function postPublished(TimelinePostPublishedEvent $event)
  40.   {
  41.     if ($event->post->getDetectedLanguage()) {
  42.       $post $this->updateTextLocale($event->post);
  43.       $post->save();
  44.     }
  45.   }
  46.   protected function updateTextLocale($post)
  47.   {
  48.     try {
  49.       $content $post->getText();
  50.       if (mb_strlen($content) > && $this->params->get('kernel.environment') != 'dev' && $language $this->googleTranslateClient->detectLanguage($content)) {
  51.         $post->setDetectedLanguage($language);
  52.       }
  53.     } catch(\Exception $e) {}
  54.     return $post;
  55.   }
  56. }