Completed
Pull Request — master (#7)
by
unknown
13:44
created

MyTwitter::TwitterFeed()   D

Complexity

Conditions 18
Paths 26

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
nc 26
nop 2
dl 0
loc 62
rs 4.8666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SunnySideUp\ShareThis;
4
5
use SilverStripe\Core\Injector\Injectable;
6
use SilverStripe\Control\Session;
7
use SilverStripe\Core\Config\Config;
8
use SunnySideUp\ShareThis\MyTwitter;
9
use SunnySideUp\ShareThis\MyTwitterData;
10
use SilverStripe\Control\Director;
11
use SunnySideUp\ShareThis\TwitterOAuth;
12
use SilverStripe\ORM\ArrayList;
13
use SilverStripe\ORM\FieldType\DBDatetime;
14
use SilverStripe\View\ArrayData;
15
16
/**
17
 * @author romain [at] sunnys side up .co.nz + nicolaas [at] sunny side up . co .nz
18
 * @inspiration: https://github.com/tylerkidd/silverstripe-twitter-feed/
19
 * @funding: MSO Design (www.msodesign.com)
20
 *
21
 **/
22
class MyTwitter
23
{
24
    use Injectable;
25
26
    private static $debug = false;
27
28
    private static $singletons = array();
29
30
    private static $favourites_only = false;
31
32
    private static $non_replies_only = false;
33
34
    private static $twitter_consumer_key = "";
35
36
    private static $twitter_consumer_secret = "";
37
38
    private static $titter_oauth_token = "";
39
40
    private static $titter_oauth_token_secret = "";
41
42
    private static $twitter_config = array(
43
        'include_entities' => 'true',
44
        'include_rts' => 'true'
45
    );
46
47
    /**
48
     * returns a DataObjetSet of the last $count tweets.
49
     * - saves twitter feed to dataobject
50
     *
51
     * @param String $username (e.g. mytwitterhandle)
52
     * @param Int $count - number of tweets to retrieve at any one time
53
     * @return DataObjectSet | Null
54
     */
55
    public static function last_statuses($username, $count = 1, $useHourlyCache = true)
56
    {
57
        if (!$username) {
58
            user_error("No username provided");
59
        }
60
        $sessionName = "MyTwitterFeeds$username".date("Ymdh");
61
        if (Session::get($sessionName) && $useHourlyCache && !Config::inst()->get(MyTwitter::class, "debug")) {
62
            //do nothing
63
        } else {
64
            if (empty(self::$singletons[$username])) {
65
                self::$singletons[$username] = new MyTwitter($username, $count);
66
            }
67
            $dataObjectSet = self::$singletons[$username]->TwitterFeed($username, $count);
68
            if ($dataObjectSet && $dataObjectSet->count()) {
69
                foreach ($dataObjectSet as $tweet) {
70
                    if (!MyTwitterData::get()->filter(array("TwitterID" => $tweet->ID))->count()) {
71
                        $myTwitterData = new MyTwitterData();
72
                        $myTwitterData->TwitterID = $tweet->ID;
73
                        $myTwitterData->Title = $tweet->Title;
74
                        $myTwitterData->Date = $tweet->Date;
75
                        $myTwitterData->write();
76
                    }
77
                }
78
            }
79
            Session::set($sessionName, 1);
80
        }
81
        Config::inst()->update(MyTwitterData::class, "username", $username);
82
        return MyTwitterData::get()->filter(array("Hide" => 0))->limit($count);
83
    }
84
85
86
    /**
87
     * retries latest tweets from Twitter
88
     *
89
     * @param String $username (e.g. mytwitterhandle)
90
     * @param Int $count - number of tweets to retrieve at any one time
91
     * @return DataObjectSet | Null
0 ignored issues
show
Documentation introduced by
Should the return type not be null|ArrayList?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
92
     */
93
    public function TwitterFeed($username, $count = 5)
94
    {
95
        if (!$username) {
96
            user_error("No username provided");
97
        }
98
        Config::inst()->update(MyTwitterData::class, "username", $username);
99
        //check settings are available
100
        $requiredSettings = array("twitter_consumer_key", "twitter_consumer_secret", "titter_oauth_token", "titter_oauth_token");
101
        foreach ($requiredSettings as $setting) {
102
            if (!Config::inst()->get(MyTwitter::class, $setting)) {
103
                user_error(" you must set MyTwitter::$setting", E_USER_NOTICE);
104
                return null;
105
            }
106
        }
107
        require_once(Director::baseFolder().'/'.SS_SHARETHIS_DIR.'/third_party/twitter_oauth/TwitterOAuthConsumer.php');
108
        $connection = new TwitterOAuth(
109
            Config::inst()->get(MyTwitter::class, "twitter_consumer_key"),
110
            Config::inst()->get(MyTwitter::class, "twitter_consumer_secret"),
111
            Config::inst()->get(MyTwitter::class, "titter_oauth_token"),
112
            Config::inst()->get(MyTwitter::class, "titter_oauth_token_secret")
113
        );
114
        $config = Config::inst()->get(MyTwitter::class, "twitter_config");
115
        $config['screen_name'] = $username;
116
        $tweets = $connection->get('statuses/user_timeline', $config);
117
        $tweetList = new ArrayList();
118
        if (count($tweets) > 0 && !isset($tweets->error)) {
119
            $i = 0;
120
            foreach ($tweets as $tweet) {
121
                if (Config::inst()->get(MyTwitter::class, "favourites_only") && $tweet->favorite_count == 0) {
122
                    break;
123
                }
124
                if (Config::inst()->get(MyTwitter::class, "non_replies_only") && $tweet->in_reply_to_status_id) {
125
                    break;
126
                }
127
                if (Config::inst()->get(MyTwitter::class, "debug")) {
128
                    print_r($tweet);
129
                }
130
                if (++$i > $count) {
131
                    break;
132
                }
133
134
                $date = new DBDatetime();
135
                $date->setValue(strtotime($tweet->created_at));
136
                $text = htmlentities($tweet->text, ENT_NOQUOTES, $encoding = "UTF-8", $doubleEncode = false);
137
                if (!empty($tweet->entities) && !empty($tweet->entities->urls)) {
138
                    foreach ($tweet->entities->urls as $url) {
139
                        if (!empty($url->url) && !empty($url->display_url)) {
140
                            $text = str_replace($url->url, '<a href="'.$url->url.'" class="external">'.$url->display_url.'</a>', $text);
141
                        }
142
                    }
143
                }
144
                $tweetList->push(
145
                    new ArrayData(array(
146
                        'ID' => $tweet->id_str,
147
                        'Title' => $text,
148
                        'Date' => $date
149
                    ))
150
                );
151
            }
152
        }
153
        return $tweetList;
154
    }
155
}
156