Passed
Push — master ( af2b13...78cdc3 )
by Nicolaas
07:47
created

getPinterestLinkForSpecificImage()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 12
c 3
b 0
f 0
nc 4
nop 2
dl 0
loc 17
rs 8.8333
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
        $this->getShareThisArray($customDescription);
223
        return $this->pageURL ?
224
            'https://www.facebook.com/sharer/sharer.php?u=' . $this->pageURL . '&t=' . $this->title . ''
225
            :
226
            '';
227
    }
228
229
    /**
230
     * ALIAS
231
     * Generate a URL to share this content on Twitter
232
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
233
     * @param string $customDescription   e.g. foo bar cool stuff
234
     * @return string
235
     */
236
    public function TwitterShareLink(?string $customDescription = ''): string
237
    {
238
        return $this->getTwitterShareLink($customDescription);
239
    }
240
241
    /**
242
     * Generate a URL to share this content on Twitter
243
     * Specs: https://dev.twitter.com/web/tweet-button/web-intent.
244
     * example: https://twitter.com/intent/tweet?
245
     *  &source=http%3A%2F%2Fsunnysideup.co.nz
246
     *  &text=test:%20http%3A%2F%2Fsunnysideup.co.nz
247
     *  &via=foobar
248
     * @param string $customDescription   e.g. foo bar cool stuff
249
     * @return string
250
     */
251
    public function getTwitterShareLink(?string $customDescription = ''): string
252
    {
253
        $this->getShareThisArray($customDescription);
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
        $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
        $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
        $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
        $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
        $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
        $cacheKey = $this->object->ID . '_' . preg_replace('/[^A-Za-z0-9]/', '_', $customDescription);
402
        if (! isset(self::$cacheGetShareThisArray[$cacheKey])) {
403
            //1. link
404
            $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...
405
406
            $this->title = $this->shareThisTitleField();
407
408
            $this->media = $this->shareThisMediaField();
409
410
            $this->description = $this->shareThisDescriptionField($customDescription);
411
412
            $this->hashTags = $this->getValuesFromArrayToString('hashTagsArray', 'hash_tags', '#');
413
            $this->mentions = $this->getValuesFromArrayToString('mentionsArray', 'mentions', '@');
414
            $this->vias = $this->getValuesFromArrayToString('viasArray', 'vias', '@');
415
            $this->titleFull = trim($this->mentions . ' ' . $this->title . ' ' . $this->hashTags . ' ' . $this->vias);
416
            $this->descriptionFull = trim($this->mentions . ' ' . $this->description . ' ' . $this->hashTags . ' ' . $this->vias);
417
418
            //return ...
419
            self::$cacheGetShareThisArray[$cacheKey] = [
420
                'pageURL' => rawurlencode($this->link),
421
                'title' => rawurlencode($this->title),
422
                'titleFull' => rawurlencode($this->titleFull),
423
                'media' => rawurlencode($this->media),
424
                'description' => rawurlencode($this->description),
425
                'descriptionFull' => rawurlencode($this->descriptionFull),
426
                'hashTags' => rawurlencode($this->hashTags),
427
                'mentions' => rawurlencode($this->mentions),
428
                'vias' => rawurlencode($this->vias),
429
            ];
430
        }
431
        foreach (self::$cacheGetShareThisArray[$cacheKey] as $field => $value) {
432
            $this->{$field} = $value;
433
        }
434
435
        return self::$cacheGetShareThisArray[$cacheKey];
436
    }
437
438
    /**
439
     * @param string $imageMethod   e.g. MyImage
440
     * @param bool $useImageTitle  if set to false, it will use the page title as the image title
441
     *
442
     * @return string
443
     */
444
    public function PinterestLinkForSpecificImage(string $imageMethod, ?bool $useImageTitle = false): string
445
    {
446
        return $this->getPinterestLinkForSpecificImage(
447
            $imageMethod,
448
            $useImageTitle
449
        );
450
    }
451
452
    public function getPinterestLinkForSpecificImage(string $imageMethod, ?bool $useImageTitle = false): string
453
    {
454
        if ($this->object && $this->object->exists() && $this->object->hasMethod($imageMethod)) {
455
            $image = $this->object->{$imageMethod}();
456
            if ($image && $image->exists()) {
457
                if ($useImageTitle) {
458
                    $imageTitle = $image->Title;
459
                } else {
460
                    $imageTitle = $this->object->Title;
461
                }
462
                return 'http://pinterest.com/pin/create/button/'
463
                    . '?url=' . urlencode($this->object->AbsoluteLink()) . '&amp;'
464
                    . 'description=' . urlencode($imageTitle) . '&amp;'
465
                    . 'media=' . urlencode($image->AbsoluteLink());
466
            }
467
        }
468
        return '';
469
    }
470
471
    protected function getValuesFromArrayToString(string $variable, string $staticVariable, ?string $prepender = '@')
472
    {
473
        if (! empty($this->{$variable})) {
474
            $a = $this->{$variable};
475
        } else {
476
            $a = $this->Config()->get($staticVariable);
477
        }
478
        $str = '';
479
        if (is_array($a) && count($a)) {
480
            $str = $prepender . implode(' ' . $prepender, $a);
481
        }
482
483
        return trim($str);
484
    }
485
486
    private function shareThisLinkField(): string
487
    {
488
        return $this->shareThisFieldAsString($this->linkMethod);
489
    }
490
491
    private function shareThisTitleField(): string
492
    {
493
        return $this->shareThisFieldAsString($this->titleMethod);
494
    }
495
496
    private function shareThisFieldAsString(string $field): string
497
    {
498
        $value = '';
499
        if ($this->object->hasMethod($field)) {
500
            $value = $this->object->{$field}();
501
        } elseif (isset($this->object->{$field})) {
502
            $value = $this->object->{$field};
503
        }
504
505
        return (string) $value;
506
    }
507
508
    private function shareThisMediaField(): string
509
    {
510
        $media = '';
511
        $imageMethods = $this->imageMethods;
512
        if (is_array($imageMethods) && count($imageMethods)) {
513
            //do nothing
514
        } else {
515
            $imageMethods = Config::inst()->get(
516
                'ShareThisSimpleProvider',
517
                'image_methods'
518
            );
519
        }
520
        if (is_array($imageMethods) && count($imageMethods)) {
521
            foreach ($imageMethods as $imageMethod) {
522
                if ($this->object->hasMethod($imageMethod)) {
523
                    $imageField = $imageMethod . 'ID';
524
                    if ($this->{$imageField}) {
525
                        $image = $this->object->{$imageMethod}();
526
                        if ($image && $image->exists()) {
527
                            $media = $image->AbsoluteLink();
528
                            break;
529
                        }
530
                    }
531
                }
532
            }
533
        }
534
535
        return $media;
536
    }
537
538
    private function shareThisDescriptionField(?string $customDescription = ''): string
539
    {
540
        if ($customDescription) {
541
            $description = $customDescription;
542
        } else {
543
            $description = '';
544
            if ($descriptionMethod = $this->descriptionMethod) {
545
                //do nothing
546
            } else {
547
                $descriptionMethod = Config::inst()->get(
548
                    'ShareThisSimpleProvider',
549
                    'description_method'
550
                );
551
            }
552
            if ($descriptionMethod) {
553
                $description = $this->shareThisFieldAsString($descriptionMethod);
554
            }
555
        }
556
557
        return (string) $description;
558
    }
559
}
560