Skip to content

Commit

Permalink
decouple Message from Client. Closes #15, fixes maknz#70
Browse files Browse the repository at this point in the history
  • Loading branch information
alek13 committed Feb 5, 2021
1 parent 53a102b commit 9822040
Show file tree
Hide file tree
Showing 5 changed files with 172 additions and 155 deletions.
138 changes: 72 additions & 66 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ A simple PHP package for sending messages to [Slack](https://slack.com)
with [incoming webhooks](https://my.slack.com/services/new/incoming-webhook),
focused on ease-of-use and elegant syntax.

**supports:** PHP `7.0`, `7.1`, `7.2`
**supports:** PHP `7.1`, `7.2`, `7.3`, `7.4` or `8.0`
**require:** `guzzlehttp/guzzle` any of versions `~6.0|~5.0|~4.0`

> This is the fork of popular, great, but abandoned package [`maknz/slack`](https://github.com/maknz/slack)
Expand Down Expand Up @@ -60,10 +60,10 @@ $client = new Maknz\Slack\Client('https://hooks.slack.com/...');
// use response_type (in_channel | ephemeral) to denote whether the message will be visible
// to others in the channel.
$settings = [
'username' => 'Cyril',
'channel' => '#accounting',
'reponse_type' => 'in_channel',
'link_names' => true
'username' => 'Cyril',
'channel' => '#accounting',
'reponse_type' => 'in_channel',
'link_names' => true
];

$client = new Maknz\Slack\Client('https://hooks.slack.com/...', $settings);
Expand Down Expand Up @@ -121,66 +121,69 @@ $client->to('#accounting')->withIcon('http://example.com/accounting.png')->send(

```php
$client->to('#operations')->attach([
'fallback' => 'Server health: good',
'text' => 'Server health: good',
'color' => 'danger',
'fallback' => 'Server health: good',
'text' => 'Server health: good',
'color' => 'danger',
])->send('New alert from the monitoring system'); // no message, but can be provided if you'd like
```

#### Send an attachment with fields ([preview](https://goo.gl/264mhU))

```php
$client->to('#operations')->attach([
'fallback' => 'Current server stats',
'text' => 'Current server stats',
'color' => 'danger',
'fields' => [
[
'title' => 'CPU usage',
'value' => '90%',
'short' => true // whether the field is short enough to sit side-by-side other fields, defaults to false
],
[
'title' => 'RAM usage',
'value' => '2.5GB of 4GB',
'short' => true
]
]
'fallback' => 'Current server stats',
'text' => 'Current server stats',
'color' => 'danger',
'fields' => [
[
'title' => 'CPU usage',
'value' => '90%',
'short' => true // whether the field is short enough to sit side-by-side other fields, defaults to false
],
[
'title' => 'RAM usage',
'value' => '2.5GB of 4GB',
'short' => true
]
]
])->send('New alert from the monitoring system'); // no message, but can be provided if you'd like
```

#### Send an attachment with an author ([preview](https://goo.gl/CKd1zJ))

```php
$client->to('@regan')->attach([
'fallback' => 'Keep up the great work! I really love how the app works.',
'text' => 'Keep up the great work! I really love how the app works.',
'author_name' => 'Jane Appleseed',
'author_link' => 'https://yourapp.com/feedback/5874601',
'author_icon' => 'https://static.pexels.com/photos/61120/pexels-photo-61120-large.jpeg'
'fallback' => 'Keep up the great work! I really love how the app works.',
'text' => 'Keep up the great work! I really love how the app works.',
'author_name' => 'Jane Appleseed',
'author_link' => 'https://yourapp.com/feedback/5874601',
'author_icon' => 'https://static.pexels.com/photos/61120/pexels-photo-61120-large.jpeg'
])->send('New user feedback');
```

#### Using blocks ([Block Kit](https://api.slack.com/block-kit))

```php
$client->to('@regan')->withBlock([
'type' => 'section',
'text' => 'Do you love the app?'
])->withBlock([
'type' => 'actions',
'elements' => [[
'type' => 'button',
'text' => 'Love it',
'style' => 'primary',
'action_id' => 'love',
], [
'type' => 'button',
'text' => 'Hate it',
'style' => 'danger',
'action_id' => 'hate',
],
])->send('Notification fallback message');
$client->to('@regan')
->withBlock([
'type' => 'section',
'text' => 'Do you love the app?'
])
->withBlock([
'type' => 'actions',
'elements' => [[
'type' => 'button',
'text' => 'Love it',
'style' => 'primary',
'action_id' => 'love',
], [
'type' => 'button',
'text' => 'Hate it',
'style' => 'danger',
'action_id' => 'hate',
],]
])
->send('Notification fallback message');
```

## Advanced usage
Expand All @@ -201,11 +204,11 @@ $client->to('#general')->enableMarkdown()->send('Enable _markdown_ just for this

```php
$client->to('#operations')->attach([
'fallback' => 'It is all broken, man',
'text' => 'It is _all_ broken, man',
'pretext' => 'From user: *JimBob*',
'color' => 'danger',
'mrkdwn_in' => ['pretext', 'text']
'fallback' => 'It is all broken, man',
'text' => 'It is _all_ broken, man',
'pretext' => 'From user: *JimBob*',
'color' => 'danger',
'mrkdwn_in' => ['pretext', 'text']
])->send('New alert from the monitoring system');
```

Expand All @@ -219,10 +222,12 @@ $client->to('@regan')->send('I am sending this implicitly');

// Explicitly
$message = $client->createMessage();
$message
->to('@regan')
->setText('I am sending this explicitly')
;

$message->to('@regan')->setText('I am sending this explicitly');

$message->send();
$client->send($message);
```

### Attachments
Expand All @@ -231,34 +236,35 @@ When using attachments, the easiest way is to provide an array of data as shown

```php
$attachment = new Attachment([
'fallback' => 'Some fallback text',
'text' => 'The attachment text'
'fallback' => 'Some fallback text',
'text' => 'The attachment text'
]);

// Explicitly create a message from the client
// rather than using the magic passthrough methods
$message = $client->createMessage();

$message->attach($attachment);

// Explicitly set the message text rather than
// implicitly through the send method
$message->setText('Hello world')->send();
$message->setText('Hello world');

$client->send($message);
```

Each attachment field is also an object, an AttachmentField. They can be used as well instead of their data in array form:

```php
$attachment = new Attachment([
'fallback' => 'Some fallback text',
'text' => 'The attachment text',
'fields' => [
new AttachmentField([
'title' => 'A title',
'value' => 'A value',
'short' => true
])
]
'fallback' => 'Some fallback text',
'text' => 'The attachment text',
'fields' => [
new AttachmentField([
'title' => 'A title',
'value' => 'A value',
'short' => true
])
]
]);
```

Expand Down
113 changes: 83 additions & 30 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
use RuntimeException;

/**
* @method Message to(string $channel)
* @method Message send(string $text = null)
* @mixin Message
*/
class Client
{
Expand Down Expand Up @@ -108,6 +107,11 @@ class Client
'markdown_in_attachments' => 'setMarkdownInAttachments',
];

/**
* @var Message
*/
protected $message;

/**
* Instantiate a new Client.
*
Expand Down Expand Up @@ -139,18 +143,48 @@ private static function getOptionSetter(string $option)
return static::$optionSetter[$option] ?? null;
}

/**
* @param array $options
*
* @return \Maknz\Slack\Client
*/
public function setOptions(array $options)
{
foreach ($options as $option => $value) {
$this->setOption($option, $value);
}

return $this;
}

/**
* @param $option
* @param $value
*/
public function setOption($option, $value)
{
$setter = self::getOptionSetter($option);
if ($setter !== null) {
$this->$setter($value);
}
}

/**
* Pass any unhandled methods through to a new Message
* instance.
*
* @param string $name The name of the method
* @param array $arguments The method arguments
*
* @return \Maknz\Slack\Message
* @return $this|mixed
*/
public function __call($name, $arguments)
{
return call_user_func_array([$this->createMessage(), $name], $arguments);
/** @var Message $message */
$message = $this->getOrCreateMessage();
$value = $message->$name(...$arguments);

return strpos($name, 'get') === 0 ? $value : $this;
}

/**
Expand Down Expand Up @@ -381,6 +415,14 @@ public function setMarkdownInAttachments(array $fields)
$this->markdown_in_attachments = $fields;
}

/**
* @return Message
*/
public function getMessage()
{
return $this->message;
}

/**
* Create a new message with defaults.
*
Expand All @@ -403,9 +445,19 @@ public function createMessage()
return $message;
}

/**
* @return Message
*/
protected function getOrCreateMessage()
{
return $this->message ?? $this->message = $this->createMessage();
}

/**
* Send a message.
*
* @internal will become protected
*
* @param \Maknz\Slack\Message $message
*
* @throws \RuntimeException
Expand All @@ -423,6 +475,33 @@ public function sendMessage(Message $message)
$this->guzzle->post($this->endpoint, ['body' => $encoded]);
}

/**
* Send the message.
*
* @param string|\Maknz\Slack\Message $text The text to send
*
* @return \Maknz\Slack\Message
*
* @throws \RuntimeException
*/
public function send($text = null)
{
if ($text instanceof Message) {
$message = $text;
} else {
$message = $this->getOrCreateMessage();
if ($text !== null) {
$message->setText($text);
}
}

$this->sendMessage($message);

$this->message = null;

return $message;
}

/**
* Prepares the payload to be sent to the webhook.
*
Expand Down Expand Up @@ -473,30 +552,4 @@ protected function getAttachmentsAsArrays(Message $message)

return $attachments;
}

/**
* @param array $options
*
* @return \Maknz\Slack\Client
*/
public function setOptions(array $options)
{
foreach ($options as $option => $value) {
$this->setOption($option, $value);
}

return $this;
}

/**
* @param $option
* @param $value
*/
public function setOption($option, $value)
{
$setter = self::getOptionSetter($option);
if ($setter !== null) {
$this->$setter($value);
}
}
}
Loading

0 comments on commit 9822040

Please sign in to comment.