Passed
Push — master ( 52b355...d62036 )
by Nicolaas
03:50
created

ShareThisSimpleProvider::getBlueSkyShareLink()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

506
        if ($this->object->/** @scrutinizer ignore-call */ hasMethod($field)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
507
            $value = $this->object->{$field}();
508
        } elseif (isset($this->object->{$field})) {
509
            $value = $this->object->{$field};
510
        }
511
512
        return (string) $value;
513
    }
514
515
    private function shareThisMediaField(): string
516
    {
517
        $media = '';
518
        $imageMethods = $this->imageMethods;
519
        if (is_array($imageMethods) && count($imageMethods)) {
520
            //do nothing
521
        } else {
522
            $imageMethods = Config::inst()->get(
523
                'ShareThisSimpleProvider',
524
                'image_methods'
525
            );
526
        }
527
528
        if (is_array($imageMethods) && count($imageMethods)) {
529
            foreach ($imageMethods as $imageMethod) {
530
                if ($this->object->hasMethod($imageMethod)) {
531
                    $imageField = $imageMethod . 'ID';
532
                    if ($this->{$imageField}) {
533
                        $image = $this->object->{$imageMethod}();
534
                        if ($image && $image->exists()) {
535
                            $media = $image->AbsoluteLink();
536
537
                            break;
538
                        }
539
                    }
540
                }
541
            }
542
        }
543
544
        return $media;
545
    }
546
547
    private function shareThisDescriptionField(?string $customDescription = ''): string
548
    {
549
        if ($customDescription) {
550
            $description = $customDescription;
551
        } else {
552
            $description = '';
553
            $descriptionMethod = $this->descriptionMethod;
554
            if (! $descriptionMethod) {
555
                $descriptionMethod = Config::inst()->get(
556
                    'ShareThisSimpleProvider',
557
                    'description_method'
558
                );
559
            }
560
561
            if ($descriptionMethod) {
562
                $description = $this->shareThisFieldAsString($descriptionMethod);
563
            }
564
        }
565
566
        return $description;
567
    }
568
}
569