Files
php-qml/spike/php/index.php
magdev 9655b6fef9 Add Phase 0 spike: end-to-end transport verified
Bare PHP behind FrankenPHP plus a Qt/QML host that spawns it. GET /api/ping
publishes a Mercure event; the QML window receives it back over the SSE
stream. Findings (Caddy directive ordering, Mercure transport scalar,
PR_SET_PDEATHSIG for child cleanup, PHP 8.5 curl_close deprecation, port
collision with system FrankenPHP, pure-QML SSE viability) are recorded in
spike/README.md so Phase 1 starts from a known-good baseline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 00:15:50 +02:00

65 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
const MERCURE_KEY = '!ChangeThisDevKey!';
const MERCURE_HUB = 'http://127.0.0.1:8765/.well-known/mercure';
const MERCURE_TOPIC = 'app://ping';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
header('Access-Control-Allow-Origin: *');
if ($path === '/api/ping' && $method === 'GET') {
$payload = ['pong' => true, 'now' => date('c')];
publishToMercure(MERCURE_TOPIC, $payload);
header('Content-Type: application/json');
echo json_encode($payload);
return;
}
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['error' => 'not found', 'path' => $path]);
function publishToMercure(string $topic, array $data): void
{
$body = http_build_query([
'topic' => $topic,
'data' => json_encode($data),
]);
$ch = curl_init(MERCURE_HUB);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Bearer ' . mintPublisherJwt(),
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
]);
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
error_log("mercure publish topic=$topic http=$code body=" . ($resp === false ? 'false' : (string) $resp));
}
function mintPublisherJwt(): string
{
$header = ['alg' => 'HS256', 'typ' => 'JWT'];
$payload = ['mercure' => ['publish' => ['*']]];
$h = b64url(json_encode($header));
$p = b64url(json_encode($payload));
$s = b64url(hash_hmac('sha256', "$h.$p", MERCURE_KEY, true));
return "$h.$p.$s";
}
function b64url(string $bytes): string
{
return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}