Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 98 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ if ($response->wasSuccessful())
);
}
}

```

### Getting your balance
Expand All @@ -120,3 +119,101 @@ $spryng = new Spryng($apiKey);
$balance = $spryng->balance->get()->toObject();
echo "You have " . $balance->getAmount() . " credits remaining\n";
```

## Setting up your Spryng account in laravel

Add the environment variables to your `config/services.php`:

```php
// config/services.php
...
'spryng' => [
'access_key' => env('SPRYNG_ACCESS_KEY', ''),
'originator' => env('SPRYNG_ORIGINATOR', ''),
'recipients' => env('SPRYNG_RECIPIENTS', []),
],
...
```

Add your Spryng Access Key, Default originator (name or number of sender), and default recipients to your `.env`:

```php
// .env
...
SPRYNG_ACCESS_KEY=
SPRYNG_ORIGINATOR=
SPRYNG_RECIPIENTS=
],
...
```

You can create a 'SpryngChannel.php' in 'App/Channels'

```php
use Illuminate\Notifications\Notification;
use Spryng\SpryngRestApi\Exceptions\ValidationException;
use Spryng\SpryngRestApi\SpryngClient;

class SpryngChannel
{
private SpryngClient $client;

public function __construct(SpryngClient $client)
{
$this->client = $client;
}

public function send($notifiable, Notification $notification)
{
$config = config('services.spryng');

$spryngMessage = $notification->toSpryng($notifiable);

if (is_string($spryngMessage)) {
$spryngMessageObj = new \Spryng\SpryngRestApi\Objects\Message();
$spryngMessageObj->setBody($spryngMessage);
$spryngMessage = $spryngMessageObj;
}

$spryngMessage->setOriginator($config['originator']);

$data = [];

if ($to = $notifiable->routeNotificationFor('spryng')) {
$spryngMessage->setRecipients([$to]);
}

try {
$data = $this->client->send($spryngMessage);
} catch (ValidationException $e) {
logger()->error($e->getMessage());
}

return $data;
}
}
```

Now you can use the channel in your `via()` method inside the notification:

``` php
use App\Channels\SpryngChannel;
use Spryng\SpryngRestApi\Objects\Message;
use Illuminate\Notifications\Notification;

class VpsServerOrdered extends Notification
{
public function via($notifiable)
{
return [SpryngChannel::class];
}

public function toSpryng($notifiable): Message
{
$message = new Message();
$message->setBody('This is message');

return $message;
}
}
```
7 changes: 7 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,12 @@
"psr-4": {
"Spryng\\SpryngRestApi\\": "src/Spryng/SpryngRestApi"
}
},
"extra": {
"laravel": {
"providers": [
"Spryng\\SpryngRestApi\\SpryngServiceProvider"
]
}
}
}
23 changes: 9 additions & 14 deletions src/Spryng/SpryngRestApi/ApiResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ class ApiResource

public function __construct($raw = null)
{
if ($raw !== null)
{
if ($raw !== null) {
$this->setRaw($raw);
}
}
Expand All @@ -25,16 +24,16 @@ public function getRaw()
}

/**
* @param mixed $raw
* @param mixed $raw
*/
public function setRaw($raw)
{
$this->raw = $raw;
}

/**
* @param $raw string|array
* @param $class string
* @param $raw string|array
* @param $class string
* @return ApiResource|array
*/
public static function deserializeFromRaw($raw, $class)
Expand All @@ -43,8 +42,7 @@ public static function deserializeFromRaw($raw, $class)
$json = json_decode($raw, true);

// If the data parameter is set, it means that this is a collection of message objects
if (isset($json['data']))
{
if (isset($json['data'])) {
$collection = new MessageCollection();
$collection->setTotal($json['total']);
$collection->setPerPage($json['per_page']);
Expand All @@ -55,9 +53,8 @@ public static function deserializeFromRaw($raw, $class)
$collection->setFrom($json['from']);
$collection->setTo($json['to']);

$messages = array();
foreach ($json['data'] as $rawMessage)
{
$messages = [];
foreach ($json['data'] as $rawMessage) {
// Call the function recursively to deserialize every message. Serialize back to Json to avoid array/object
// conversion issues
$messages[] = self::deserializeFromRaw(json_encode($rawMessage), $class);
Expand All @@ -69,17 +66,15 @@ public static function deserializeFromRaw($raw, $class)

// If we've come here, we're deserializing a single message or balance response
$obj = new $class;
foreach ($json as $key => $val)
{
foreach ($json as $key => $val) {
// Remove underscores from the key that may be present in the response
$key = str_replace('_', '', $key);

// Get the name of the set method by capitalizing the first character of the key
$name = 'set'.ucfirst($key);

// If there is such a set method, call it
if (method_exists($class, $name))
{
if (method_exists($class, $name)) {
$obj->$name($val);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Spryng/SpryngRestApi/BaseClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ public function getApi()
}

/**
* @param mixed $api
* @param mixed $api
*/
public function setApi($api)
{
$this->api = $api;
}
}
}
16 changes: 16 additions & 0 deletions src/Spryng/SpryngRestApi/Exceptions/InvalidConfiguration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Spryng\SpryngRestApi\Exceptions;

use Exception;

class InvalidConfiguration extends Exception
{
/**
* @return static
*/
public static function configurationNotSet()
{
return new static('In order to send notification via Spryng you need to add credentials in the `spryng` key of `config.services`.');
}
}
6 changes: 5 additions & 1 deletion src/Spryng/SpryngRestApi/Exceptions/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,8 @@

namespace Spryng\SpryngRestApi\Exceptions;

class ValidationException extends \Exception { }
use Exception;

class ValidationException extends Exception
{
}
40 changes: 20 additions & 20 deletions src/Spryng/SpryngRestApi/Http/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

class HttpClient implements HttpClientInterface
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
public const METHOD_GET = 'GET';

public const METHOD_POST = 'POST';

public const METHOD_PATCH = 'PATCH';

public const METHOD_DELETE = 'DELETE';

/**
* @var false|resource
Expand All @@ -22,19 +25,18 @@ class HttpClient implements HttpClientInterface
/**
* @var Response|null
*/
protected $lastResponse;
protected ?Response $lastResponse;

public function __construct(Request $req = null)
public function __construct(?Request $req = null)
{
$this->ch = curl_init();

if ($req !== null)
{
if ($req !== null) {
$this->setActiveRequest($req);
}
}

public function send(Request $req = null)
public function send(?Request $req = null)
{
if ($req === null) {
if ($this->activeRequest === null) {
Expand All @@ -48,8 +50,7 @@ public function send(Request $req = null)

// Don't print the result
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
switch ($this->activeRequest->getHttpMethod())
{
switch ($this->activeRequest->getHttpMethod()) {
case self::METHOD_GET:
case self::METHOD_DELETE:
$this->lastResponse = $this->executeNoData();
Expand All @@ -75,6 +76,7 @@ private function executeNoData()
$this->applyHeaders();

$rawResponse = curl_exec($this->ch);

return Response::constructFromCurlResponse($this->ch, $rawResponse);
}

Expand All @@ -90,13 +92,13 @@ private function executeWithData()
$this->applyHeaders();

$rawResponse = curl_exec($this->ch);

return Response::constructFromCurlResponse($this->ch, $rawResponse);
}

/**
* Sets the current request to be activated to $req
*
* @param Request $req
* @return HttpClientInterface
*/
public function setActiveRequest(Request $req)
Expand Down Expand Up @@ -125,20 +127,19 @@ public function getLastResponse()
private function applyHeaders()
{
// Convert associative array of headers with key and value to single string headers
$headers = array();
$headers = [];
foreach ($this->activeRequest->getHeaders() as $key => $value) {
// Apply the user agent header using the CURLOPT_USERAGENT option
if (strtolower($key) === 'user-agent')
{
if (strtolower($key) === 'user-agent') {
curl_setopt($this->ch, CURLOPT_USERAGENT, $value);

continue;
}
$headers[] = sprintf('%s: %s', $key, $value);
}

// Set converted headers on the curl instance
if (count($headers) > 0)
{
if (count($headers) > 0) {
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
}
Expand All @@ -159,8 +160,7 @@ private function setUrl()
$url = sprintf('%s%s', $this->activeRequest->getBaseUrl(), $this->activeRequest->getMethod());

// If any query string parameters are set, format them and add to the URL.
if (count($this->activeRequest->getQueryStringParameters()) > 0)
{
if (count($this->activeRequest->getQueryStringParameters()) > 0) {
$url .= sprintf('?%s', http_build_query($this->activeRequest->getQueryStringParameters()));
}

Expand All @@ -186,4 +186,4 @@ public function getActiveRequest()
{
return $this->activeRequest;
}
}
}
9 changes: 3 additions & 6 deletions src/Spryng/SpryngRestApi/Http/HttpClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,19 @@ interface HttpClientInterface
{
/**
* HttpClientInterface constructor.
* @param Request|null $req
*/
public function __construct(Request $req = null);
public function __construct(?Request $req = null);

/**
* Executes the currently active request or $req if it is set.
*
* @param Request $req
* @return Response
*/
public function send(Request $req = null);
public function send(?Request $req = null);

/**
* Sets the current request to be activated to $req
*
* @param Request $req
* @return HttpClientInterface
*/
public function setActiveRequest(Request $req);
Expand All @@ -32,4 +29,4 @@ public function setActiveRequest(Request $req);
* @return Response
*/
public function getLastResponse();
}
}
Loading