FeedService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Article;
  4. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  5. use App\Repository\ArticleRepository;
  6. use Laminas\Feed\Writer\Entry;
  7. use Laminas\Feed\Writer\Feed;
  8. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  9. use Symfony\Component\Routing\RouterInterface;
  10. class FeedService
  11. {
  12. public const ATOM = 'atom';
  13. public const RSS = 'rss';
  14. public function __construct(
  15. protected ArticleRepository $articleRepository,
  16. protected UrlGeneratorInterface $router,
  17. protected MarkdownParser $markdownParser,
  18. protected ParameterBagInterface $parameterBagInterface
  19. )
  20. {
  21. }
  22. public function createFeed(array $articles, \DateTimeImmutable $updatedAt, string $type = self::RSS): string
  23. {
  24. $feed = new Feed();
  25. $feed->setTitle($this->parameterBagInterface->get('title'));
  26. $feed->setLink($this->router->generate('app_index', [], RouterInterface::ABSOLUTE_URL));
  27. $feed->setFeedLink($this->router->generate('app_feed', ['type' => $type], RouterInterface::ABSOLUTE_URL), $type);
  28. $feed->setDescription('Derniers articles du blog');
  29. $feed->setLanguage('fr');
  30. $feed->setDateModified($updatedAt);
  31. foreach($this->getItems($articles) as $item) {
  32. $feed->addEntry($item);
  33. }
  34. return $feed->export($type);
  35. }
  36. public function getItems($articles): \Iterator
  37. {
  38. foreach($articles as $article) {
  39. /** @var Article $article */
  40. $item = new Entry();
  41. $item
  42. ->setTitle($article->getTitle())
  43. ->setLink($this->router->generate('app_view', ['slug' => $article->getSlug()], RouterInterface::ABSOLUTE_URL))
  44. ->setDateCreated($article->getPublicationDate())
  45. ->setDateModified($item->getDateCreated())
  46. ->addAuthor(['name' => (string) $article->getAuthor()])
  47. ;
  48. $tags = $article->getTags();
  49. foreach($tags as $tag) {
  50. $item->addCategory([
  51. 'term' => (string) $tag->getName(),
  52. 'scheme' => $this->router->generate('app_search', ['tag' => $tag->getName()], RouterInterface::ABSOLUTE_URL)
  53. ]);
  54. }
  55. # Fix pour supprimer le allowfullscreen récupéré par l'extension embed pour youtube
  56. $content = $this->markdownParser->convertToHtml($article->getContent());
  57. $content = str_replace('allowfullscreen', 'allowfullscreen="true"', $content);
  58. $item->setContent($content);
  59. ;
  60. yield $item;
  61. }
  62. }
  63. }