<?php
namespace App\Twig;
use App\Entity\AdvertsCategory;
use App\Entity\Beach;
use App\Entity\ClubsCategory;
use App\Entity\EventsPageFrequencyInstance;
use App\Entity\JobsCategory;
use App\Entity\NewsCategory;
use App\Entity\Pages\ClubsPage;
use App\Entity\Pages\EventsPage;
use App\Repository\ClubsPageRepository;
use App\Repository\EventsPageFrequencyInstanceRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
class GcsExtension extends AbstractExtension
{
/** @var EntityManagerInterface $em */
private $em;
/**
* @var RouterInterface
*/
private $router;
/**
* ArticleTwigExtension constructor.
*
* @param EntityManagerInterface $em
* @param RouterInterface $router
*/
public function __construct(EntityManagerInterface $em, RouterInterface $router)
{
$this->em = $em;
$this->router = $router;
if (func_num_args() > 2) {
@trigger_error(
sprintf(
'Passing the "request_stack" service as the third argument in "%s" is deprecated in KunstmaanArticleBundle 5.1 and will be removed in KunstmaanArticleBundle 6.0. Remove the "request_stack" argument from your service definition.',
__METHOD__
),
E_USER_DEPRECATED
);
}
}
public function getFunctions()
{
return [
new TwigFunction('get_nearest_event_date', [$this, 'getNearestEventDate']),
new TwigFunction('get_default_article_image', [$this, 'getDefaultArticleImage']),
new TwigFunction('check_for_clubs_from_category', [$this, 'checkForClubsFromCategory']),
new TwigFunction('get_news_from_categories', [$this, 'getNewsFromCategories']),
new TwigFunction('get_adverts_from_categories', [$this, 'getAdvertsFromCategories']),
new TwigFunction('get_jobs_from_categories', [$this, 'getJobsFromCategories']),
new TwigFunction('get_events_sport_categories', [$this, 'getEventsSportCategories']),
new TwigFunction('get_beaches', [$this, 'getBeaches']),
new TwigFunction(
'get_article_tag_path', array($this, 'getArticleTagRouterPath')
),
new TwigFunction(
'get_article_category_path', array($this, 'getArticleCategoryRouterPath')
),
new TwigFunction(
'get_article_categories', array($this, 'getCategories')
),
new TwigFunction(
'get_article_tags', array($this, 'getTags')
),
new TwigFunction('asset_timestamp', [$this, 'getAssetTimestamp']),
];
}
public function getFilters()
{
return [
new TwigFilter('remove_script_tags', [$this, 'removeScriptTags'])
];
}
public function removeScriptTags(?string $content = null): string
{
if (!is_string($content)) {
return "";
}
return preg_replace('#<script(.*?)>(.*?)</script>#is', '', $content);
}
public function getDefaultArticleImage()
{
return '/frontend/img/general/default-article.jpg';
}
public function getNearestEventDate(EventsPage $eventsPage)
{
$nearestDate = $eventsPage->getStartDate();
/**
* @var EventsPageFrequencyInstanceRepository $pageInsRepository
*/
$pageInsRepository = $this->em->getRepository(EventsPageFrequencyInstance::class);
$instance = $pageInsRepository->findClosestForEvent($eventsPage);
if ($instance) {
return $instance->getDate();
}
/*$now = new \DateTime("now");
$dateRange = new \DatePeriod(
$eventsPage->getStartDate(),
$eventsPage->getDateFrequency(),
$eventsPage->getEndDate()
);
foreach ($dateRange as $date) {
if ($date < $now) {
continue;
}
return $date;
break;
}*/
return $nearestDate;
}
private function find_closest($array, \DateTimeInterface $date)
{
//$count = 0;
foreach ($array as $day) {
//$interval[$count] = abs(strtotime($date) - strtotime($day));
$interval[] = abs($date->getTimestamp() - $day->getTimestamp());
//$count++;
}
asort($interval);
$closest = key($interval);
return $array[$closest];
}
public function getNewsFromCategories($categories, $lang = 'pl', $limit = null)
{
$em = $this->em;
$pageRepository = $em->getRepository('App:Pages\NewsPage');
$categoriesArray = null;
/** @var NewsCategory $category */
foreach ($categories as $category) {
$categoriesArray[] = $category->getId();
}
return $pageRepository->getArticles($lang, null, $limit, $categoriesArray, null, false);
}
public function checkForClubsFromCategory(ClubsCategory $category, $lang = 'pl')
{
$em = $this->em;
/** @var ClubsPageRepository $pageRepository */
$pageRepository = $em->getRepository(ClubsPage::class);
$categoriesArray = null;
/** @var NewsCategory $category */
$categoriesArray[] = $category->getId();
return $pageRepository->getArticles($lang, null, null, $categoriesArray);
}
public function getAdvertsFromCategories($categories, $lang = 'pl', $limit = null)
{
$em = $this->em;
$pageRepository = $em->getRepository('App:Pages\AdvertsPage');
$categoriesArray = null;
/** @var AdvertsCategory $category */
foreach ($categories as $category) {
$categoriesArray[] = $category->getId();
}
return $pageRepository->getArticles($lang, null, $limit, $categoriesArray);
}
public function getJobsFromCategories($categories, $lang = 'pl', $limit = null)
{
$em = $this->em;
$pageRepository = $em->getRepository('App:Pages\JobsPage');
$categoriesArray = null;
/** @var JobsCategory $category */
foreach ($categories as $category) {
$categoriesArray[] = $category->getId();
}
return $pageRepository->getArticles($lang, null, $limit, $categoriesArray);
}
public function getEventsSportCategories()
{
$em = $this->em;
$pageRepository = $em->getRepository('App:Pages\EventsPage');
return $pageRepository->getDistinctValues('sports');
}
/**
* Get tags array for view.
*
* @param Request $request
* @param string $className
*
* @return array
*/
public function getTags(Request $request, $className)
{
$context = array();
$tagRepository = $this->em->getRepository($className);
$context['tags'] = $tagRepository->findBy(array(), array('name' => 'ASC'));
$searchTag = $request->get('tag') ? explode(',', $request->get('tag')) : null;
if ($searchTag) {
$context['activeTag'] = true;
$context['activeTags'] = $searchTag;
}
return $context;
}
/**
* Get categories array for view.
*
* @param Request $request
* @param string $className
*
* @return array
*/
public function getCategories(Request $request, $className)
{
$context = array();
$categoryRepository = $this->em->getRepository($className);
$context['categories'] = $categoryRepository->findBy(array(), array('name' => 'ASC'));
$searchCategory = $request->get('category') ? explode(',', $request->get('category')) : null;
if ($searchCategory) {
$context['activeCategory'] = true;
$context['activeCategories'] = $searchCategory;
}
return $context;
}
/**
* @param string $slug
* @param string $tag
* @param string $locale
* @param array $parameters
* @param int $referenceType
*
* @return string
*/
public function getArticleTagRouterPath(
$slug,
$tag,
$locale,
$parameters = [],
$referenceType = UrlGeneratorInterface::ABSOLUTE_PATH
)
{
$routeName = sprintf('_slug_tag_%s', $locale);
return $this->getArticleRouterPath($routeName, 'tag', $slug, $tag, $locale, $parameters, $referenceType);
}
/**
* @param string $slug
* @param string $category
* @param string $locale
* @param array $parameters
* @param int $referenceType
*
* @return string
*/
public function getArticleCategoryRouterPath(
$slug,
$category,
$locale,
$parameters = [],
$referenceType = UrlGeneratorInterface::ABSOLUTE_PATH
)
{
$routeName = sprintf('_slug_category_%s', $locale);
return $this->getArticleRouterPath(
$routeName,
'category',
$slug,
$category,
$locale,
$parameters,
$referenceType
);
}
/**
* @return string
*/
public function getName()
{
return 'article_twig_extension';
}
/**
* @param string $routeName
* @param string $type
* @param string $slug
* @param string $tagOrCategory
* @param string $locale
* @param array $parameters
* @param int $referenceType
*
* @return string
*/
protected function getArticleRouterPath(
$routeName,
$type,
$slug,
$tagOrCategory,
$locale,
$parameters = [],
$referenceType = UrlGeneratorInterface::ABSOLUTE_PATH
)
{
if (!$this->articleRouteExists($type, $locale)) {
$routeName = '_slug';
}
if (!isset($parameters[$type])) {
$parameters[$type] = $tagOrCategory;
}
if (!isset($parameters['url'])) {
$parameters['url'] = $slug;
}
if (!isset($parameters['_locale'])) {
$parameters['_locale'] = $locale;
}
return $this->router->generate($routeName, $parameters, $referenceType);
}
/**
* @param string $type
* @param string $locale
*
* @return bool
*/
protected function articleRouteExists($type, $locale)
{
$routeName = sprintf('_slug_%s_%s', $type, $locale);
try {
return !is_null($this->router->getRouteCollection()->get($routeName));
} catch (\Exception $e) {
return false;
}
}
public function getBeaches()
{
$beachRepo = $this->em->getRepository(Beach::class);
$beaches = $beachRepo->findAll();
return $beaches;
}
public function getAssetTimestamp(string $path): int
{
try {
return filemtime(ltrim($path, '/')) ?: 0;
} catch (\Exception $exception) {
return 0;
}
}
}