Passed
Push — master ( d52e8c...6f57e9 )
by Nicolaas
03:52
created

SpecificImage()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 7
eloc 8
c 5
b 0
f 0
nc 4
nop 2
dl 0
loc 14
rs 8.8333
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
    ];
115
116
    /**
117
     * @param DataObject $object
118
     */
119
    public function __construct($object)
120
    {
121
        parent::__construct();
122
        $this->object = $object;
123
    }
124
125
    public function setLinkMethod(string $s): self
126
    {
127
        $this->linkMethod = $s;
128
129
        return $this;
130
    }
131
132
    public function setTitleMethod(string $s): self
133
    {
134
        $this->titleMethod = $s;
135
136
        return $this;
137
    }
138
139
    public function setImageMethods(string $a): self
140
    {
141
        $this->imageMethods = $a;
142
143
        return $this;
144
    }
145
146
    public function setDescriptionMethod(string $s): self
147
    {
148
        $this->descriptionMethod = $s;
149
150
        return $this;
151
    }
152
153
    public function setHashTags(array $a): self
154
    {
155
        $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...
156
157
        return $this;
158
    }
159
160
    public function setMentions(array $a): self
161
    {
162
        $this->mentionsArray = $a;
163
164
        return $this;
165
    }
166
167
    public function setVias(array $a): self
168
    {
169
        $this->viasArray = $a;
170
171
        return $this;
172
    }
173
174
    public function getWindowPopupHtml(): DBHTMLText
175
    {
176
        $width = $this->Config()->get('pop_up_window_width');
177
        $height = $this->Config()->get('pop_up_window_height');
178
        $html = <<<html
179
                    onclick="
180
                        window.open(this.href,'Share','width={$width},height={$height},toolbar=no,menubar=no,location=no,status=no,scrollbars=no,resizable');
181
                        return false;
182
                    "
183
html;
184
        $html = preg_replace('#\s+#', ' ', $html);
185
186
        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...
187
    }
188
189
    /**
190
     * return of ShareThisLinks.
191
     *
192
     * @param string $customDescription e.g. foo bar cool stuff
193
     */
194
    public function ShareThisLinks(?string $customDescription = ''): ArrayList
195
    {
196
        $arrayList = ArrayList::create();
197
        $options = array_keys(Config::inst()->get(ShareThisSimpleProvider::class, 'casting', Config::UNINHERITED));
198
        $icons = $this->config()->get('icon_links');
199
        foreach ($options as $option) {
200
            $className = str_replace('ShareLink', '', (string) $option);
201
            $className = strtolower($className);
202
            $icon = '';
203
            if (! empty($icons[$className])) {
204
                $urlLink = $icons[$className];
205
                $url = ModuleResourceLoader::resourceURL($urlLink);
206
                $icon = DBField::create_field('HTMLText', '<img src="' . $url . '" alt="' . $option . '" />');
207
            }
208
            $method = 'get' . $option;
209
            $arrayList->push(
210
                ArrayData::create(
211
                    [
212
                        'Class' => $className,
213
                        'Link' => $this->{$method}($customDescription),
214
                        'Icon' => $icon,
215
                    ]
216
                )
217
            );
218
        }
219
220
        return $arrayList;
221
    }
222
223
224
    /**
225
     * Generate a URL to share this content on Facebook.
226
     *
227
     * @param string $customDescription e.g. foo bar cool stuff
228
     *                                  https://www.facebook.com/dialog/feed?
229
     *                                  &link=URL_HERE
230
     *                                  &picture=IMAGE_LINK_HERE
231
     *                                  &name=TITLE_HERE
232
     *                                  &caption=%20
233
     *                                  &description=DESCRIPTION_HERE
234
     *                                  &redirect_uri=http%3A%2F%2Fwww.facebook.com%2F
235
     */
236
    public function getFacebookShareLink(?string $customDescription = ''): string
237
    {
238
        $this->getShareThisArray($customDescription);
239
240
        return '' === $this->pageURL ? '' :
241
            'https://www.facebook.com/sharer/sharer.php?u=' . $this->pageURL;
242
    }
243
244
245
    /**
246
     * Generate a URL to share this content on Twitter
247
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
248
     * example: https://twitter.com/intent/tweet?
249
     *  &source=http%3A%2F%2Fsunnysideup.co.nz
250
     *  &text=test:%20http%3A%2F%2Fsunnysideup.co.nz
251
     *  &via=foobar.
252
     *
253
     * @param string $customDescription e.g. foo bar cool stuff
254
     */
255
    public function getBlueSkyShareLink(?string $customDescription = ''): string
256
    {
257
        $this->getShareThisArray($customDescription);
258
259
        return '' === $this->pageURL ? '' :
260
            'https://bsky.app/intent/compose?text=' . ($this->titleFull) . '&url=' . $this->pageURL;
261
    }
262
263
    /**
264
     * Generate a URL to share this content on Twitter
265
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
266
     * example: https://twitter.com/intent/tweet?
267
     *  &source=http%3A%2F%2Fsunnysideup.co.nz
268
     *  &text=test:%20http%3A%2F%2Fsunnysideup.co.nz
269
     *  &via=foobar.
270
     *
271
     * @param string $customDescription e.g. foo bar cool stuff
272
     */
273
    public function getTwitterShareLink(?string $customDescription = ''): string
274
    {
275
        $this->getShareThisArray($customDescription);
276
277
        return '' === $this->pageURL ? '' :
278
            'https://x.com/intent/tweet?text=' . ($this->titleFull) . '&url=' . $this->pageURL;
279
    }
280
281
282
    /**
283
     * Generate a URL to share this content on Twitter
284
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
285
     *
286
     * @param string $customDescription e.g. foo bar cool stuff
287
     *
288
     * @return string
289
     */
290
    public function getTumblrShareLink(?string $customDescription = '')
291
    {
292
        $this->getShareThisArray($customDescription);
293
294
        return '' === $this->pageURL ? '' :
295
            'https://www.tumblr.com/share/link?url=' . ($this->pageURL) . '&name=' . ($this->title) . '&description=' . ($this->description);
296
    }
297
298
299
    /**
300
     * Generate a URL to share this content on Twitter
301
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
302
     *
303
     * @param string $customDescription e.g. foo bar cool stuff
304
     */
305
    public function getPinterestShareLink(?string $customDescription = ''): string
306
    {
307
        $this->getShareThisArray($customDescription);
308
309
        return '' === $this->pageURL ? '' :
310
            'https://pinterest.com/pin/create/button/?url=' . $this->pageURL . '&description=' . $this->description . '&media=' . $this->media . '';
311
    }
312
313
314
315
    /**
316
     * Generate a URL to share this content on Twitter
317
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
318
     *
319
     * @param string $customDescription e.g. foo bar cool stuff
320
     */
321
    public function getRedditShareLink(?string $customDescription = ''): string
322
    {
323
        $this->getShareThisArray($customDescription);
324
325
        return '' === $this->pageURL ? '' :
326
            'https://reddit.com/submit?url=' . $this->pageURL . '&title=' . $this->title;
327
    }
328
329
    /**
330
     * Generate a URL to share this content on Twitter
331
     * Specs: ???
332
     * example: https://www.linkedin.com/shareArticle?
333
     * mini=true&url=https://www.cnn.com&title=&summary=chek this out&source=.
334
     *
335
     * @param string $customDescription e.g. foo bar cool stuff
336
     */
337
    public function getLinkedInShareLink(?string $customDescription = ''): string
338
    {
339
        $this->getShareThisArray($customDescription);
340
341
        return '' === $this->pageURL ? '' :
342
            'https://www.linkedin.com/shareArticle?mini=true&url=' . $this->pageURL . '&summary=' . $this->titleFull . '';
343
    }
344
345
    /**
346
     * Generate a 'mailto' URL to share this content via Email.
347
     *
348
     * @param string $customDescription e.g. foo bar cool stuff
349
     */
350
    public function getEmailShareLink(?string $customDescription = ''): string
351
    {
352
        $this->getShareThisArray($customDescription);
353
354
        return '' === $this->pageURL ? '' :
355
            'mailto:?subject=' . $this->title . ': ' . $this->pageURL  . '&body=' . $this->pageURL;
356
    }
357
358
    /**
359
     * Generate a URL to share this content via SMS.
360
     *
361
     * @param string $customDescription e.g. foo bar cool stuff
362
     */
363
    public function getSmsShareLink(?string $customDescription = ''): string
364
    {
365
        $this->getShareThisArray($customDescription);
366
367
        return '' === $this->pageURL ? '' :
368
            'sms:?body=' . ($this->titleFull . ' ' . $this->pageURL);
369
    }
370
    /**
371
     * Generate a URL to share this content on WhatsApp.
372
     *
373
     * @param string $customDescription e.g. foo bar cool stuff
374
     */
375
    public function getWhatsAppShareLink(?string $customDescription = ''): string
376
    {
377
        $this->getShareThisArray($customDescription);
378
379
        return '' === $this->pageURL ? '' :
380
            'https://api.whatsapp.com/send?text=' . ($this->titleFull . ' ' . $this->pageURL);
381
    }
382
383
    /**
384
     * Generate a URL to share this content on Snapchat.
385
     *
386
     * @param string $customDescription e.g. foo bar cool stuff
387
     */
388
    public function getSnapchatShareLink(?string $customDescription = ''): string
389
    {
390
        $this->getShareThisArray($customDescription);
391
392
        return '' === $this->pageURL ? '' :
393
            'https://www.snapchat.com/share?url=' . $this->pageURL . '&text=' . $this->titleFull;
394
    }
395
396
397
398
    /**
399
     * Generate a URL to share this content on Signal.
400
     *
401
     * @param string $customDescription e.g. foo bar cool stuff
402
     */
403
    public function getSignalShareLink(?string $customDescription = ''): string
404
    {
405
        $this->getShareThisArray($customDescription);
406
407
        return '' === $this->pageURL ? '' :
408
            'https://signal.me/#p/' . ($this->titleFull . ' ' . $this->pageURL);
409
    }
410
411
412
    public function getPrintPageLink(): string
413
    {
414
        return 'javascript:window.print();';
415
    }
416
417
418
    /**
419
     * @param string $customDescription e.g. foo bar cool stuff
420
     */
421
    public function getShareThisArray(?string $customDescription = ''): array
422
    {
423
        $cacheKey = $this->object->ID . '_' . preg_replace('#[^A-Za-z0-9]#', '_', $customDescription);
424
        if (! isset(self::$cacheGetShareThisArray[$cacheKey])) {
425
            //1. link
426
            $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...
427
428
            $this->title = $this->shareThisTitleField();
429
430
            $this->media = $this->shareThisMediaField();
431
432
            $this->description = $this->shareThisDescriptionField($customDescription);
433
434
            $this->hashTags = $this->getValuesFromArrayToString('hashTagsArray', 'hash_tags', '#');
435
            $this->mentions = $this->getValuesFromArrayToString('mentionsArray', 'mentions');
436
            $this->vias = $this->getValuesFromArrayToString('viasArray', 'vias');
437
            $this->titleFull = trim($this->mentions . ' ' . $this->title . ' ' . $this->hashTags . ' ' . $this->vias);
438
            $this->descriptionFull = trim($this->mentions . ' ' . $this->description . ' ' . $this->hashTags . ' ' . $this->vias);
439
440
            //return ...
441
            self::$cacheGetShareThisArray[$cacheKey] = [
442
                'pageURL' => rawurlencode($this->link),
443
                'title' => rawurlencode($this->title),
444
                'titleFull' => rawurlencode($this->titleFull),
445
                'media' => rawurlencode($this->media),
446
                'description' => rawurlencode($this->description),
447
                'descriptionFull' => rawurlencode($this->descriptionFull),
448
                'hashTags' => rawurlencode($this->hashTags),
449
                'mentions' => rawurlencode($this->mentions),
450
                'vias' => rawurlencode($this->vias),
451
            ];
452
        }
453
454
        foreach (self::$cacheGetShareThisArray[$cacheKey] as $field => $value) {
455
            $this->{$field} = $value;
456
        }
457
458
        return self::$cacheGetShareThisArray[$cacheKey];
459
    }
460
461
462
    protected function getValuesFromArrayToString(string $variable, string $staticVariable, ?string $prepender = '@')
463
    {
464
        $a = empty($this->{$variable}) ? $this->Config()->get($staticVariable) : $this->{$variable};
465
        $str = '';
466
        if (is_array($a) && count($a)) {
467
            $str = $prepender . implode(' ' . $prepender, $a);
468
        }
469
470
        return trim($str);
471
    }
472
473
    private function shareThisLinkField(): string
474
    {
475
        return $this->shareThisFieldAsString($this->linkMethod);
476
    }
477
478
    private function shareThisTitleField(): string
479
    {
480
        return $this->shareThisFieldAsString($this->titleMethod);
481
    }
482
483
    private function shareThisFieldAsString(string $field): string
484
    {
485
        $value = '';
486
        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

486
        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...
487
            $value = $this->object->{$field}();
488
        } elseif (isset($this->object->{$field})) {
489
            $value = $this->object->{$field};
490
        }
491
492
        return (string) $value;
493
    }
494
495
    private function shareThisMediaField(): string
496
    {
497
        $media = '';
498
        $imageMethods = $this->imageMethods;
499
        if (is_array($imageMethods) && count($imageMethods)) {
500
            //do nothing
501
        } else {
502
            $imageMethods = Config::inst()->get(
503
                'ShareThisSimpleProvider',
504
                'image_methods'
505
            );
506
        }
507
508
        if (is_array($imageMethods) && count($imageMethods)) {
509
            foreach ($imageMethods as $imageMethod) {
510
                if ($this->object->hasMethod($imageMethod)) {
511
                    $imageField = $imageMethod . 'ID';
512
                    if ($this->{$imageField}) {
513
                        $image = $this->object->{$imageMethod}();
514
                        if ($image && $image->exists()) {
515
                            $media = $image->AbsoluteLink();
516
517
                            break;
518
                        }
519
                    }
520
                }
521
            }
522
        }
523
524
        return $media;
525
    }
526
527
    private function shareThisDescriptionField(?string $customDescription = ''): string
528
    {
529
        if ($customDescription) {
530
            $description = $customDescription;
531
        } else {
532
            $description = '';
533
            $descriptionMethod = $this->descriptionMethod;
534
            if (! $descriptionMethod) {
535
                $descriptionMethod = Config::inst()->get(
536
                    'ShareThisSimpleProvider',
537
                    'description_method'
538
                );
539
            }
540
541
            if ($descriptionMethod) {
542
                $description = $this->shareThisFieldAsString($descriptionMethod);
543
            }
544
        }
545
546
        return $description;
547
    }
548
}
549