Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
datashaman committed Oct 25, 2024
1 parent 08259ad commit 0b00553
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 134 deletions.
4 changes: 4 additions & 0 deletions .phpactor.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "/phpactor.schema.json",
"language_server_phpstan.enabled": true
}
169 changes: 79 additions & 90 deletions src/ServiceBusChannel.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,11 @@ class ServiceBusChannel
*/
public function __construct(array $config = [])
{
$this->config = $config ?: config('services.service_bus');
$this->config = $config ?: config("services.service_bus");

$this->client = new Client(
[
'base_uri' => Arr::get($this->config, 'endpoint'),
]
);
$this->client = new Client([
"base_uri" => Arr::get($this->config, "endpoint"),
]);
}

/**
Expand All @@ -56,20 +54,15 @@ public function send($notifiable, Notification $notification)
$event = $notification->toServiceBus($notifiable);
$eventType = $event->getEventType();
$params = $event->getParams();
$dontReport = Arr::get($this->config, 'dont_report', []);
$dontReport = Arr::get($this->config, "dont_report", []);

if (Arr::get($this->config, 'enabled') == false) {
if (Arr::get($this->config, "enabled") == false) {
if (!in_array($eventType, $dontReport)) {
Log::debug(
"$eventType service bus notification [disabled]",
[
'event' => $eventType,
'params' => $params,
'tags' => [
'service-bus',
],
]
);
Log::debug("$eventType service bus notification [disabled]", [
"event" => $eventType,
"params" => $params,
"tags" => ["service-bus"],
]);
}

return;
Expand All @@ -78,46 +71,36 @@ public function send($notifiable, Notification $notification)
$token = $this->getToken();

$headers = [
'Accept' => 'application/json',
'Content-type' => 'application/json',
'x-api-key' => $token,
"Accept" => "application/json",
"Content-type" => "application/json",
"x-api-key" => $token,
];

try {
$response = $this->client->request(
'POST',
$this->getUrl('events'),
"POST",
$this->getUrl("events"),
[
'headers' => $headers,
'json' => [$params],
"headers" => $headers,
"json" => [$params],
]
);

Log::info(
"$eventType service bus notification",
[
'event' => $eventType,
'params' => $params,
'tags' => [
'service-bus',
],
'status' => $response->getStatusCode(),
]
);
Log::info("$eventType service bus notification", [
"event" => $eventType,
"params" => $params,
"tags" => ["service-bus"],
"status" => $response->getStatusCode(),
]);
} catch (RequestException $exception) {
$code = $exception->getCode();

if (in_array($code, [401, 403])) {
Log::info(
"$code received. Logging in and retrying.",
[
'event' => $eventType,
'params' => $params,
'tags' => [
'service-bus',
],
]
);
Log::info("$code received. Logging in and retrying.", [
"event" => $eventType,
"params" => $params,
"tags" => ["service-bus"],
]);

// clear the invalid token //
Cache::forget($this->generateTokenKey());
Expand Down Expand Up @@ -145,45 +128,54 @@ public function send($notifiable, Notification $notification)
*/
private function getToken(): string
{
return Cache::rememberForever(
$this->generateTokenKey(),
function () {
try {
$version = intval($this->config['version']);

if ($version < 2) {
$response = $this->client->request(
'POST',
$this->getUrl('login'),
[
'json' => Arr::only($this->config, ['username', 'password', 'venture_config_id']),
]
);
} else {
$response = $this->client->request(
'POST',
$this->getUrl('login'),
[
'json' => Arr::only($this->config, ['username', 'password', 'node_id']),
]
);
}

$body = json_decode((string) $response->getBody(), true);

$code = (int) Arr::get($body, 'code', $response->getStatusCode());

switch ($code) {
case 200:
return $body['token'];
default:
throw CouldNotSendNotification::loginFailed($response);
}
} catch (RequestException $exception) {
throw CouldNotSendNotification::requestFailed($exception);
return Cache::rememberForever($this->generateTokenKey(), function () {
try {
$version = intval($this->config["version"]);

if ($version < 2) {
$response = $this->client->request(
"POST",
$this->getUrl("login"),
[
"json" => Arr::only($this->config, [
"username",
"password",
"venture_config_id",
]),
]
);
} else {
$response = $this->client->request(
"POST",
$this->getUrl("login"),
[
"json" => Arr::only($this->config, [
"username",
"password",
"node_id",
]),
]
);
}

$body = json_decode((string) $response->getBody(), true);

$code = (int) Arr::get(
$body,
"code",
$response->getStatusCode()
);

switch ($code) {
case 200:
return $body["token"];
default:
throw CouldNotSendNotification::loginFailed($response);
}
} catch (RequestException $exception) {
throw CouldNotSendNotification::requestFailed($exception);
}
);
});
}

/**
Expand All @@ -198,18 +190,15 @@ private function getUrl(string $endpoint): string

public function generateTokenKey()
{
$version = intval($this->config['version']);
$version = intval($this->config["version"]);

if ($version < 2) {
return md5(
'service-bus-token' .
Arr::get($this->config, 'venture_config_id')
"service-bus-token" .
Arr::get($this->config, "venture_config_id")
);
}

return md5(
'service-bus-token' .
Arr::get($this->config, 'node_id')
);
return md5("service-bus-token" . Arr::get($this->config, "node_id"));
}
}
25 changes: 0 additions & 25 deletions tests/ServiceBusChannelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,36 +28,11 @@ public function testShouldThrowRequestExceptionOnSendEvent()
{
$this->expectException(CouldNotSendNotification::class);

$this->mockAll();
Cache::shouldReceive("rememberForever")->andReturn(true);
Cache::shouldReceive("forget")->andReturn(true);

$serviceChannel = new ServiceBusChannel();

$serviceChannel->send(
new AnonymousNotifiable(),
new TestNotification()
);
}

/**
* Mock classes, facades and everything else needed.
*/
private function mockAll()
{
Cache::shouldReceive("get")
->once()
->with((new ServiceBusChannel(config_v2()))->generateTokenKey())
->andReturn("value");

Log::shouldReceive("debug")->once()->andReturnNull();

Log::shouldReceive("info")->once()->andReturnNull();

Log::shouldReceive("error")->once()->andReturnNull();

Mockery::mock(Client::class, function (MockInterface $mock) {
$mock->shouldReceive("execute")->andReturn(new stdClass())->once();
});
}
}
19 changes: 0 additions & 19 deletions tests/ServiceBusEventTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
use Carbon\Carbon;
use Ringierimu\ServiceBusNotificationsChannel\Exceptions\InvalidConfigException;
use Ringierimu\ServiceBusNotificationsChannel\ServiceBusEvent;
use Throwable;

/**
* Class ServiceBusEventTest.
*/
class ServiceBusEventTest extends TestCase
{
public function testShouldCreateServiceBusEventInstance()
Expand All @@ -26,9 +22,6 @@ public function testShouldCreateServiceBusEventInstanceViaStaticCall()
$this->assertEquals("test", $serviceBus->getEventType());
}

/**
* @throws InvalidConfigException
*/
public function testShouldThrowInvalidConfigException()
{
$this->expectException(InvalidConfigException::class);
Expand All @@ -42,10 +35,6 @@ public function testShouldThrowInvalidConfigException()
->withResources("resources", ["data"]);
}

/**
* @throws InvalidConfigException
* @throws Throwable
*/
public function testShouldAllocateAttributesToServiceBusObject()
{
$resource = [
Expand Down Expand Up @@ -73,10 +62,6 @@ public function testShouldAllocateAttributesToServiceBusObject()
$this->assertEquals($resource, $serviceBusData["payload"]["resource"]);
}

/**
* @throws InvalidConfigException
* @throws Throwable
*/
public function testShouldAllocateAttributesToServiceBusObjectWithPayload()
{
$payload = [
Expand Down Expand Up @@ -105,10 +90,6 @@ public function testShouldAllocateAttributesToServiceBusObjectWithPayload()
$this->assertEquals($payload, $serviceBusData["payload"]);
}

/**
* @throws InvalidConfigException
* @throws Throwable
*/
public function testShouldReturnCorrectEventForSpecificVersion()
{
$serviceBusVersion1 = ServiceBusEvent::create("test", config_v1())
Expand Down
1 change: 1 addition & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ protected function getPackageProviders($app)
protected function defineEnvironment($app)
{
tap($app["config"], function (Repository $config) {
$config->set("cache.default", "array");
$config->set("services.service_bus", [
"enabled" => true,
"node_id" => "123456789",
Expand Down

0 comments on commit 0b00553

Please sign in to comment.