Skip to content

Instantly share code, notes, and snippets.

@torounit
Last active August 29, 2015 14:01
Show Gist options
  • Save torounit/25ecc99c69a6a35520b0 to your computer and use it in GitHub Desktop.
Save torounit/25ecc99c69a6a35520b0 to your computer and use it in GitHub Desktop.
Twitter APIで取得したTweets Objectをちょっと便利にするクラス。 Tweets (https://dev.twitter.com/docs/platform-objects/tweets)
<?php
Class Tweets extends ArrayObject {
public function __construct( Array $tweets ) {
foreach($tweets as $key => $tweet) {
$this->offsetSet($key, $this->createTweet($tweet));
}
}
public function createTweet($tweet) {
return new Tweet($tweet);
}
}
class Tweet {
private $data;
public function __construct($tweet) {
$this->data = $tweet;
}
public function __get($name) {
return $this->get($name);
}
public function get( $name ) {
$data = $this->data->$name;
if( $name == "text" and is_string($data) ) {
$data = $this->expand_url($data);
$data = $this->link_repry($data);
return $data;
}
return $this->data->$name;
}
private function link_repry( $text ) {
$user = $this->get("in_reply_to_screen_name");
return str_replace("@".$user, "<a href='https://twitter.com/".$user."'>@".$user."</a>", $text );
}
private function expand_url( $text ) {
$entities = $this->get("entities");
$text = $this->replace_url($text, $entities->urls);
$text = $this->replace_url($text, $entities->media);
return $text;
}
private function replace_url($subject, $replaces) {
foreach ($replaces as $key => $url) {
$subject = str_replace($url->url, "<a href='".$url->url."'>".$url->display_url."</a>", $subject );
}
return $subject;
}
}
@torounit
Copy link
Author

$tweets = new Tweets(json_decode($data));

URLを書き換えたりします。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment