Skip to content

Instantly share code, notes, and snippets.

@PurpleBooth
Last active June 19, 2019 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PurpleBooth/79de90456fff212cd350eabb19755fa5 to your computer and use it in GitHub Desktop.
Save PurpleBooth/79de90456fff212cd350eabb19755fa5 to your computer and use it in GitHub Desktop.
<?php
use Armakuni\Demo\PhpInserter\ConfigFactory;
use Armakuni\Demo\PhpInserter\StackdriverExporterFactory;
use Armakuni\Demo\PhpInserter\TraceService;
use OpenCensus\Trace\Tracer;
require __DIR__ . "/vendor/autoload.php";
$googleConfig = (new ConfigFactory())->build();
$exporter = (new StackdriverExporterFactory($googleConfig))->build();
(new TraceService($exporter))->start();
$message = Tracer::inSpan(
['name' => 'consume-message'],
function () {
$rawMessage = file_get_contents('php://input');
if ($rawMessage === false) {
error_log("No body");
return "";
}
$message = json_decode($rawMessage, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Invalid message: " . $rawMessage);
}
return $message;
}
);
Tracer::inSpan(
['name' => 'render'],
function () use ($message) {
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
}
http_response_code(204);
$decodedMessage = base64_decode($message['message']['data']);
if ($decodedMessage === false) {
error_log("Could not base64 decode message:" . $message['message']['data']);
return;
}
error_log($decodedMessage);
}
);
<?php
namespace Armakuni\Demo\PhpInserter;
use Google\Cloud\PubSub\PubSubClient;
class MessageSenderService
{
/**
* @var PubSubClient
*/
private $pubSubClient;
/**
* @var string
*/
private $topic;
/**
* CounterService constructor.
* @param PubSubClient $pubSubClient
* @param string $topic
*/
public function __construct(PubSubClient $pubSubClient, string $topic)
{
$this->pubSubClient = $pubSubClient;
$this->topic = $topic;
}
/**
* @param string $message
* @return void
*/
public function sendMessage(string $message): void
{
$topic = $this->pubSubClient->topic($this->topic);
if (!$topic->exists()) {
$topic->create();
}
$topic->publish(['data' => $message]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment