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

FacebookFeed_Page::Fetch()   D

Complexity

Conditions 18
Paths 16

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
nc 16
nop 1
dl 0
loc 52
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\Forms\TreeMultiSelectField;
6
use SunnySideUp\ShareThis\FacebookFeed_Item;
7
use SilverStripe\CMS\Model\SiteTree;
8
use SilverStripe\Security\Permission;
9
use SilverStripe\Forms\LiteralField;
10
use SilverStripe\ORM\DB;
11
use SunnySideUp\ShareThis\SilverstripeFacebookConnector;
12
use SilverStripe\ORM\DataObject;
13
14
/**
15
 * FROM: http://www.acornartwork.com/blog/2010/04/19/tutorial-facebook-rss-feed-parser-in-pure-php/
16
 * EXAMPLE:
17
 *		//Run the function with the url and a number as arguments
18
 *		$fb = new TheFaceBook_communicator();
19
 *		$dos = $fb->fetchFBFeed('http://facebook.com/feeds/status.php?id=xxxxxx&viewer=xxxxxx&key=xxxxx&format=rss20', 3);
20
 *		//Print Facebook status updates
21
 *		echo '<ul class="fb-updates">';
22
 *			 foreach ($dos as $do) {
23
 *					echo '<li>';
24
 *					echo '<span class="update">' .$do->Description. '</span>';
25
 *					echo '<span class="date">' .$do->Date. '</span>';
26
 *					echo '<span class="link"><a href="' .$do->Link. '">more</a></span>';
27
 *					echo '</li>';
28
 *			 }
29
 *		echo '</ul>';
30
 *
31
 *  SEE README on getting facebook URL for RSS Feed.
32
 *
33
 *
34
 **/
35
class FacebookFeed_Page extends DataObject
36
{
37
    private static $db = array(
38
        "Title" => "Varchar(244)",
39
        'FacebookPageID' => 'Varchar(40)'
40
    );
41
42
    private static $has_many = array(
43
        'Items' => FacebookFeed_Item::class
44
    );
45
46
    private static $many_many = array(
47
        'Pages' => SiteTree::class
48
    );
49
50
    public function canCreate($member = null, $context = [])
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
51
    {
52
        return Permission::checkMember($member, 'SOCIAL_MEDIA');
53
    }
54
55
    public function canView($member = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
56
    {
57
        return Permission::checkMember($member, 'SOCIAL_MEDIA');
58
    }
59
60
    public function canEdit($member = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
61
    {
62
        return Permission::checkMember($member, 'SOCIAL_MEDIA');
63
    }
64
65
    public function canDelete($member = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
66
    {
67
        return Permission::checkMember($member, 'SOCIAL_MEDIA');
68
    }
69
70
    public function getCMSFields()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
71
    {
72
        $fields = parent::getCMSFields();
73
        $fields->addFieldToTab(
74
            "Root.Main",
75
            new LiteralField(
76
                "HowToFindPageID",
77
                "<p>
78
                To find the Facebook Page ID value, you can follow these steps :</p>
79
                <ol>
80
                    <li>Open a new tab and open <a href=\"http://www.facebook.com\" target=\"_blank\">facebook</a></li>
81
                    <li>Find your page (e.g. https://www.facebook.com/EOSAsia)</li>
82
                    <li>Note the name (e.g. EOSAsia)</li>
83
                    <li>Go to <a href=\"http://findmyfacebookid.com\" target=\"_blank\">http://findmyfacebookid.com</a></li>
84
                    <li>Enter http://www.facebook.com/EOSAsia</li>
85
                    <li>You'll get the answer (e.g. 357864420974239)</li>
86
                </ol>"
87
            )
88
        );
89
        $fields->addFieldToTab(
90
            "Root.Pages",
91
            new TreeMultiSelectField("Pages", "Show on", SiteTree::class)
92
        );
93
        $pages = $this->Pages();
94
        if ($pages && $pages->count()) {
95
            $links = array();
96
            foreach ($pages as $page) {
97
                $links[] = "<li><a href=\"".$page->Link("updatefb")."\">".$page->Title."</a></li>";
98
            }
99
            if (count($links)) {
100
                $fields->addFieldToTab(
101
                    "Root.Pages",
102
                    new LiteralField(
103
                        "LinksToCheck",
104
                        "<p>
105
                            Choose the links below to view your facebook feed:
106
                        <ol>
107
                            ".implode("", $links)."
108
                        </ol>"
109
                    )
110
                );
111
            }
112
        }
113
        return $fields;
114
    }
115
116
    /**
117
     *
118
     * @param SiteTree | Int $page - page or page id
119
     * @param Int $limit
120
     *
121
     */
122
    public static function all_for_one_page($page, $limit = 10)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
123
    {
124
        if ($page instanceof SiteTree) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\CMS\Model\SiteTree does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
125
            $pageID = $page->ID;
126
        } else {
127
            $pageID = $page;
128
        }
129
        $feedIDs = array();
130
        $sql = "
131
            SELECT \"FacebookFeed_Page_Pages\".\"FacebookFeed_PageID\"
132
            FROM \"FacebookFeed_Page_Pages\"
133
            WHERE \"FacebookFeed_Page_Pages\".\"SiteTreeID\" = $pageID";
134
        $rows = DB::query($sql);
135
        if ($rows) {
136
            foreach ($rows as $row) {
137
                $feedIDs[$row["FacebookFeed_PageID"]] = $row["FacebookFeed_PageID"];
138
            }
139
        }
140
        if (count($feedIDs)) {
141
            return FacebookFeed_Item::get()->filter(
142
                array(
143
                    "FacebookFeed_PageID" => $feedIDs,
144
                    "Hide" => 0
145
                )
146
            )
147
            ->limit($limit);
148
        }
149
    }
150
151
    public function ShowableItems($limit = 10)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
152
    {
153
        return $this->getComponents('Items', 'Hide = 0', null, '', $limit);
154
    }
155
156
    public function Fetch($verbose = false)
157
    {
158
        $count = 0;
159
        if ($this->FacebookPageID) {
160
            $items = SilverstripeFacebookConnector::get_feed($this->FacebookPageID);
161
            if ($items) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $items of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
162
                foreach ($items as $item) {
163
                    $filter = array("UID" => $item["id"]);
164
                    if (! FacebookFeed_Item::get()->filter($filter)->first()) {
165
                        $count++;
166
                        $message = "";
167
                        if (isset($item["message"])) {
168
                            $message = $item["message"];
169
                        } elseif (isset($item["description"])) {
170
                            $message = $item["description"];
171
                        }
172
                        //Converts UTF-8 into ISO-8859-1 to solve special symbols issues
173
                        $message = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $message);
174
                        $message = $this->stripUnsafe($message);
175
                        //Get status update time
176
                        $pubDate = strtotime(isset($item["created_time"]) ? $item["created_time"] : "today");
177
                        $convertedDate = gmdate($timeFormat = 'Y-m-d', $pubDate);  //Customize this to your liking
178
                        //Get link to update
179
                        //Store values in array
180
                        $obj = FacebookFeed_Item::create($filter);
181
                        $obj->Title = (string) (isset($item["name"]) ? $item["name"] : "");
182
                        $obj->Date = $convertedDate;
183
                        $obj->Author = (string) (isset($item["from"]["name"]) ? $item["from"]["name"] : "");
184
                        $obj->Link = (string) (isset($item["link"]) ? $item["link"] : "");
185
                        $obj->PictureLink = (string) (isset($item["full_picture"]) ? $item["full_picture"] : "");
186
                        $obj->Description = $message;
187
                        $obj->FacebookFeed_PageID = $this->ID;
188
                        $obj->write();
189
                    }
190
                }
191
            } else {
192
                if ($verbose) {
193
                    DB::alteration_message("ERROR: no data returned", "deleted");
194
                }
195
            }
196
            if ($count == 0 && $verbose) {
197
                DB::alteration_message("Nothing to add.");
198
            }
199
        } else {
200
            if ($verbose) {
201
                DB::alteration_message("ERROR: no Facebook Page ID provided", "deleted");
202
            }
203
        }
204
        if ($count && $verbose) {
205
            DB::alteration_message("Added $count items", "created");
206
        }
207
    }
208
209
    public function stripUnsafe($string)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
210
    {
211
        // Unsafe HTML tags that members may abuse
212
        $unsafe=array(
213
            '/onmouseover="(.*?)"/is',
214
            '/onclick="(.*?)"/is',
215
            '/style="(.*?)"/is',
216
            '/target="(.*?)"/is',
217
            '/onunload="(.*?)"/is',
218
            '/rel="(.*?)"/is',
219
            '/<a(.*?)>/is',
220
            '/<\/a>/is'
221
        );
222
        $string= preg_replace($unsafe, " ", $string);
223
        return $string;
224
    }
225
}
226