Skip to content

Instantly share code, notes, and snippets.

@wilr
Created July 6, 2012 03:38
Show Gist options
  • Save wilr/3057915 to your computer and use it in GitHub Desktop.
Save wilr/3057915 to your computer and use it in GitHub Desktop.
A simple SilverStripe PHP class for loading a stream of tweets from a XML file.
<?php
/**
* Loads tweets onto a SilverStripe object through a XML file rather than the
* web API.
*
* Usage:
*
* // PHP
* function Tweets() {
* return Tweet::get('http://twitter.com/statuses/user_timeline/willrossi.rss', 10);
* }
*
* // SS
* <% if $Tweets %>
* <% loop $Tweets %>
* $Description on $PubDate.Nice
* <% end_loop %>
* <% end_if %>
*
* @license http://sam.zoy.org/wtfpl/COPYING
* @author Will Rossiter (will@fullscreen.io)
*/
class Tweet extends ViewableData {
protected $description;
protected $pubDate;
public function __construct($description, $pubDate) {
$this->description = $description;
$this->pubDate = $pubDate;
}
/**
* Parses hash tags, @usernames, and URLs in a tweet description into
* HTML links.
*
* @return string
*/
public function getDescription() {
$desc = $this->description;
$desc = substr(strstr($desc, ': '), 2, strlen($desc)); // remove preceding username
$desc = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", "<a href=\"\\0\">\\0</a>", $desc); // URLs into links
$desc = preg_replace('/(^|\s)#(\w+)/', '\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', $desc); // Hash tags to links
return DBField::create_field('HTMLText', $desc);
}
/**
* @return SS_Datetime
*/
public function getPubDate() {
return DBField::create_field('SSDatetime', $this->pubDate);
}
/**
* Get some tweets from static file with a limit.
*
* @param int $limit Limit number of tweets
* @return ArrayList
*/
public static function get($path, $limit) {
$cache = SS_Cache::factory('tweets');
if (!($output = unserialize($cache->load('tweets')))) {
$output = new ArrayList();
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'timeout' => 5
)
));
$tweets = @file_get_contents($path, '', $context);
if(!$tweets) return false;
$xml = new SimpleXMLElement($tweets);
$total = 0;
foreach($xml->xpath('channel/item') as $item) {
$output->push(new Tweet(
(string) $item->description,
(string) $item->pubDate
));
$total++;
if($total == $limit) break;
}
$cache->save(serialize($output));
}
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment