Skip to content

Instantly share code, notes, and snippets.

@dljoseph
Created November 22, 2014 08:33
Show Gist options
  • Save dljoseph/a463f53653d791df6fa1 to your computer and use it in GitHub Desktop.
Save dljoseph/a463f53653d791df6fa1 to your computer and use it in GitHub Desktop.
SilverStripe 3.1.x Fetch and Save Vimeo Thumbnail on DataObject from given Vimeo Video ID
protected function onBeforeWrite() {
//Do we have a vimeo video ID? If so, we need to grab the Vimeo thumbnail
//...but we only want to do this if either of the following conditions are true:
//1) A VimeoVideoID has been entered into the CMS and we don't have a thumbnail yet, or
//2) The VimeoVideoID entered has changed since this Article was last saved
if(($this->VimeoVideoID && !$this->TutorialCustomThumbnailID)
|| (isset($this->original['VimeoVideoID']) && ($this->VimeoVideoID != $this->original['VimeoVideoID']))) {
//Let's deal with the exceptional case first. Perhaps the content editor is removing the VimeoVideoID.
//If that is the case, we should detach the thumbnail from the record.
if(!$this->VimeoVideoID) {
$this->TutorialCustomThumbnailID = 0;
$this->IncludeTutorialVideo = false;
} else {
//get the xml data about the video from Vimeo using the Vimeo Simple API
$xml = simplexml_load_file('http://vimeo.com/api/v2/video/'.$this->VimeoVideoID.'.xml');
//Grab the URL of the video thumbnail
$xml_pic = $xml->video->thumbnail_medium;
//get the extension of the image - we will need it later
$ext = pathinfo($xml_pic, PATHINFO_EXTENSION);
//get the image data
$image = file_get_contents($xml_pic);
//write the image to the filesystem
$folder = Folder::find_or_make('/Uploads/Tutorial-Video-Thumbnails/');
file_put_contents(ASSETS_PATH . '/Uploads/Tutorial-Video-Thumbnails/'.$this->VimeoVideoID.'-medium.'.$ext, $image);
//set our thumbnail image filename
$filename = ASSETS_DIR . '/Uploads/Tutorial-Video-Thumbnails/'.$this->VimeoVideoID.'-medium.'.$ext;
//check if a record already exists for this image filename in the database.
//If one already exists, then we can just use it - no need to create another image entry in the db.
if($vimeoThumbnail = Image::get()->filter(array('Filename' => $filename))->first()) {
$this->TutorialCustomThumbnailID = $vimeoThumbnail->ID;
} else {
//create a new Image DataObject with the details of this new image and save record to database
$vimeoThumbnail = new Image();
$vimeoThumbnail->Filename = ASSETS_DIR . '/Uploads/Tutorial-Video-Thumbnails/'.$this->VimeoVideoID.'-medium.'.$ext;
$vimeoThumbnail->Title = $this->VimeoVideoID.'-medium';
$vimeoThumbnail->ParentID = $folder->ID;
$vimeoThumbnail->write();
$this->TutorialCustomThumbnailID = $vimeoThumbnail->ID;
}
}
}
parent::onBeforeWrite();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment