<?php
namespace App\EventListener;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Model\DataObject\Comment;
use Pimcore\Model\DataObject\News;
use App\Services\NewsServices;
class NewsEventListener
{
public function postAdd(DataObjectEvent $e)
{
$object = $e->getObject();
self::coutingTotalComment($object);
}
public function postUpdate(DataObjectEvent $e)
{
$object = $e->getObject();
self::coutingTotalComment($object);
if ($object instanceof News && !empty($object->getLocalizedfields()->getItems())) {
foreach ($object->getLocalizedfields()->getItems() as $key => $item) {
if ($key == "vi") {
NewsServices::deleteFolder($item['title']);
$content = $item['content'];
preg_match_all('/<img\s+[^>]*src="([^"]*)"[^>]*>/i', $content, $matches);
if(empty($matches[0])){
preg_match_all('/src=["\']?(data:image\/[^;]+;base64,[^"\']+)["\']?/i', $content, $matches);
}
$allImgTags = $matches[0];
$allSrcValues = $matches[1];
if (!empty($allSrcValues)) {
foreach ($allSrcValues as $imgData) {
if (strpos($imgData, 'base64') !== false) {
$charactersToRemove = ['"', "'", '\\', '/', ':'];
$item['title'] = str_replace($charactersToRemove, '', $item['title']);
$fullpath = NewsServices::saveBase64Image($imgData, $item['title'], $item['title'] . rand(1, 100));
$content = str_replace($imgData, $fullpath, $content);
}
}
}
$item['content'] = $content;
$object->getLocalizedfields()->setLocalizedValue('content', $content, 'vi');
}
}
}
}
private static function coutingTotalComment($object)
{
if($object instanceof Comment){
if($object->getPublished()){
// Lấy id bài viết
$idNews = $object->getCommentObject()->getId();
$comment = new Comment\Listing();
$comment->addConditionParam('commentObject__id = ?',$idNews);
$news = $object->getCommentObject();
//Cộng thêm số comment
$totalComment= $comment->count();
$news->setTotalComment($totalComment);
$news->save();
}
}
}
public function postDelete(DataObjectEvent $e)
{
$object = $e->getObject();
if($object instanceof Comment){
if($object->getCommentObject()){
$news = $object->getCommentObject();
//Trừ thêm số comment
if($news->getTotalComment()||$news->getTotalComment() > 0){
$totalComment= $news->getTotalComment()-1;
$news->setTotalComment($totalComment);
}else{
$news->setTotalComment(0);
}
$news->save();
}
}
}
}