<?php


class Dalten_Export_Helper_YoutubeIdExtractor
{
    /**
     * Získá youtube id z youtube url.
     *
     * Pokud url není na youtube, vrátí prázdný string.
     *
     * @param mixed $url
     *
     * @return string
     */
    public static function extractYoutubeId($url) {
        if (empty($url) || !is_string($url)) {
            return '';
        }
        $parsedURL = parse_url($url);
        if (isset($parsedURL['host']) && 'youtu.be' == $parsedURL['host']) {
            $matches = [];
            preg_match('~/(.*)~', $parsedURL['path'], $matches);
            if (!empty($matches[1])) {
                return $matches[1];
            }
        } elseif ('www.youtube.com' == $parsedURL['host'] || 'youtube.com' == $parsedURL['host']) {
            $parameters = [];
            $matches = [];
            if (preg_match('~/shorts/([\w-]+)~', $parsedURL['path'], $matches)==1) {
                return $matches[1];
            } elseif (isset($parsedURL['query'])) {
                parse_str($parsedURL['query'], $parameters);
                if (!empty($parameters['v'])) {
                    return $parameters['v'];
                }
            }
        }

        return '';
    }
}
