'Url is in wrong format', self::INVALID_ID => 'Wrong video id', ]; /** * Pattern for youtube url validation * @link http://stackoverflow.com/questions/2964678/jquery-youtube-url-validation-with-regex * @var string */ protected $_pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/'; /** * Url pattern used to validate videoId * @var string */ protected $_dataUrlPattern = 'https://www.googleapis.com/youtube/v3/videos?id=%s&key=%s&part=snippet'; public function __construct(array $options = []) { if (isset($options['messages'])) { $this->setMessages($options['messages']); } } protected function _validateVideoId($videoId) { if (!($apiKey = $this->getConfig('apiKey'))) { throw new Exception('YouTube API Key is not defined'); } $url = sprintf($this->_dataUrlPattern, $videoId, $apiKey); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $response = curl_exec($ch); $response = (200 == ($code = curl_getinfo($ch, CURLINFO_HTTP_CODE))) ? $response : null; curl_close($ch); if ($response) { $data = json_decode($response, true); if (is_array($data) && !empty($data['items'])) { return true; } } return false; } /** * Returns true if and only if $value meets the validation requirements * * If $value fails validation, then this method returns false, and * getMessages() will return an array of messages that explain why the * validation failed. * * @param mixed $value * * @return boolean * @throws Zend_Validate_Exception If validation of $value is impossible */ public function isValid($value) { $value = (string) $value; $this->_setValue($value); if (false == preg_match($this->_pattern, $value, $match)) { $this->_error(self::INVALID); return false; } if($this->_validateVideoId) { if (false == $this->_validateVideoId($match[1])) { $this->_error(self::INVALID_ID); return false; } } return true; } }