Repository URL to install this package:
|
Version:
2.0.1 ▾
|
<?php
namespace CrazyFactory\Slack;
/**
* Class SlackClient
*/
class SlackClient
{
protected $endpoint;
protected $config;
/**
* Slack constructor.
*
* @param array|string $config
*
* @throws \Exception
*/
public function __construct($config = [])
{
// string config will be used as endpoint
if (is_string($config)) {
$config = [
'endpoint' => $config,
];
}
if (!$this->validateConfig($config)) {
throw new \Exception('Slack configuration is invalid');
}
$this->config = $config;
}
/**
* @param array $config
* @param array $errors
*
* @return bool
*/
protected function validateConfig(array $config = [], array &$errors = [])
{
if (empty($config['endpoint'])) {
$errors[] = 'endpoint is not defined';
}
if (isset($config['context']) && !is_array($config['context'])) {
$errors[] = 'context must be null or array';
}
if (isset($config['headers']) && !is_array($config['headers'])) {
$errors[] = 'headers must be null or array';
}
return empty($errors);
}
/**
* Logs the message to Slack channel.
*
* @param array|string $context
*
* @return bool
* @throws \Exception
*/
public function send($context = [])
{
if (is_string($context)) {
$context = [
'text' => $context,
];
}
// Merge with default context
$config_context=isset($this->config['context']) ? $this->config['context']:[];
$mergedContext = array_merge( $config_context, $context);
return (isset($mergedContext['async'])? $mergedContext['async']: false)
? $this->sendAsync($mergedContext)
: $this->sendSync($mergedContext);
}
/**
* Send a message to a Slack webhook using PHP curl.
*
* @param array $context See https://api.slack.com/incoming-webhooks for more information
*
* @return bool
*/
protected function sendSync(array $context)
{
$payload = json_encode($context, JSON_UNESCAPED_UNICODE);
$curl = curl_init($this->config['endpoint']);
$config_headers = isset($this->config['headers']) ? $this->config['headers'] : [];
$headers = ['Content-Type' => 'application/json'] + $config_headers;
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_VERBOSE => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $payload,
]);
curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $code == 200;
}
/**
* Send a message to a Slack webhook using system CURL.
*
* @param array $context See https://api.slack.com/incoming-webhooks for more information
*
* @return bool
*/
protected function sendAsync(array $context)
{
$payload = json_encode($context, JSON_UNESCAPED_UNICODE);
$command = 'curl -X POST ';
$config_headers = isset($this->config['headers']) ? $this->config['headers'] : [];
$headers = ['Content-Type' => 'application/json'] + $config_headers;
foreach ($headers as $key => $value) {
$command .= '-H ' . escapeshellarg("$key: $value") . ' ';
}
// Fire and forget.
exec("$command --data '{$payload}' {$this->config['endpoint']} > /dev/null 2>&1 &");
return true;
}
}