[TASK] Refactor Twitter api 65/23165/2
authorNicole Cordes <cordes@cps-it.de>
Sat, 17 Aug 2013 21:41:29 +0000 (23:41 +0200)
committerNicole Cordes <typo3@cordes.co>
Sat, 17 Aug 2013 21:44:23 +0000 (23:44 +0200)
Refactor Twitter api and introduce an own tweet repository to be more
flexible for new requests.

Releases: 1.0
Change-Id: If22a166ad98a44c4fd054eca2f7857c8ad7e2526
Reviewed-on: https://review.typo3.org/23165
Reviewed-by: Nicole Cordes
Tested-by: Nicole Cordes
Classes/Controller/TwitterController.php
Classes/Domain/Repository/TweetRepository.php [new file with mode: 0644]
Classes/Twitter/Api.php

index 0a5af93..64bca70 100644 (file)
 class Tx_WtTwitter_Controller_TwitterController extends Tx_Extbase_MVC_Controller_ActionController {
 
        /**
+        * @var Tx_WtTwitter_Domain_Repository_TweetRepository
+        */
+       protected $tweetRepository = NULL;
+
+       public function injectTweetRepository(Tx_WtTwitter_Domain_Repository_TweetRepository $tweetRepository) {
+               $this->tweetRepository = $tweetRepository;
+       }
+
+       /**
         * Initializes the current action
         *
         * @return void
@@ -61,45 +70,20 @@ class Tx_WtTwitter_Controller_TwitterController extends Tx_Extbase_MVC_Controlle
         * @return string The rendered view
         */
        public function listAction() {
-               $extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['wt_twitter']);
-               $response = '';
                $tweets = array();
+               $response = '';
 
-               if (empty($extensionConfiguration['oauth_token']) || empty($extensionConfiguration['oauth_token_secret'])) {
-                       $this->flashMessageContainer->add(
-                               'Please authorize your Twitter account in the extension settings.',
-                               'Twitter account not authorize',
-                               t3lib_FlashMessage::ERROR
-                       );
-               } elseif (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] || !function_exists('curl_init')) {
-                       $this->flashMessageContainer->add(
-                               'Please enable the use of curl in TYPO3 Install Tool by activation of TYPO3_CONF_VARS[SYS][curlUse] and check PHP integration.',
-                               'No curl available',
-                               t3lib_FlashMessage::ERROR
-                       );
-               } else {
-                       $count = (int)$this->settings['limit'];
-                       switch ($this->settings['mode']) {
-                               case 'showOwn':
-                                       $tweets = Tx_WtTwitter_Twitter_Api::getTweetsFromUserTimeline(
-                                               $extensionConfiguration['oauth_token'],
-                                               $extensionConfiguration['oauth_token_secret'],
-                                               $this->settings['account'],
-                                               $this->settings['showRetweets'],
-                                               $count,
-                                               $response
-                                       );
-                                       break;
-                               case 'showFromSearch':
-                                       $tweets = Tx_WtTwitter_Twitter_Api::getTweetsFromSearch(
-                                               $extensionConfiguration['oauth_token'],
-                                               $extensionConfiguration['oauth_token_secret'],
-                                               $this->settings['hashtag'],
-                                               $count,
-                                               $response
-                                       );
-                                       break;
-                       }
+               if (count($this->settings) < 8) { // only flexform config (but no TypoScript)
+                       $this->flashMessageContainer->add('Please add wt_twitter Static Template in the TYPO3 Backend'); // show missing template error
+               }
+
+               switch ($this->settings['mode']) {
+                       case 'showOwn':
+                               $tweets = $this->tweetRepository->getTweetsFromUserTimeline($this->settings, $this->settings['limit'], $response);
+                               break;
+                       case 'showFromSearch':
+                               $tweets = $this->tweetRepository->getTweetsFromSearch($this->settings, $this->settings['limit'], $response);
+                               break;
                }
                // Look up for any errors
                if ($response !== '') {
@@ -122,10 +106,6 @@ class Tx_WtTwitter_Controller_TwitterController extends Tx_Extbase_MVC_Controlle
                }
                $this->view->assign('tweets', $tweets); // array to view
 
-               if (count($this->settings) < 5) { // only flexform config (but no TypoScript)
-                       $this->flashMessageContainer->add('Please add wt_twitter Static Template in the TYPO3 Backend'); // show missing template error
-               }
-
                if ($this->settings['debug'] == 1) {
                        t3lib_utility_Debug::debug($this->settings, 'TypoScript and Flexform settings');
                        t3lib_utility_Debug::debug($tweets, 'Result Array from Twitter');
diff --git a/Classes/Domain/Repository/TweetRepository.php b/Classes/Domain/Repository/TweetRepository.php
new file mode 100644 (file)
index 0000000..f9fddb1
--- /dev/null
@@ -0,0 +1,195 @@
+<?php
+/***************************************************************
+ *  Copyright notice
+ *
+ *  (c) 2013 Nicole Cordes <cordes@cps-it.de>
+ *  All rights reserved
+ *
+ *  This script is part of the TYPO3 project. The TYPO3 project is
+ *  free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  The GNU General Public License can be found at
+ *  http://www.gnu.org/copyleft/gpl.html.
+ *
+ *  This script is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
+
+/**
+ * Repository for tweets
+ *
+ * @author Nicole Cordes <cordes@cps-it.de>
+ * @package TYPO3
+ * @subpackage wt_twitter
+ */
+class Tx_WtTwitter_Domain_Repository_TweetRepository {
+
+       /**
+        * The extension configuration
+        *
+        * @var array
+        */
+       protected $extensionConfiguration = array();
+
+       /**
+        * The flash messages container
+        *
+        * @var Tx_Extbase_MVC_Controller_FlashMessages
+        */
+       protected $flashMessageContainer = NULL;
+
+       /**
+        * Constructor function
+        */
+       public function __construct() {
+               $this->extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['wt_twitter']);
+       }
+
+       /**
+        * @param Tx_Extbase_MVC_Controller_FlashMessages $flashMessageContainer
+        * @return void
+        */
+       public function injectFlashMessageContainer(Tx_Extbase_MVC_Controller_FlashMessages $flashMessageContainer) {
+               $this->flashMessageContainer = $flashMessageContainer;
+       }
+
+       /**
+        * @param array $settings
+        * @param integer $count
+        * @param NULL $response
+        * @return array
+        */
+       public function getTweetsFromSearch($settings, $count, &$response = NULL) {
+               $tweets = array();
+
+               if ($this->isTwitterSigned()&& $this->isCurlActivated()) {
+                       $parameter = array(
+                               'q' => $settings['hashtag']
+                       );
+
+                       $result = $this->callApi(Tx_WtTwitter_Twitter_Api::getSearchTweetsUrl(), 'GET', $parameter, $response);
+                       $tweets = $result->statuses;
+               }
+
+               return $this->addOldUserInformation($this->sliceTweets($tweets, $count));
+       }
+
+       /**
+        * @param array $settings
+        * @param integer $count
+        * @param NULL $response
+        * @return array
+        */
+       public function getTweetsFromUserTimeline($settings, $count, &$response = NULL) {
+               $tweets = array();
+
+               if ($this->isTwitterSigned() && $this->isCurlActivated()) {
+                       $parameter = array();
+
+                       // Get screen name
+                       if (Tx_WtTwitter_Utility_Compatibility::testInt($settings['account'])) {
+                               $parameter['user_id'] = $settings['account'];
+                       } else {
+                               $parameter['screen_name'] = $settings['account'];
+                       }
+
+                       // Enable retweets
+                       if ($settings['showRetweets']) {
+                               $parameter['include_rts'] = 'true';
+                       } else {
+                               $parameter['include_rts'] = 'false';
+                       }
+
+                       $tweets = $this->callApi(Tx_WtTwitter_Twitter_Api::getUserTimelineUrl(), 'GET', $parameter, $response);
+               }
+
+               return $this->addOldUserInformation($this->sliceTweets($tweets, $count));
+       }
+
+       /**
+        * @return boolean
+        */
+       protected function isTwitterSigned() {
+               if (empty($this->extensionConfiguration['oauth_token']) || empty($this->extensionConfiguration['oauth_token_secret'])) {
+                       $this->flashMessageContainer->add(
+                               'Please authorize your Twitter account in the extension settings.',
+                               'Twitter account not authorize',
+                               t3lib_FlashMessage::ERROR
+                       );
+
+                       return FALSE;
+               }
+
+               return TRUE;
+       }
+
+       /**
+        * @return boolean
+        */
+       protected function isCurlActivated() {
+               if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] || !function_exists('curl_init')) {
+                       $this->flashMessageContainer->add(
+                               'Please enable the use of curl in TYPO3 Install Tool by activation of TYPO3_CONF_VARS[SYS][curlUse] and check PHP integration.',
+                               'No curl available',
+                               t3lib_FlashMessage::ERROR
+                       );
+
+                       return FALSE;
+               }
+
+               return TRUE;
+       }
+
+       /**
+        * @param string $url
+        * @param string $method
+        * @param array $parameter
+        * @param NULL $response
+        * @return array
+        */
+       protected function callApi($url, $method, $parameter, $response) {
+               return Tx_WtTwitter_Twitter_Api::processRequest(
+                       $this->extensionConfiguration['oauth_token'],
+                       $this->extensionConfiguration['oauth_token_secret'],
+                       $url,
+                       $method,
+                       $parameter,
+                       $response
+               );
+       }
+
+       /**
+        * @param array $tweets
+        * @param integer $count
+        * @return array
+        */
+       protected function sliceTweets(array $tweets, $count) {
+               if (count($tweets) <= $count) {
+                       return $tweets;
+               }
+
+               return array_slice($tweets, 0, $count);
+       }
+
+       /**
+        * @param array $tweets
+        * @return array
+        */
+       protected function addOldUserInformation(array $tweets) {
+               foreach ($tweets as &$tweet) {
+                       $tweet->profile_image_url = $tweet->user->profile_image_url;
+                       $tweet->from_user = $tweet->user->screen_name;
+               }
+               unset($tweet);
+
+               return $tweets;
+       }
+
+}
\ No newline at end of file
index 94e2b76..962546e 100644 (file)
@@ -76,7 +76,7 @@ final class Tx_WtTwitter_Twitter_Api {
         */
        public static function getOAuthParameter($oAuthToken, array $additionalParameter = array()) {
                $oAuthParameter = array(
-                       'oauth_consumer_key' => self::consumerKey,
+                       'oauth_consumer_key' => static::consumerKey,
                        'oauth_nonce' => md5(microtime() . mt_rand()),
                        'oauth_signature_method' => 'HMAC-SHA1',
                        'oauth_timestamp' => time(),
@@ -153,131 +153,47 @@ final class Tx_WtTwitter_Twitter_Api {
        /**
         * @param string $oAuthToken
         * @param string $oAuthTokenSecret
-        * @param string $query
-        * @param string|NULL $count
-        * @param NULL $returnedResponse
-        *
-        * @return array
-        */
-       public static function getTweetsFromSearch($oAuthToken, $oAuthTokenSecret, $query, $count = NULL, &$returnedResponse = NULL) {
-               $tweets = array();
-               $parameter = array(
-                       'q' => $query,
-               );
-
-               $url = self::getSearchTweetsUrl();
-
-               $ch = curl_init();
-               curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-               curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
-               curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
-               curl_setopt($ch, CURLOPT_HEADER, 0);
-               curl_setopt($ch, CURLOPT_URL, $url . '?' . Tx_WtTwitter_Twitter_Api::implodeArrayForUrl($parameter));
-
-               $oAuthParameter = Tx_WtTwitter_Twitter_Api::createSignature(
-                       Tx_WtTwitter_Twitter_Api::getOAuthParameter(
-                               $oAuthToken
-                       ),
-                       $url,
-                       'GET',
-                       Tx_WtTwitter_Twitter_Api::consumerSecret,
-                       $oAuthTokenSecret,
-                       $parameter
-               );
-
-               $header = array(
-                       'Authorization: OAuth ' . self::implodeArrayForHeader($oAuthParameter),
-                       'Content-Length:',
-                       'Content-Type:',
-                       'Expect:'
-               );
-               curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
-
-               $response = curl_exec($ch);
-               if (isset($returnedResponse)) {
-                       $returnedResponse = $response;
-               }
-               if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
-                       $responseObject = json_decode($response);
-                       $tweets = $responseObject->statuses;
-                       $tweets = array_slice($tweets, 0, $count);
-                       foreach ($tweets as &$value) {
-                               $value->profile_image_url = $value->user->profile_image_url;
-                               $value->from_user = $value->user->screen_name;
-                       }
-                       unset($value);
-
-               }
-               curl_close($ch);
-
-               return $tweets;
-       }
-
-       /**
-        * @param string $oAuthToken
-        * @param string $oAuthTokenSecret
-        * @param string $screenName
-        * @param integer $showRetweets
-        * @param string|NULL $count
-        * @param NULL $returnedResponse
-        *
+        * @param string $url
+        * @param string $method
+        * @param array $parameter
+        * @param NULL $response
         * @return array
         */
-       public static function getTweetsFromUserTimeline($oAuthToken, $oAuthTokenSecret, $screenName, $showRetweets, $count = NULL, &$returnedResponse = NULL) {
+       public static function processRequest($oAuthToken, $oAuthTokenSecret, $url, $method, $parameter, &$response) {
                $tweets = array();
-               $parameter = array();
-               if (Tx_WtTwitter_Utility_Compatibility::testInt($screenName)) {
-                       $parameter['user_id'] = $screenName;
-               } else {
-                       $parameter['screen_name'] = $screenName;
-               }
-               if ($showRetweets) {
-                       $parameter['include_rts'] = 'true';
-               } else {
-                       $parameter['include_rts'] = 'false';
-               }
-
-               $url = self::getUserTimelineUrl();
 
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
-               curl_setopt($ch, CURLOPT_URL, $url . '?' . Tx_WtTwitter_Twitter_Api::implodeArrayForUrl($parameter));
+               curl_setopt($ch, CURLOPT_URL, $url . '?' . static::implodeArrayForUrl($parameter));
 
-               $oAuthParameter = Tx_WtTwitter_Twitter_Api::createSignature(
-                       Tx_WtTwitter_Twitter_Api::getOAuthParameter(
+               $oAuthParameter = static::createSignature(
+                       static::getOAuthParameter(
                                $oAuthToken
                        ),
                        $url,
-                       'GET',
-                       Tx_WtTwitter_Twitter_Api::consumerSecret,
+                       $method,
+                       static::consumerSecret,
                        $oAuthTokenSecret,
                        $parameter
                );
 
                $header = array(
-                       'Authorization: OAuth ' . self::implodeArrayForHeader($oAuthParameter),
+                       'Authorization: OAuth ' . static::implodeArrayForHeader($oAuthParameter),
                        'Content-Length:',
                        'Content-Type:',
                        'Expect:'
                );
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
 
-               $response = curl_exec($ch);
-               if (isset($returnedResponse)) {
-                       $returnedResponse = $response;
+               $result = curl_exec($ch);
+               if (isset($response)) {
+                       $response = $result;
                }
                if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
-                       $tweets = json_decode($response);
-                       $tweets = array_slice($tweets, 0, $count);
-                       foreach ($tweets as &$value) {
-                               $value->profile_image_url = $value->user->profile_image_url;
-                               $value->from_user = $value->user->screen_name;
-                       }
-                       unset($value);
-
+                       $tweets = json_decode($result);
                }
                curl_close($ch);