You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.5 KiB

<?php
namespace Grav\Plugin\Shortcodes;
use Thunder\Shortcode\Shortcode\ShortcodeInterface;
class YTShortcode extends Shortcode
{
const YOUTUBE_REGEX = '/(?:https?:\/{2}(?:(?:www.youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=))|(?:youtu\.be\/)))((?:videoseries\?list=[a-zA-Z0-9_-]{34})|[a-zA-Z0-9_-]{11})/';
public function init()
{
$this->shortcode->getHandlers()->add('yt', function(ShortcodeInterface $sc) {
// Get shortcode content and parameters
$url = $sc->getContent();
$params = $sc->getParameters();
$privacy_mode = $sc->getParameter('privacy_enhanced_mode');
if ($url) {
preg_match($this::YOUTUBE_REGEX, $url, $matches);
$search = $matches[0];
// double check to make sure we found a valid YouTube video ID
if (!isset($matches[1])) {
return $search;
}
/** @var Twig $twig */
$twig = $this->grav['twig'];
// build the replacement embed HTML string
$replace = $twig->processTemplate('partials/yt.html.twig', array(
'player_parameters' => $params,
'privacy_enhanced_mode' => $privacy_mode,
'video_id' => $matches[1],
));
// do the replacement
return str_replace($search, $replace, $search);
}
});
}
}