Skip to content

Instantly share code, notes, and snippets.

@davidino
Created May 5, 2011 14:10
Show Gist options
  • Select an option

  • Save davidino/957099 to your computer and use it in GitHub Desktop.

Select an option

Save davidino/957099 to your computer and use it in GitHub Desktop.
Youtube Widget & Validator for Symfony
<?php
$urls = array(
'/http:\/\/www.youtube.com\/watch\?v=([a-zA-Z0-9_-]+)([%&=#a-zA-Z0-9_-])*/',
'/http:\/\/www.youtube.com\/watch#\!v=([a-zA-Z0-9_-]+)([%&=#a-zA-Z0-9_-])*/',
'/http:\/\/youtu.be\/([a-zA-Z0-9_-]+)/',
);
$youtube_video_id = preg_replace($urls, '$1', $videoUrl);
<?php
class DavidinoValidatorFormYoutube extends sfValidatorRegex
{
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
$this->addRequiredOption('pattern');
$this->addOption('must_match', true);
$this->addOption('pattern', $this->getPattern());
}
/**
* Returns the current validator's regular expression.
*
* @return string
*/
public function getPattern()
{
$pattern =
'/http:\/\/www.youtube.com\/watch\?v=([a-zA-Z0-9_-]+)([%&=#a-zA-Z0-9_-])*'.
'|http:\/\/www.youtube.com\/watch#\!v=([a-zA-Z0-9_-]+)([%&=#a-zA-Z0-9_-])*'.
'|http:\/\/youtu.be\/([a-zA-Z0-9_-]+)/' ;
return $pattern;
}
}
<?php
class DavidinoWidgetFormYoutube extends sfWidgetFormInputText
{
/**
* Renders the widget.
*
* @param string $name The element name
* @param string $value The value displayed in this widget
* @param array $attributes An array of HTML attributes to be merged with the default HTML attributes
* @param array $errors An array of errors for the field
*
* @return string An HTML tag string
*
* @see sfWidgetForm
*/
public function render($name, $value = null, $attributes = array(), $errors = array())
{
$urls = array(
'/http:\/\/www.youtube.com\/watch\?v=([a-zA-Z0-9_-]+)([%&=#a-zA-Z0-9_-])*/',
'/http:\/\/www.youtube.com\/watch#\!v=([a-zA-Z0-9_-]+)([%&=#a-zA-Z0-9_-])*/',
'/http:\/\/youtu.be\/([a-zA-Z0-9_-]+)/',
);
$value = preg_replace($urls, 'http://youtu.be/$1', $value);
$tag = '<div>'.link_to(image_tag('http://img.youtube.com/vi/$1/1.jpg', 'alt='), 'http://youtu.be/$1', 'class=yt'). '</div>';
$count = 0;
$replaced = preg_replace('/http:\/\/youtu.be\/([a-zA-Z0-9_-]+)/', $tag, $value,-1,$count);
$html = '';
if($count)
{
$html = $replaced;
}
$html .= parent::render($name, $value, $attributes, $errors);
return $html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment