Passed
Branch master (af2b13)
by Nicolaas
03:22
created

ShareThisSimpleProvider::shareThisFieldAsString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
namespace Sunnysideup\ShareThisSimple\Api;
4
5
use SilverStripe\Core\Config\Config;
6
use SilverStripe\ORM\ArrayList;
7
use SilverStripe\ORM\DataObject;
8
9
use SilverStripe\ORM\FieldType\DBField;
10
use SilverStripe\View\ArrayData;
11
use SilverStripe\View\ViewableData;
12
13
class ShareThisSimpleProvider extends ViewableData
14
{
15
    /**
16
     * @var DataObject
17
     */
18
    protected $object;
19
20
    protected $linkMethod = 'AbsoluteLink';
21
22
    protected $titleMethod = 'Title';
23
24
    protected $imageMethods = [];
25
26
    protected $descriptionMethod = 'SocialMediaDescription'; //change to 'SocialMediaDescription'
27
28
    protected $hashTagArray = [];
29
30
    protected $mentionsArray = [];
31
32
    protected $viasArray = [];
33
34
    /**
35
     * @var string
36
     */
37
    protected $pageURL = '';
38
39
    /**
40
     * @var string
41
     */
42
    protected $title = '';
43
44
    /**
45
     * @var string
46
     */
47
    protected $titleFull = '';
48
49
    /**
50
     * @var string
51
     */
52
    protected $media = '';
53
54
    /**
55
     * @var string
56
     */
57
    protected $description = '';
58
59
    /**
60
     * @var string
61
     */
62
    protected $descriptionFull = '';
63
64
    /**
65
     * @var string
66
     */
67
    protected $hashTags = '';
68
69
    /**
70
     * @var string
71
     */
72
    protected $mentions = '';
73
74
    /**
75
     * @var string
76
     */
77
    protected $vias = '';
78
79
    protected static $pop_up_window_height = 320;
80
81
    protected static $pop_up_window_width = 200;
82
83
    protected static $cacheGetShareThisArray = [];
84
85
    private static $description_method = '';
86
87
    private static $default_mentions = [];
88
89
    private static $default_vias = [];
90
91
    private static $default_hash_tags = [];
92
93
    private static $image_methods = [];
94
95
    private static $casting = [
96
        'FacebookShareLink' => 'Varchar',
97
        'TwitterShareLink' => 'Varchar',
98
        'TumblrShareLink' => 'Varchar',
99
        'PinterestShareLink' => 'Varchar',
100
        'EmailShareLink' => 'Varchar',
101
        'RedditShareLink' => 'Varchar',
102
        'PinterestLinkForSpecificImage' => 'Varchar',
103
    ];
104
105
    /**
106
     * @param DataObject $object
107
     */
108
    public function __construct($object)
109
    {
110
        parent::__construct();
111
        if (! $object instanceof DataObject) {
0 ignored issues
show
introduced by
$object is always a sub-type of SilverStripe\ORM\DataObject.
Loading history...
112
            user_error('Please provide a DataObject, you have provided a: ' . get_class($object));
113
        }
114
        $this->object = $object;
115
    }
116
117
    public function setLinkMethod(string $s): self
118
    {
119
        $this->linkMethod = $s;
120
        return $this;
121
    }
122
123
    public function setTitleMethod(string $s): self
124
    {
125
        $this->titleMethod = $s;
126
        return $this;
127
    }
128
129
    public function setImageMethods(string $a): self
130
    {
131
        $this->imageMethods = $a;
132
        return $this;
133
    }
134
135
    public function setDescriptionMethod(string $s): self
136
    {
137
        $this->descriptionMethod = $s;
138
        return $this;
139
    }
140
141
    public function setHashTags(array $a): self
142
    {
143
        $this->hashTagsArray = $a;
0 ignored issues
show
Bug Best Practice introduced by
The property hashTagsArray does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
144
        return $this;
145
    }
146
147
    public function setMentions(array $a): self
148
    {
149
        $this->mentionsArray = $a;
150
        return $this;
151
    }
152
153
    public function setVias(array $a): self
154
    {
155
        $this->viasArray = $a;
156
        return $this;
157
    }
158
159
    public function getWindowPopupHtml(): string
160
    {
161
        $width = $this->Config()->get('pop_up_window_width');
162
        $height = $this->Config()->get('pop_up_window_height');
163
        $html = <<<html
164
                    onclick="window.open(this.href,'Share','width=${width},height=${height},toolbar=no,menubar=no,location=no,status=no,scrollbars=no,resizable=yes'); return '';"
165
html;
166
        $html = preg_replace('!\s+!', ' ', $html);
167
168
        return DBField::create_field('HTMLText', $html);
169
    }
170
171
    /**
172
     * return of ShareThisLinks.
173
     * @param string $customDescription   e.g. foo bar cool stuff
174
     * @return ArrayList
175
     */
176
    public function ShareThisLinks(?string $customDescription = ''): ArrayList
177
    {
178
        $arrayList = ArrayList::create();
179
        $options = array_keys($this->config()->get('casting')); //$this->config()->get('casting') ???
180
        foreach ($options as $option) {
181
            $className = str_replace('ShareLink', '', $option);
182
            $className = strtolower($className);
183
            $method = 'get' . $option;
184
            $arrayList->push(
185
                ArrayData::create(
186
                    [
187
                        'Class' => $className,
188
                        'Link' => $this->{$method}($customDescription),
189
                    ]
190
                )
191
            );
192
        }
193
194
        return $arrayList;
195
    }
196
197
    /**
198
     * ALIAS
199
     * Generate a URL to share this content on Facebook.
200
     * @param string $customDescription   e.g. foo bar cool stuff
201
     * @return string
202
     */
203
    public function FacebookShareLink(?string $customDescription = ''): string
204
    {
205
        return $this->getFacebookShareLink($customDescription);
206
    }
207
208
    /**
209
     * Generate a URL to share this content on Facebook.
210
     * @param string $customDescription   e.g. foo bar cool stuff
211
     * https://www.facebook.com/dialog/feed?
212
     *  &link=URL_HERE
213
     *  &picture=IMAGE_LINK_HERE
214
     *  &name=TITLE_HERE
215
     *  &caption=%20
216
     *  &description=DESCRIPTION_HERE
217
     *  &redirect_uri=http%3A%2F%2Fwww.facebook.com%2F
218
     * @return string
219
     */
220
    public function getFacebookShareLink(?string $customDescription = ''): string
221
    {
222
        return $this->pageURL ?
223
            'https://www.facebook.com/sharer/sharer.php?u=' . $this->pageURL . '&t=' . $this->title . ''
224
            :
225
            '';
226
    }
227
228
    /**
229
     * ALIAS
230
     * Generate a URL to share this content on Twitter
231
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
232
     * @param string $customDescription   e.g. foo bar cool stuff
233
     * @return string
234
     */
235
    public function TwitterShareLink(?string $customDescription = ''): string
236
    {
237
        return $this->getTwitterShareLink($customDescription);
238
    }
239
240
    /**
241
     * Generate a URL to share this content on Twitter
242
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
243
     * example: https://twitter.com/intent/tweet?
244
     *  &source=http%3A%2F%2Fsunnysideup.co.nz
245
     *  &text=test:%20http%3A%2F%2Fsunnysideup.co.nz
246
     *  &via=foobar
247
     * @param string $customDescription   e.g. foo bar cool stuff
248
     * @return string
249
     */
250
    public function getTwitterShareLink(?string $customDescription = ''): string
251
    {
252
        extract($this->getShareThisArray($customDescription));
253
254
        return $this->pageURL ?
255
            'https://twitter.com/intent/tweet?source=' . $this->pageURL . '&text=' . $this->titleFull . '' . urlencode(': ') . $this->pageURL
256
            :
257
            '';
258
    }
259
260
    /**
261
     * ALIAS
262
     * Generate a URL to share this content on Twitter
263
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
264
     * @param string $customDescription   e.g. foo bar cool stuff
265
     * @return string
266
     */
267
    public function LinkedInShareLink(?string $customDescription = ''): string
268
    {
269
        return $this->getLinkedInShareLink($customDescription);
270
    }
271
272
    /**
273
     * Generate a URL to share this content on Twitter
274
     * Specs: ???
275
     * example: https://www.linkedin.com/shareArticle?
276
     * mini=true&url=http://www.cnn.com&title=&summary=chek this out&source=
277
     * @param string $customDescription   e.g. foo bar cool stuff
278
     * @return string
279
     */
280
    public function getLinkedInShareLink(?string $customDescription = ''): string
281
    {
282
        extract($this->getShareThisArray($customDescription));
283
284
        return $this->pageURL ?
285
           'https://www.linkedin.com/shareArticle?mini=true&url=' . $this->pageURL . '&summary=' . $this->titleFull . ''
286
           :
287
           '';
288
    }
289
290
    /**
291
     * ALIAS
292
     * Generate a URL to share this content on Twitter
293
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
294
     * @param string $customDescription   e.g. foo bar cool stuff
295
     * @return string
296
     */
297
    public function TumblrShareLink(?string $customDescription = ''): string
298
    {
299
        return $this->getTumblrShareLink($customDescription);
300
    }
301
302
    /**
303
     * Generate a URL to share this content on Twitter
304
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
305
     * @param string $customDescription   e.g. foo bar cool stuff
306
     * @return string
307
     */
308
    public function getTumblrShareLink(?string $customDescription = '')
309
    {
310
        extract($this->getShareThisArray($customDescription));
311
312
        return $this->pageURL ?
313
            'http://www.tumblr.com/share/link?url=' . $this->pageURL . '&name=' . $this->title . '&description=' . $this->description . ''
314
            :
315
            '';
316
    }
317
318
    /**
319
     * ALIAS
320
     * Generate a URL to share this content on Twitter
321
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
322
     * @param string $customDescription   e.g. foo bar cool stuff
323
     * @return string
324
     */
325
    public function PinterestShareLink(?string $customDescription = ''): string
326
    {
327
        return $this->getPinterestShareLink($customDescription);
328
    }
329
330
    /**
331
     * Generate a URL to share this content on Twitter
332
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
333
     * @param string $customDescription   e.g. foo bar cool stuff
334
     * @return string
335
     */
336
    public function getPinterestShareLink(?string $customDescription = ''): string
337
    {
338
        extract($this->getShareThisArray($customDescription));
339
340
        return $this->pageURL ?
341
            'http://pinterest.com/pin/create/button/?url=' . $this->pageURL . '&description=' . $this->description . '&media=' . $this->media . ''
342
            :
343
            '';
344
    }
345
346
    /**
347
     * ALIAS
348
     * Generate a 'mailto' URL to share this content via Email.
349
     * @param string $customDescription   e.g. foo bar cool stuff
350
     * @return string
351
     */
352
    public function EmailShareLink(?string $customDescription = ''): string
353
    {
354
        return $this->getEmailShareLink($customDescription);
355
    }
356
357
    /**
358
     * Generate a 'mailto' URL to share this content via Email.
359
     * @param string $customDescription   e.g. foo bar cool stuff
360
     * @return string
361
     */
362
    public function getEmailShareLink(?string $customDescription = ''): string
363
    {
364
        extract($this->getShareThisArray($customDescription));
365
366
        return $this->pageURL ? 'mailto:?subject=' . $this->title . '&body=' . $this->pageURL . '' : '';
367
    }
368
369
    /**
370
     * ALIAS
371
     * Generate a URL to share this content on Twitter
372
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
373
     * @param string $customDescription   e.g. foo bar cool stuff
374
     * @return string
375
     */
376
    public function RedditShareLink(?string $customDescription = ''): string
377
    {
378
        return $this->getRedditShareLink($customDescription);
379
    }
380
381
    /**
382
     * Generate a URL to share this content on Twitter
383
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
384
     * @param string $customDescription   e.g. foo bar cool stuff
385
     * @return string
386
     */
387
    public function getRedditShareLink(?string $customDescription = ''): string
388
    {
389
        extract($this->getShareThisArray($customDescription));
390
391
        return $this->pageURL ? 'http://reddit.com/submit?url=' . $this->pageURL . '&title=' . $this->title . '' : '';
392
    }
393
394
    /**
395
     * @param string $customDescription   e.g. foo bar cool stuff
396
     *
397
     * @return array
398
     */
399
    public function getShareThisArray(?string $customDescription = ''): array
400
    {
401
        if (! isset(self::$cacheGetShareThisArray[$this->object->ID])) {
402
            //1. link
403
            $this->link = $this->shareThisLinkField();
0 ignored issues
show
Bug Best Practice introduced by
The property link does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
404
405
            $this->title = $this->shareThisTitleField();
406
407
            $this->media = $this->shareThisMediaField();
408
409
            $this->description = $this->shareThisDescriptionField($customDescription);
410
411
            $this->hashTags = $this->getValuesFromArrayToString('hashTagsArray', 'hash_tags', '#');
412
            $this->mentions = $this->getValuesFromArrayToString('mentionsArray', 'mentions', '@');
413
            $this->vias = $this->getValuesFromArrayToString('viasArray', 'vias', '@');
414
            $this->titleFull = trim($this->mentions . ' ' . $this->title . ' ' . $this->hashTags . ' ' . $this->vias);
415
            $this->descriptionFull = trim($this->mentions . ' ' . $this->description . ' ' . $this->hashTags . ' ' . $this->vias);
416
417
            //return ...
418
            self::$cacheGetShareThisArray[$this->object->ID] = [
419
                'pageURL' => rawurlencode($this->link),
420
                'title' => rawurlencode($this->title),
421
                'titleFull' => rawurlencode($this->titleFull),
422
                'media' => rawurlencode($this->media),
423
                'description' => rawurlencode($this->description),
424
                'descriptionFull' => rawurlencode($this->descriptionFull),
425
                'hashTags' => rawurlencode($this->hashTags),
426
                'mentions' => rawurlencode($this->mentions),
427
                'vias' => rawurlencode($this->vias),
428
            ];
429
        }
430
431
        return self::$cacheGetShareThisArray[$this->object->ID];
432
    }
433
434
    /**
435
     * @param string $imageMethod   e.g. MyImage
436
     * @param bool $useImageTitle  if set to false, it will use the page title as the image title
437
     *
438
     * @return string
439
     */
440
    public function PinterestLinkForSpecificImage(string $imageMethod, ?bool $useImageTitle = false): string
441
    {
442
        return $this->getPinterestLinkForSpecificImage(
443
            $imageMethod,
444
            $useImageTitle
445
        );
446
    }
447
448
    public function getPinterestLinkForSpecificImage(string $imageMethod, ?bool $useImageTitle = false): string
449
    {
450
        if ($this->object && $this->object->hasMethod($imageMethod)) {
451
            $image = $this->object->{$imageMethod}();
452
            if ($image && $image->exists()) {
453
                if ($useImageTitle) {
454
                    $imageTitle = $image->Title;
455
                } else {
456
                    $imageTitle = $this->object->Title;
457
                }
458
                return 'http://pinterest.com/pin/create/button/'
459
                    . '?url=' . urlencode($this->object->AbsoluteLink()) . '&amp;'
460
                    . 'description=' . urlencode($imageTitle) . '&amp;'
461
                    . 'media=' . urlencode($image->AbsoluteLink());
462
            }
463
        }
464
        return '';
465
    }
466
467
    protected function getValuesFromArrayToString(string $variable, string $staticVariable, ?string $prepender = '@')
468
    {
469
        if (! empty($this->{$variable})) {
470
            $a = $this->{$variable};
471
        } else {
472
            $a = $this->Config()->get($staticVariable);
473
        }
474
        $str = '';
475
        if (is_array($a) && count($a)) {
476
            $str = $prepender . implode(' ' . $prepender, $a);
477
        }
478
479
        return trim($str);
480
    }
481
482
    private function shareThisLinkField(): string
483
    {
484
        return $this->shareThisFieldAsString($this->linkMethod);
485
    }
486
487
    private function shareThisTitleField(): string
488
    {
489
        return $this->shareThisFieldAsString($this->titleMethod);
490
    }
491
492
    private function shareThisFieldAsString(string $field): string
493
    {
494
        $value = '';
495
        if ($this->object->hasMethod($field)) {
496
            $value = $this->object->{$field}();
497
        } elseif (isset($this->object->{$field})) {
498
            $value = $this->object->{$field};
499
        }
500
501
        return (string) $value;
502
    }
503
504
    private function shareThisMediaField(): string
505
    {
506
        $media = '';
507
        $imageMethods = $this->imageMethods;
508
        if (is_array($imageMethods) && count($imageMethods)) {
509
            //do nothing
510
        } else {
511
            $imageMethods = Config::inst()->get(
512
                'ShareThisSimpleProvider',
513
                'image_methods'
514
            );
515
        }
516
        if (is_array($imageMethods) && count($imageMethods)) {
517
            foreach ($imageMethods as $imageMethod) {
518
                if ($this->object->hasMethod($imageMethod)) {
519
                    $imageField = $imageMethod . 'ID';
520
                    if ($this->{$imageField}) {
521
                        $image = $this->object->{$imageMethod}();
522
                        if ($image && $image->exists()) {
523
                            $media = $image->AbsoluteLink();
524
                            break;
525
                        }
526
                    }
527
                }
528
            }
529
        }
530
531
        return $media;
532
    }
533
534
    private function shareThisDescriptionField(?string $customDescription = ''): string
535
    {
536
        if ($customDescription) {
537
            $description = $customDescription;
538
        } else {
539
            $description = '';
540
            if ($descriptionMethod = $this->descriptionMethod) {
541
                //do nothing
542
            } else {
543
                $descriptionMethod = Config::inst()->get(
544
                    'ShareThisSimpleProvider',
545
                    'description_method'
546
                );
547
            }
548
            if ($descriptionMethod) {
549
                $description = $this->shareThisFieldAsString($descriptionMethod);
550
            }
551
        }
552
553
        return (string) $description;
554
    }
555
}
556