/** * Partendo dall'oggetto che la Api Twitter restituisce per ogni tweet, verifica in base alla proprietà <code>id_str</code> * se il tweet è già presente nel database. In caso affermativo restituisce true, altrimenti inserisce in nuovo record * nel database e lo restituisce. * @param mixed $data Oggetto del tweet restituito dalla Api Twitter * @return mixed True se il tweet è già presente nel database, altrimenti nuovo record creato */ public static function CreateFromObj($data) { $tweet = self::find()->where('id_str=:idstr', [':idstr' => $data->id_str])->one(); if (!$tweet) { # Nuovo tweet: lo inserisco nel database $tweet = new TwitterTweet(); $tweet->id_str = $data->id_str; $tweet->created = date('Y-m-d H:i:s', strtotime($data->created_at)); $text = trim(str_replace('#' . Yii::$app->twitter->hashtag, '<span class="hashtag">#' . Yii::$app->twitter->hashtag . '</span>', $data->text)); $urls = $data->entities->urls; if (is_array($urls)) { foreach ($urls as $url) { $text = str_replace($url->url, Html::a($url->display_url, $url->expanded_url, array('target' => 'blank')), $text); } } $tweet->text = $text; $tweet->save(); $tweet->refresh(); return $tweet; } return true; }
/** * Costruisce una nuova istanza e recupera la lista dei tweet, eventualmente limita * al numero passato come parametro. * @param int $limit Numero massimo di tweet da considerare * @throws InvalidConfigException */ public function __construct($limit = null) { parent::__construct(); if (!Yii::$app->twitter->screenName || !Yii::$app->twitter->hashtag) { throw new InvalidConfigException('Componente Twitter: parametri di configurazione mancanti.'); } $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'; $getfield = '?count=3200&screen_name=' . Yii::$app->twitter->screenName; $requestMethod = 'GET'; $tweets = json_decode($this->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest()); if (!isset($tweets->errors)) { if (isset($limit) && (int) $limit > 0) { $limit = (int) $limit; } else { $limit = 3200; } # Scorro tutti i tweets e controllo se sono già presenti nel database. foreach ($tweets as $tw) { foreach ($tw->entities->hashtags as $ht) { if ($ht->text === Yii::$app->twitter->hashtag) { $tweet = TwitterTweet::CreateFromObj($tw); if ($tweet === true) { break 2; } # trovato tweet già presente nel db: inutile continuare! } } } } # Restituisco la lista dei tweets (tutti o gli ultimi se impostato il $limit) $query = TwitterTweet::find()->orderBy(['created' => SORT_DESC]); if ($limit) { $query->limit($limit); } $this->_tweets = $query->all(); $this->_tweets_index = 0; }