Last active
June 19, 2019 03:49
-
-
Save PurpleBooth/79de90456fff212cd350eabb19755fa5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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