Passed
Push — develop ( fefadb...6c2c37 )
by Martin
32s
created

TwitterOAuth07::canPublish()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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