Passed
Push — develop ( f1d4ab...4ae802 )
by Martin
01:16
created

TwitterOAuth07::prepareStatus()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MartinGeorgiev\SocialPost\Provider\Twitter;
6
7
use Abraham\TwitterOAuth\TwitterOAuth;
8
use MartinGeorgiev\SocialPost\Provider\FailureWhenPublishingSocialPost;
9
use MartinGeorgiev\SocialPost\Provider\SocialNetworkPublisher;
10
use Throwable;
11
12
/**
13
 * Provider for publishing on a Twitter page.
14
 * Uses TwitterOAuth v0.7
15
 * @see https://github.com/abraham/twitteroauth
16
 *
17
 * @since 1.0.0
18
 * @author Martin Georgiev <[email protected]>
19
 * @license https://opensource.org/licenses/MIT MIT
20
 * @link https://github.com/martin-georgiev/social-post-bundle Package's homepage
21
 */
22
class TwitterOAuth07 implements SocialNetworkPublisher
23
{
24
    /**
25
     * @var TwitterOAuth
26
     */
27
    private $twitter;
28
29
    /**
30
     * @param TwitterOAuth $twitter Ready to use instance of TwitterOAuth
31
     */
32
    public function __construct(TwitterOAuth $twitter)
33
    {
34
        $this->twitter = $twitter;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function publish(
41
        string $message,
42
        string $link = '',
43
        string $pictureLink = '',
44
        string $caption = '',
45
        string $description = ''
46
    ): bool {
47
        try {
48
            $status = $this->prepareStatus($message, $link);
49
            $post = $this->twitter->post('statuses/update', ['status' => $status, 'trim_user' => true]);
50
51
            return !empty($post->id_str);
52
        } catch (Throwable $t) {
53
            throw new FailureWhenPublishingSocialPost($t);
54
        }
55
    }
56
57
    /**
58
     * @param string $message
59
     * @param string $link
60
     * @return string
61
     */
62
    protected function prepareStatus(
63
        string $message,
64
        string $link
65
    ): string {
66
        $status = $message;
67
68
        if (filter_var($link, FILTER_VALIDATE_URL) !== false) {
69
            $linkIsNotPartOfTheMessage = mb_strpos($message, $link) === false;
70
            if ($linkIsNotPartOfTheMessage) {
71
                $status .= ' ' . $link;
72
            }
73
        }
74
75
        return $status;
76
    }
77
}
78