View source
<?php
namespace Drupal\url_to_video_filter\Service;
class UrlToVideoFilterService implements UrlToVideoFilterServiceInterface {
public function convertYouTubeUrls($text) {
$return = [
'text' => $text,
'url_found' => FALSE,
];
$urls = $this
->parseYouTubeUrls($text);
if (count($urls)) {
$return['url_found'] = TRUE;
foreach ($urls as $url) {
$embed_code = $this
->convertYouTubeUrlToEmbedCode($url);
$return['text'] = str_replace($url, $embed_code, $return['text']);
}
}
return $return;
}
public function convertVimeoUrls($text) {
$return = [
'text' => $text,
'url_found' => FALSE,
];
$urls = $this
->parseVimeoUrls($text);
if (count($urls)) {
$return['url_found'] = TRUE;
foreach ($urls as $url) {
$embed_code = $this
->convertVimeoUrlToEmbedCode($url);
$return['text'] = str_replace($url, $embed_code, $return['text']);
}
}
return $return;
}
protected function parseYouTubeUrls($text) {
$urls = [];
$youtube_regex = '/(^|\\b)http(s)?:\\/\\/(www\\.)?youtube\\.com\\/watch.+?(?=($|\\s|\\r|\\r\\n|\\n|<))/m';
preg_match_all($youtube_regex, $text, $matches);
$urls = array_merge($urls, $matches[0]);
$youtube_regex = '/(^|\\b)http(s)?:\\/\\/(www\\.)?youtu\\.be\\/.+?(?=($|\\s|\\r|\\r\\n|\\n|<))/m';
preg_match_all($youtube_regex, $text, $matches);
$urls = array_merge($urls, $matches[0]);
$youtube_regex = '/(^|\\b)http(s)?:\\/\\/(www\\.)?youtube\\.com\\/embed.+?(?=($|\\s|\\r|\\r\\n|\\n|<))/m';
preg_match_all($youtube_regex, $text, $matches);
$urls = array_merge($urls, $matches[0]);
return $urls;
}
protected function convertYouTubeUrlToEmbedCode($url) {
$embed_code = '';
if (strpos($url, 'youtube.com/watch')) {
$video_key = preg_replace('/(http)?(s)?(:\\/\\/)?(www\\.)?youtube\\.com\\/watch\\?v=/', '', $url);
}
elseif (strpos($url, 'youtube.com/embed')) {
$video_key = preg_replace('/(http)?(s)?(:\\/\\/)?(www\\.)?youtube\\.com\\/embed\\//', '', $url);
}
elseif (strpos($url, 'youtu.be')) {
$video_key = preg_replace('/(http)?(s)?(:\\/\\/)?(www\\.)?youtu.be\\//', '', $url);
}
$embed_code .= '<span class="url-to-video-container youtube-container no-js">';
$embed_code .= '<span class="youtube-player url-to-video-player loader" data-youtube-id="' . $video_key . '"></span>';
$embed_code .= '</span>';
return $embed_code;
}
protected function parseVimeoUrls($text) {
$vimeo_regex = '/(^|\\b)http(s)?:\\/\\/(www\\.)?vimeo\\.com.+?(?=($|\\s|\\r|\\r\\n|\\n|<))/m';
preg_match_all($vimeo_regex, $text, $matches);
return $matches[0];
}
protected function convertVimeoUrlToEmbedCode($url) {
$embed_code = '';
$video_key = preg_replace('/(http)?(s)?(:\\/\\/)?(www\\.)?vimeo\\.com\\//', '', $url);
$embed_code .= '<span class="url-to-video-container vimeo-container no-js">';
$embed_code .= '<span class="vimeo-player url-to-video-player loader" data-vimeo-id="' . $video_key . '"></span>';
$embed_code .= '</span>';
return $embed_code;
}
}