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

ShareThisSTE::makeShareIcons()   B

Complexity

Conditions 10
Paths 5

Size

Total Lines 45

Duplication

Lines 10
Ratio 22.22 %

Importance

Changes 0
Metric Value
cc 10
nc 5
nop 1
dl 10
loc 45
rs 7.3333
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A ShareThisSTE::ShareAll() 0 6 2

How to fix   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\Dev\Debug;
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\Forms\HeaderField;
8
use SilverStripe\Forms\CheckboxField;
9
use SilverStripe\Forms\LiteralField;
10
use SunnySideUp\ShareThis\ShareThisOptions;
11
use SilverStripe\View\Requirements;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Convert;
14
use SilverStripe\View\ArrayData;
15
use SilverStripe\ORM\ArrayList;
16
use SunnySideUp\ShareThis\ShareThisDataObject;
17
use SilverStripe\CMS\Model\SiteTreeExtension;
18
19
/**
20
 * Add a field to each SiteTree object and it's subclasses to enable Share icons.
21
 * @author nicolaas [at] sunnysideup.co.nz
22
 * @inspiration: Silverstripe Original Module - full credits to them.  We made our own to improve their module
23
 * @todo fix populateDefaults to make sure SiteConfig table is built first
24
 */
25
class ShareThisSTE extends SiteTreeExtension
26
{
27
28
    /**
29
     * Use the font-awesome icon collection?
30
     * @var Boolean
31
     */
32
    private static $use_font_awesome = true;
33
34
    /**
35
     * list of sitetree extending classnames where
36
     * the ShareThis functionality should be included
37
     * @var Array
38
     */
39
    private static $always_include_in = array();
40
41
    /**
42
     * list of sitetree extending classnames where
43
     * the ShareThis functionality should NEVER be included
44
     * @var Array
45
     */
46
    private static $never_include_in = array();
47
48
    /**
49
    * use BW icons
50
    * @var boolean
51
    */
52
    private static $use_bw_effect = false;
53
54
    /**
55
    * specify icons to be included, if left empty, this variable will be ignored
56
    * We have this variable so that you can setup a bunch of default icons
57
    * @var array
58
    */
59
    private static $included_icons = array();
60
61
    /**
62
    * specify icons to be excluded, if left empty, this variable will be ignored
63
    * We have this variable so that you can setup a bunch of default icons
64
    * @var array
65
    */
66
    private static $excluded_icons = array();
67
68
    /**
69
     * standard SS method
70
     * @var Array
71
     **/
72
    private static $db = array(
73
        'ShareIcons' => 'Boolean'
74
    );
75
76
    public function updateCMSFields(FieldList $fields)
77
    {
78
        if ($this->applyToOwnerClass()) {
79
            $config = $this->owner->getSiteConfig();
80
            if (! $config->AlwaysIncludeShareThisLinks) {
81
                $fields->addFieldToTab('Root.SocialMedia', new HeaderField('ShareThisHeader', 'Allow users to share this page'));
82
                $fields->addFieldToTab('Root.SocialMedia', new CheckboxField('ShareIcons', 'Show Share Icons on this page', $config->IncludeByDefault));
83
                $fields->addFieldToTab('Root.SocialMedia', new LiteralField('LinkToSiteConfigSocialMedia', "<p>Note: make sure to review the social media settings in the <a href=\"{$config->CMSEditLink()}\">Site Config</a>.</p>"));
84
            }
85
            $list = ShareThisOptions::get_all_options($this->owner->Title, $this->owner->Link(), $this->owner->MetaDescription);
86
            $fields->addFieldToTab('Root.SocialMedia', new HeaderField('ShareThisNow', 'Share this page on your favourite social media sites...'));
87
            $html = "<div><p>Click on any of the icons below to share the '<i>{$this->owner->Title}</i>' page. Any click will open a new tab/window where you will need to enter your login details.</p>";
88
            foreach ($list as $key => $innerArray) {
89
                if (! isset($innerArray['click'])) {
90
                    $html .= "<span><a href=\"{$innerArray['url']}\" target=\"_blank\" style=\"whitespace: nowrap; display: inline-block;\"><img src=\"" . SS_SHARETHIS_DIR . "/images/icons/$key.png\" alt=\"$key\"/>{$innerArray['title']}</a></span>&nbsp;&nbsp;";
91
                }
92
            }
93
            $html .= '</div>';
94
            $fields->addFieldToTab('Root.SocialMedia', new LiteralField('ShareNow', $html));
95
        }
96
        return $fields;
97
    }
98
99
    public function ShowShareIcons()
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...
100
    {
101
        if ($this->applyToOwnerClass()) {
102
            $config = $this->owner->getSiteConfig();
103
            if ($config->AlwaysIncludeShareThisLinks) {
104
                return true;
105
            }
106
            return $this->owner->ShareIcons;
107
        }
108
    }
109
110
    public function ShareIcons()
111
    {
112
        $bookmarks = $this->makeBookmarks('IncludeThisIcon');
113
        return $this->makeShareIcons($bookmarks);
114
    }
115
116
    public function ShareAllExpandedList()
117
    {
118
        Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js');
119
        Requirements::javascript(SS_SHARETHIS_DIR . '/javascript/ShareAllExpandedList.js');
120
        $bookmarks = $this->makeBookmarks('IncludeThisIconInExtendedList');
121
        return $this->makeShareIcons($bookmarks);
122
    }
123
124
    public function IncludeShareAll()
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...
125
    {
126
        $config = $this->owner->getSiteConfig();
127
        return $config->ShareThisAllInOne;
128
    }
129
130
    public function ShareAll()
131
    {
132
        if ($this->IncludeShareAll()) {
133
            return ShareThisOptions::get_share_all();
134
        }
135
    }
136
137
    /**
138
     * eturns array
139
     */
140
    protected function makeShareIcons($bookmarks)
141
    {
142
        $icons = array();
143
        if ($bookmarks) {
144
            $useFontAwesome = Config::inst()->get(ShareThisSTE::class, "use_font_awesome");
145
            Requirements::themedCSS('SocialNetworking', "sharethis"); // ALSO  added in template
146
            if ($useFontAwesome) {
147
                Requirements::css("//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
148
            }
149
            Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js');
150
            Requirements::javascript(SS_SHARETHIS_DIR . '/javascript/shareThis.js');
151
            if (Config::inst()->get(ShareThisSTE::class, "use_bw_effect")) {
152
                Requirements::customScript('sharethis.set_use_BW(true);', 'ShareThisBWEffect');
153
            }
154
            foreach ($bookmarks as $key => $bookmark) {
155
                if (isset($bookmark['title']) && isset($bookmark['url'])) {
156
                    $icon = array(
157
                        'Title' => Convert::raw2att($bookmark['title']),
158
                        'URL' => $bookmark['url'],
159
                        'Key' => $key,
160
                        'ImageSource' => "sharethis/images/icons/$key.png",
161
                        'FAIcon' => $bookmark["faicon"],
162
                        'UseStandardImage' => true
163
                    );
164
                    if (isset($bookmark['click'])) {
165
                        $icon['OnClick'] = $bookmark['click'];
166
                    }
167 View Code Duplication
                    if ($useFontAwesome) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168
                        $icon['ImageSource'] = null;
169
                        $icon['UseStandardImage'] = false;
170
                        $icon['FAIcon'] = $bookmark["faicon"];
171
                    }
172 View Code Duplication
                    if (isset($bookmark['icon'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
173
                        $icon['ImageSource'] = $bookmark['icon'];
174
                        $icon['UseStandardImage'] = false;
175
                        $icon['FAIcon'] = null;
176
                    }
177
                    $icons[] = new ArrayData($icon);
178
                } else {
179
                    Debug::show("Title of url not defined for $key");
180
                }
181
            }
182
        }
183
        return new ArrayList($icons);
184
    }
185
186
    protected function makeBookmarks($field)
187
    {
188
        $finalBookmarks = array();
189
        $bookmarks = ShareThisOptions::get_page_specific_data($this->owner->Title, $this->owner->Link(), $this->owner->MetaDescription);
190
        $objects = ShareThisDataObject::get()
191
            ->filter($field, 1)
192
            ->sort(array('Sort' => 'ASC', 'Title' => 'ASC'));
193
        if ($objects->count()) {
194
            foreach ($objects as $obj) {
195
                if (isset($bookmarks[$obj->Title])) {
196
                    $finalBookmarks[$obj->Title] = $bookmarks[$obj->Title];
197
                    if ($obj->AlternativeIconID && $obj->AlternativeIcon()->exists()) {
198
                        $finalBookmarks[$obj->Title]['icon'] = $obj->AlternativeIcon()->Link();
199
                    }
200
                }
201
            }
202
        } else {
203
            $finalBookmarks = $bookmarks;
204
        }
205
        return $finalBookmarks;
206
    }
207
208
    private function applyToOwnerClass()
209
    {
210
        $always = Config::inst()->get(ShareThisSTE::class, "always_include_in");
211
        $never = Config::inst()->get(ShareThisSTE::class, "never_include_in");
212
        if (count($always) == 0 && count($never) == 0) {
213
            return true;
214 View Code Duplication
        } elseif (count($never) && count($always) == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
215
            if (in_array($this->owner->ClassName, $never)) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !in_array($this->...er->ClassName, $never);.
Loading history...
216
                return false;
217
            }
218
            return true;
219
        } elseif (count($always) && count($never) == 0) {
220
            if (in_array($this->owner->ClassName, $always)) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return in_array($this->o...r->ClassName, $always);.
Loading history...
221
                return true;
222
            }
223
            return false;
224 View Code Duplication
        } elseif (count($never) && count($always)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225
            if (in_array($this->owner->ClassName, $never)) {
226
                return false;
227
            }
228
            if (in_array($this->owner->ClassName, $always)) {
0 ignored issues
show
Unused Code introduced by
This if statement and the following return statement are superfluous as you return always true.
Loading history...
229
                return true;
230
            }
231
            //exception... if dev sets both always and never
232
            //then the ones not set will be included by default.
233
            return true;
234
        } else {
235
            user_error("Strange condition!", E_USER_NOTICE);
236
        }
237
    }
238
}
239