YoutubeShortcode.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace Grav\Plugin\Shortcodes;
  3. use Thunder\Shortcode\Shortcode\ShortcodeInterface;
  4. class YoutubeShortcode extends Shortcode
  5. {
  6. const YOUTUBE_REGEX = '/(?:https?:\/{2}(?:(?:www.youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=))|(?:youtu\.be\/)))([a-zA-Z0-9_-]{11})/';
  7. public function init()
  8. {
  9. $this->shortcode->getHandlers()->add('youtube', function(ShortcodeInterface $sc) {
  10. // Get shortcode content and parameters
  11. $url = $sc->getContent();
  12. $params = $sc->getParameters();
  13. $privacy_mode = $sc->getParameter('privacy_enhanced_mode');
  14. if ($url) {
  15. preg_match($this::YOUTUBE_REGEX, $url, $matches);
  16. $search = $matches[0];
  17. // double check to make sure we found a valid YouTube video ID
  18. if (!isset($matches[1])) {
  19. return $search;
  20. }
  21. /** @var Twig $twig */
  22. $twig = $this->grav['twig'];
  23. // build the replacement embed HTML string
  24. $replace = $twig->processTemplate('partials/youtube.html.twig', array(
  25. 'player_parameters' => $params,
  26. 'privacy_enhanced_mode' => $privacy_mode,
  27. 'video_id' => $matches[1],
  28. ));
  29. // do the replacement
  30. return str_replace($search, $replace, $search);
  31. }
  32. });
  33. }
  34. }