1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MartinGeorgiev\SocialPost\SocialNetwork\Twitter; |
6
|
|
|
|
7
|
|
|
use Abraham\TwitterOAuth\TwitterOAuth; |
8
|
|
|
use MartinGeorgiev\SocialPost\Message; |
9
|
|
|
use MartinGeorgiev\SocialPost\Publisher; |
10
|
|
|
use MartinGeorgiev\SocialPost\SocialNetwork\Enum; |
11
|
|
|
use MartinGeorgiev\SocialPost\SocialNetwork\Exception\FailureWhenPublishingMessage; |
12
|
|
|
use MartinGeorgiev\SocialPost\SocialNetwork\Exception\MessageNotIntendedForPublisher; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Provider for publishing on a Twitter page. |
16
|
|
|
* Uses TwitterOAuth v0.7 |
17
|
|
|
* @see https://github.com/abraham/twitteroauth |
18
|
|
|
* |
19
|
|
|
* @since 1.0.0 |
20
|
|
|
* @author Martin Georgiev <[email protected]> |
21
|
|
|
* @license https://opensource.org/licenses/MIT |
22
|
|
|
* @link https://github.com/martin-georgiev/social-post |
23
|
|
|
*/ |
24
|
|
|
class TwitterOAuth07 implements Publisher |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var TwitterOAuth |
28
|
|
|
*/ |
29
|
|
|
private $twitter; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param TwitterOAuth $twitter Ready to use instance of TwitterOAuth |
33
|
|
|
*/ |
34
|
|
|
public function __construct(TwitterOAuth $twitter) |
35
|
|
|
{ |
36
|
|
|
$this->twitter = $twitter; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function canPublish(Message $message): bool |
40
|
|
|
{ |
41
|
|
|
$canPublish = !empty(array_intersect($message->getNetworksToPublishOn(), [Enum::ANY, Enum::TWITTER])); |
42
|
|
|
|
43
|
|
|
return $canPublish; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function publish(Message $message): bool |
47
|
|
|
{ |
48
|
|
|
if (!$this->canPublish($message)) { |
49
|
|
|
throw new MessageNotIntendedForPublisher(Enum::TWITTER); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
try { |
53
|
|
|
$status = $this->prepareStatus($message); |
54
|
|
|
$post = $this->twitter->post('statuses/update', ['status' => $status, 'trim_user' => true]); |
55
|
|
|
|
56
|
|
|
return !empty($post->id_str); |
57
|
|
|
} catch (\Exception $e) { |
58
|
|
|
throw new FailureWhenPublishingMessage($e); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function prepareStatus(Message $message): string |
63
|
|
|
{ |
64
|
|
|
$status = $message->getMessage(); |
65
|
|
|
|
66
|
|
|
if (filter_var($message->getLink(), FILTER_VALIDATE_URL) !== false) { |
67
|
|
|
$linkIsNotIncludedInTheStatus = mb_strpos($status, $message->getLink()) === false; |
68
|
|
|
if ($linkIsNotIncludedInTheStatus) { |
69
|
|
|
$status .= ' '.$message->getLink(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $status; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|