<?php
namespace App\Controller;
use App\Entity\Article;
use App\Entity\Card;
use App\Entity\CardItem;
use App\Entity\Category;
use App\Entity\Channel;
use App\Entity\Comment;
use App\Entity\Media;
use App\Entity\StaticPage;
use App\Entity\StripeProduct;
use App\Entity\User;
use App\Form\RegisterType;
use App\Service\ArticleEntityService;
use App\Service\CaptchaService;
use App\Service\CartService;
use App\Service\FavoriteService;
use App\Service\LikesService;
use App\Service\MediaEntityService;
use App\Service\PlatformService;
use App\Service\StaticPageBlockEntityService;
use App\Service\StorageService;
use App\Service\StripeService;
use App\Service\UserService;
use Bluesquare\ValidatorBundle\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class MainController extends AbstractController
{
private KernelInterface $appKernel;
protected MediaEntityService $mediaEntityService;
private ParameterBagInterface $parameterBag;
// constructor injection
public function __construct(
KernelInterface $appKernel,
MediaEntityService $mediaEntityService,
ParameterBagInterface $parameterBag
){
$this->appKernel = $appKernel;
$this->mediaEntityService = $mediaEntityService;
$this->parameterBag = $parameterBag;
}
/**
* @Route("/", name="home")
*/
public function index(EntityManagerInterface $manager, StaticPageBlockEntityService $staticPageBlockEntityService)
{
$channel = $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
if ($channel instanceof Channel) {
$homepage = $channel->getHomepage();
if ($homepage instanceof StaticPage) {
$structure = $this->getStaticPageStructure($homepage, $staticPageBlockEntityService);
return $this->render('static_page/static_page.html.twig', [
'page' => $homepage,
'blocks' => $structure['blocks'],
'block_header' => $structure['block_header'],
'homepage_static_page' => true,
]);
}
return $this->redirectToRoute('homepage');
}
throw $this->createNotFoundException();
}
/**
* @Route("/home/{page}", name="homepage",defaults={"page"=1})
* @throws \Exception
*/
public function home(
Request $request,
Validator $validator,
ArticleEntityService $articleService,
EntityManagerInterface $manager,
StripeService $stripeService,
$page
): ?Response
{
$channel = $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
if (!$channel) {
throw $this->createNotFoundException();
}
if ($request->isXmlHttpRequest()) {
$articlesHomepage=$manager->getRepository(Article::class)->getLiveArticlesRefonte($channel,8,$page*3);
$articlesHomepage = $articleService->formatAll($articlesHomepage);
return $this->render('home/recent-articles-more.html.twig', [
'page' => $page,
'articles' => $articlesHomepage,
]);
}
/* @var User $user */
$user = $this->getUser();
$user_subscriptions = $user ? $stripeService->getUserSubscriptions($user) : [];
$subscription_status = false;
if (!empty($user_subscriptions)) {
// Check if user has an active subscription
foreach ($user_subscriptions as $user_subscription) {
if ('active' === $user_subscription->getStatus()) {
$subscription_status = true;
break;
}
}
}
return $this->render('home/home.html.twig', [
'validator' => $validator,
'user' => $user,
'userSubscriptionsStatus' => $subscription_status,
'page' => $page,
]);
}
/**
* @Route("/static/banner.jpg", name="static.platform.banner")
*/
public function banner(PlatformService $platformService)
{
$banner = $platformService->getImagePath('banner.jpg', $platformService->getRoot().'/public/assets/images/default/banner.jpg');
header('content-type: image/jpeg');
header('Pragma: public');
header('Cache-Control: must-revalidate');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $platformService->getConfig(true)['images.last_update']).' GMT');
echo file_get_contents($banner);
exit;
}
/**
* @Route("/static/logo.png", name="static.platform.logo")
*/
public function logo(PlatformService $platformService)
{
$logo = $platformService->getImagePath('logo.png', $platformService->getRoot().'/public/assets/images/default/logo_transparent.jpg');
header('content-type: image/png');
header('Pragma: public');
header('Cache-Control: must-revalidate');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $platformService->getConfig(true)['images.last_update']).' GMT');
echo file_get_contents($logo);
exit;
}
/**
* @Route("/static/favicon.png", name="static.platform.favicon")
*/
public function favicon(PlatformService $platformService)
{
$favicon = $platformService->getImagePath('favicon.png', $platformService->getRoot().'/public/assets/images/default/favicon.png');
header('content-type: image/png');
header('Pragma: public');
header('Cache-Control: must-revalidate');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $platformService->getConfig(true)['images.last_update']).' GMT');
echo file_get_contents($favicon);
exit;
}
/**
* @Route("/rss", name="rss", defaults={"_format"="xml"})
*/
public function rss(ArticleEntityService $articleService, EntityManagerInterface $em, MediaEntityService $entityService): Response
{
$articles_array = [];
$articleRepository = $this->getDoctrine()->getRepository(Article::class);
$articles = $articleRepository->getLiveArticles(null, 50);
$projectDir = $this->appKernel->getProjectDir();
$tempDir = $projectDir . '/var/temp';
if (!is_dir($tempDir)) {
@mkdir($tempDir, 0755, true);
}
foreach ($articles as $article) {
$cover = $article->getCover();
// If cover exists but no thumbnail, try to download and generate one
if ($cover && !$cover->getThumbnail()) {
$entity = $em->getRepository(Media::class)->find($cover->getId());
if (!$entity) {
$entity = new Media();
$entity->setType($cover->getType());
$entity->setLabel($cover->getLabel());
$em->persist($entity);
$em->flush();
}
$type = $cover->getType() ?? 'image/jpeg';
$parts = explode('/', $type);
$extension = $parts[1] ?? 'jpg';
$file = $tempDir . '/' . uniqid('article_' . $article->getId() . '_') . '.' . $extension;
// build remote path
$storageUrlFront = $this->getParameter('storage_url_front');
$storagePathFront = $this->parameterBag->has('storage_path') ? $this->getParameter('storage_path_front') : null;
if ($storagePathFront) {
$path = rtrim($storageUrlFront, '/') . '/' . trim($storagePathFront, '/') . '/media/' . $cover->getFile();
} else {
$path = rtrim($storageUrlFront, '/') . '/media/' . $cover->getFile();
}
try {
$content = @file_get_contents($path);
if ($content === false) {
// cannot fetch remote file
@unlink($file);
continue;
}
file_put_contents($file, $content);
} catch (\Throwable $e) {
@unlink($file);
continue;
}
try {
$uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile(
$file,
basename($file),
mime_content_type($file) ?: $type,
null,
true
);
$entityService->postValidateThumbnail($entity, $uploadedFile);
$em->persist($entity);
$article->setCover($entity);
$em->persist($article);
$em->flush();
} catch (\Throwable $e) {
// ignore errors for a single article and continue
} finally {
@unlink($file);
}
}
// If article has a usable thumbnail, verify it and add to the list
if ($article->getCover() !== null && $article->getCover()->getThumbnail() !== null) {
$thumbnail = $article->getCover()->getThumbnail();
$folder = '/media_thumbnail/';
if ($article->getCover()->getWpThumbnail()) {
$thumbnail = $article->getCover()->getWpThumbnail();
$folder = '/media_thumbnail_wp/';
}
if ($this->parameterBag->has('storage_path')) {
$path = rtrim($this->getParameter('storage_url'), '/') . '/' . trim($this->getParameter('storage_path'), '/') . $folder . $thumbnail;
} else {
$path = rtrim($this->getParameter('storage_url'), '/') . $folder . $thumbnail;
}
if ($this->mediaEntityService->isMediaWorking($path)) {
$articles_array[] = $article;
}
// else skip article
} elseif ($article->getCover() === null) {
// no cover - include article
$articles_array[] = $article;
}
}
$articles = $articleService->formatAll($articles_array);
return $this->render('rss.xml.twig', [
'articles' => $articles,
]);
}
/**
* @Route("/rss/{slug}.xml", name="rss.slug", defaults={"_format"="xml"})
*/
public function rssBySlug(ArticleEntityService $articleService, EntityManagerInterface $em, MediaEntityService $entityService, $slug): Response
{
// slug currently unused; reuse main rss logic
return $this->rss($articleService, $em, $entityService);
}
/**
* @Route("/moneyTizerDirectCode", name="moneyTizerDirectCode")
*/
public function moneyTizerDirectCode(): Response
{
return $this->render('article/moneyTizerDirectCode.html.twig');
}
/**
* @Route("/sitemap.xml", name="sitemap", defaults={"_format"="xml"})
*/
public function sitemap(ArticleEntityService $articleEntityService)
{
$urlCategories = [];
$articleRepository = $this->getDoctrine()->getRepository(Article::class);
$categoryRepository = $this->getDoctrine()->getRepository(Category::class);
$articles = $articleEntityService->formatAll($articleRepository->getLiveArticles(null, 50));
$appurl = $this->parameterBag->get('app_url');
$categories = $categoryRepository->getCategories_all();
foreach ($categories as $category) {
$urlCategories[] = $appurl.$this->generateUrl('category.view', ['slug' => $category->getSlug()]);
}
$dailyChanges=[
$appurl.$this->generateUrl('homepage'),
$appurl.$this->generateUrl('articleLive'),
];
$urls=[
$appurl.$this->generateUrl('homepage'),
$appurl.$this->generateUrl('articleLive'),
$appurl. $this->generateUrl('video-podcast'),
$appurl. $this->generateUrl('offer.index'),
$appurl. $this->generateUrl('contact.form'),
$appurl. $this->generateUrl('auth.login'),
$appurl. $this->generateUrl('articles.recherche.view'),
$appurl."/page/abonnements",
$appurl."/page/mentions-legales",
];
$urls = array_merge($urls, $urlCategories);
return $this->render('sitemaps/sitemap.xml.twig', [
'articles' => $articles,
'urls' => $urls,
'dailyChanges' => $dailyChanges,
'urlCategories' => $urlCategories,
]);
}
/**
* @Route("/sitemap-images.xml", name="sitemap_images", defaults={"_format"="xml"})
*/
public function sitemapImages(ArticleEntityService $articleEntityService)
{
$articleRepository = $this->getDoctrine()->getRepository(Article::class);
$articles = $articleEntityService->formatAll($articleRepository->getLiveArticles(null, 50));
return $this->render('sitemaps/sitemap-images.xml.twig', [
'articles' => $articles,
]);
}
/**
* @Route("/sitemap-news.xml", name="sitemap_news", defaults={"_format"="xml"})
*/
public function sitemapNews(ArticleEntityService $articleEntityService)
{
$articleRepository = $this->getDoctrine()->getRepository(Article::class);
$articles = $articleEntityService->formatAll($articleRepository->getLiveArticles(null, 50));
return $this->render('sitemaps/sitemap-news.xml.twig', [
'articles' => $articles,
]);
}
/**
* @Route("/robots.txt", name="robots", defaults={"_format"="txt"})
*/
public function robots()
{
return $this->render('robots.txt.twig');
}
/**
* @Route("/_captcha", name="captcha")
*/
public function captcha(CaptchaService $captchaService)
{
return $this->json($captchaService->generate());
}
protected function getStaticPageStructure(StaticPage $page, StaticPageBlockEntityService $blockEntityService)
{
$blocks = $blockEntityService->index($page);
usort($blocks, function ($a, $b) {
return $a['position'] - $b['position'];
});
// BLOCK_HEADER sorting
$header = null;
$types = array_column($blocks, 'type');
if (\in_array('STATIC_PAGE_BLOCK_HEADER', $types, true)) {
$header_key = array_search('STATIC_PAGE_BLOCK_HEADER', $types, true);
$header = $blocks[$header_key]; // Retrieve BLOCK_HEADER
unset($blocks[$header_key]); // Remove it from the $blocks array
$blocks = array_values($blocks); // Redindexing array
// Get children
$parent_id = $header['id'];
$ids = array_column($blocks, 'id');
$header_children_media = [];
foreach ($blocks as $block) {
if ($block['parent'] === $parent_id && 'STATIC_PAGE_BLOCK_MEDIA' === $block['type']) {
$child_id = $block['id'];
$child_key = array_search($child_id, $ids, true);
unset($blocks[$child_key]); // Remove child from $blocks array
$header_children_media[] = $block['media']['file']; // Retrieve BLOCK_HEADER's media children
}
}
$header['media'] = $header_children_media;
}
$blocks = array_map(function ($block) {
$block['data'] = @json_decode($block['data'], true);
if (!\is_array($block['data'])) {
$block['data'] = [];
}
return $block;
}, $blocks);
return [
'blocks' => $blocks,
'block_header' => $header,
];
}
/**
* @Route("/ads-txt-smilewanted-2021.txt", name="ads-txt-smilewanted-2021.txt", methods={"GET"})
* @Cache(expires="+1 day", public=true)
*/
public function adText(PlatformService $platformService)
{
if ('aircosmos' !== $this->getParameter('app_slug')) {
return new Response("Vous n'êtes pas sur Air&Cosmos");
}
$txt = file_get_contents($platformService->getRoot().'/public/assets/smileWanted/ads-txt-smilewanted-2021.txt');
$response = new Response(json_encode($txt));
$response->headers->set('Content-Type', 'text/plain');
$response->sendHeaders();
return $response;
}
/**
* @Route("/ads.txt", name="ads.txt", methods={"GET"})
*/
public function adsText(PlatformService $platformService, StorageService $storageService)
{
if ('aircosmos' !== $this->getParameter('app_slug')) {
return new Response("Vous n'êtes pas sur Air&Cosmos", 404);
}
$localFilePath = $this->appKernel->getProjectDir().'/var/data/ads.txt';
if (file_exists($localFilePath)) {
@unlink($localFilePath);
}
$storageService->retrieve('platform/ads.txt', $localFilePath);
$txt = file_get_contents($this->appKernel->getProjectDir().'/var/data/ads.txt');
$ads_txt_themoneytizer = file_get_contents('https://www.themoneytizer.com/ads.txt?id=85376');
if (empty($ads_txt_themoneytizer)) {
$ch = curl_init();
curl_setopt($ch, \CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, \CURLOPT_URL, 'https://www.themoneytizer.com/ads.txt?id=85376');
$ads_txt_themoneytizer = curl_exec($ch);
curl_close($ch);
}
$txt = $txt."\n".$ads_txt_themoneytizer;
$response = new Response($txt);
$response->headers->set('Content-Type', 'text/plain');
$response->sendHeaders();
return $response;
}
/**
* @Route("/forgot-pwd-modal", name="forgot-pwd-modal")
*/
public function forgot_pwd_modal(): Response
{
$builder = $this->createFormBuilder()
->add('email', EmailType::class, [
'constraints' => [
new NotBlank(),
new Email(),
],
]);
$form = $builder->getForm();
return $this->render('_partials/login/forgot_password_modal.html.twig', ['form' => $form->createView()]);
}
/**
* @Route("/login-modal", name="login-modal")
*/
public function login_modal(Request $request): Response
{
$builder = $this->createFormBuilder()
->add('email', EmailType::class, [
'constraints' => [
new NotBlank(),
new Email(),
],
'attr' => [
'class' => 'auth-form-input',
],
])
->add('password', PasswordType::class, [
'constraints' => [
new NotBlank(),
],
'attr' => [
'class' => 'auth-form-input',
],
])
// ->add('recaptcha', EWZRecaptchaV3Type::class, [
// 'action_name' => 'auth_register',
// 'mapped' => false,
// 'constraints' => [
// new IsTrueV3(),
// ],
// ])
;
$form = $builder->getForm();
return $this->render('_partials/login/login-modal.html.twig', ['form' => $form->createView()]);
}
/**
* @Route("/auth/creation-compte", name="creation-compte")
*/
public function register_modal(Request $request, UserService $userService, EntityManagerInterface $entityManager, MailerInterface $symfonyMailer,ValidatorInterface $validator)
{
$user = new User();
$form = $this->createForm(RegisterType::class, $user);
$form->handleRequest($request);
if ($request->isXmlHttpRequest()) {
$data = json_decode($request->getContent());
$email = $data->email;
$violations = $validator->validate($email, [
new Assert\NotBlank(),
new Assert\Email(),
]);
$user_exist = $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
if ($user_exist ) {
return $this->json(['errors' => 'error','motif'=>'exist'], 500);
} if ( 0 !== \count($violations)) {
return $this->json(['errors' => 'error','motif'=>'invalid'], 500);
}
return $this->json(['success' => 'ok'], 200);
}
$sender = $this->getParameter('mailer_from_address');
if ($form->isSubmitted() && $form->isValid()) {
$email = $form->get('email')->getData();
$user_exist = $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
if ($this->hasNumbers($form->getData()->getFirstname()) && $this->hasNumbers($form->getData()->getLastname())) {
$this->addFlash('error', 'les données ne sont pas valides');
return $this->render('_partials/register/register-confirm.html.twig', [
'form' => $form->createView(), 'email' => $email,
]);
} else {
if (!$user_exist) {
$user = $userService->createUser_new($form->getData());
$userService->sendActivationEmail($user, $sender, $symfonyMailer);
$session = $request->getSession();
$price_id = $session->get('price_id');
if ($price_id && $user->getActivatedAt()) {
return $this->redirectToRoute('products.details', ['price_id' => $price_id]);
}
$article_id = $session->get('article_id');
$article_slug = $session->get('article_slug');
if ($article_id && $article_slug && $user->getActivatedAt()) {
return $this->redirectToRoute('article.view', ['id' => $article_id, 'slug' => $article_slug]);
}
return $this->render('_partials/register/register-confirm.html.twig', [
'form' => $form->createView(), 'email' => $email,
]);
}
}
return $this->redirectToRoute('homepage');
}
return $this->render('_partials/register/register-modal.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/resend-email/{email}", name="resend-email")
*/
public function resend_email($email, UserService $userService, EntityManagerInterface $manager , MailerInterface $symfonyMailer)
{
$sender = $this->getParameter('mailer_from_address');
$user = $manager->getRepository(User::class)->findOneBy(['email' => $email]);
$userService->sendActivationEmail($user, $sender, $symfonyMailer);
return $this->render('_partials/register/register-confirm.html.twig', [
'email' => $email,
]);
}
/**
* @Route("/like-comment", name="like-comment")
*/
public function like_comment(Request $request, LikesService $likesService, EntityManagerInterface $manager)
{
$user = $this->getUser();
if ($request->isXmlHttpRequest()) {
$data = json_decode($request->getContent());
$comment = $manager->getRepository(Comment::class)->findOneBy(['id' => $data->data]);
if ($comment->isLikedByUser($user)) {
$likesService->dislike($user, $comment);
return $this->json(['count' => \count($comment->getCommentLikes())], 200);
}
$likesService->like($user, $comment);
return $this->json(['count' => \count($comment->getCommentLikes())], 200);
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/add-cart", name="add-cart")
*/
public function add_to_cart(Request $request, CartService $cartService, EntityManagerInterface $manager)
{
$user = $this->getUser();
if ($request->isXmlHttpRequest()) {
if ($user) {
$data = json_decode($request->getContent());
$product = $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $data->data]);
if ($product) {
$cartService->addProductToCart($user, $product);
return $this->json(['success' => 'ok'], 200);
}
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/add-cart/{stripe_id}", name="add-to-cart")
*/
public function addProductToCart(Request $request, CartService $cartService, EntityManagerInterface $manager, $stripe_id)
{
/** @var User $user */
$user = $this->getUser();
if ($request->isXmlHttpRequest()) {
$product = $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $stripe_id]);
if ($user && $product) {
$cartService->addProductToCart($user, $product);
return $this->json(['success' => 'ok'], 200);
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/add-favorites", name="add-favorites")
*/
public function add_to_favorites(Request $request, FavoriteService $favoriteService, EntityManagerInterface $manager)
{
/** @var User $user */
$user = $this->getUser();
$productiD = $request->get('product');
$product = $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $productiD]);
if ($request->isXmlHttpRequest()) {
if ($product && $user) {
$favoriteService->addProductToFavorite($user, $product);
return $this->json(['success' => 'ok', 'action' => 'add'], 200);
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/remove-from-favorites", name="remove-from-favorites")
*/
public function remove_from_favorites(Request $request, FavoriteService $favoriteService, EntityManagerInterface $manager)
{
/** @var User $user */
$user = $this->getUser();
$productiD = $request->get('product');
$product = $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $productiD]);
if ($request->isXmlHttpRequest()) {
if ($product && $user) {
$favoriteService->removeProductFromFavorite($user, $product);
return $this->json(['success' => 'ok', 'action' => 'remove'], 200);
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/remove-from-cart", name="remove-from-cart")
*/
public function remove_from_cart(Request $request, EntityManagerInterface $manager):Response
{
/** @var User $user */
$user = $this->getUser();
$productiD = $request->get('product');
$product = $manager->getRepository(StripeProduct::class)->findOneBy(['stripe_id' => $productiD]);
$id = $product->getId();
if ($request->isXmlHttpRequest()) {
if ($product && $user) {
$itemID = $manager->getRepository(Card::class)->findCardItem($user , $id);
$item = $manager->getRepository(CardItem::class)->findOneBy(['id' => $itemID[0]['id']]);
$quantity = $item->getQuantity();
$manager->remove($item);
$manager->flush();
return $this->json([
'success' => 'ok',
'action' => 'remove',
'quantity' => $quantity
], 200);
}
}
return new Response("ok");
}
/**
* @Route("/add-article-favorites", name="add-article-favorites")
*/
public function add_article_to_favorites(Request $request, FavoriteService $favoriteService, EntityManagerInterface $manager)
{
if ($request->isXmlHttpRequest()) {
$articleId = $request->get('article');
$article = $articleId ? $manager->getRepository(Article::class)->find($articleId): null;
if ($article) {
/** @var User $user */
$user = $this->getUser();
$favoriteService->addArticleToFavorite($user, $article);
return $this->json(['success' => 'ok', 'action' => 'add'], 200);
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/remove-article-from-favorites", name="remove-article-from-favorites")
*/
public function remove_article_from_favorites(Request $request, FavoriteService $favoriteService, EntityManagerInterface $manager)
{
if ($request->isXmlHttpRequest()) {
$articleId = $request->get('article');
$article = $articleId ? $manager->getRepository(Article::class)->find($articleId): null;
if ($article) {
/** @var User $user */
$user = $this->getUser();
$favoriteService->removeArticleFromFavorite($user, $article);
return $this->json(['success' => 'ok', 'action' => 'remove'], 200);
}
}
return $this->redirectToRoute('homepage');
}
// public function defaultThumbnail($articles, $container, $em, $entityService, $temp_dir)
// {
// foreach ($articles as $article) {
// if(!$article->getCover()->getThumbnail()){
// $a=$container->get('kernel')->getProjectDir()."/public/assets/images/theme-5/air_cosmos.jpg";
// $entityD=$em->getRepository(Media::class)->find($article->getCover()->getId());
// $fileD=$temp_dir."/".rand(0,999)."--defaultThumbail.jpg";
//
// $content = file_get_contents($a);
// file_put_contents($fileD, $content);
// $uploadedFileD = new \Symfony\Component\HttpFoundation\File\UploadedFile(
// $fileD,
// basename($fileD),
// mime_content_type($fileD),
// filesize($fileD),
// false,
// true
// );
//
// $entityService->postValidateThumbnailDefault($entityD, $uploadedFileD);
// $em->persist($entityD);
// $article->setCover($entityD);
// $em->persist($article);
// $em->flush();
// @unlink($fileD);
// }
// }
// }
private function hasNumbers($str) {
return preg_match('/\d/', $str) === 1;
}
}