-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe-mode-example.php
More file actions
84 lines (65 loc) · 2.36 KB
/
Copy pathsafe-mode-example.php
File metadata and controls
84 lines (65 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use RpcPhpToolkit\RpcSafeEndpoint;
use RpcPhpToolkit\Client\RpcSafeClient;
/**
* Example: Using RpcSafeEndpoint and RpcSafeClient
*
* This example demonstrates how to use the Safe mode classes
* for better type preservation and automatic safe mode handling.
*/
// ===== SERVER SIDE =====
// Create a safe endpoint (Safe Mode enabled by default)
$rpc = new RpcSafeEndpoint('/api', ['server' => 'example']);
// Register methods that handle special types
$rpc->addMethod('getCurrentTime', function() {
return [
'timestamp' => time(),
'datetime' => new DateTime('now'),
'timezone' => date_default_timezone_get()
];
});
$rpc->addMethod('mathOperations', function($params) {
return [
'infinity' => INF,
'negativeInfinity' => -INF,
'notANumber' => NAN,
'result' => $params['a'] + $params['b']
];
});
$rpc->addMethod('echo', function($params) {
return $params;
});
// Handle incoming request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$response = $rpc->handleRequest($input);
header('Content-Type: application/json');
echo $response;
exit;
}
// ===== CLIENT SIDE =====
// Create a safe client (Safe Mode enabled by default)
$client = new RpcSafeClient('http://localhost:8080/api');
try {
// Call methods
$time = $client->call('getCurrentTime');
echo "Current time: " . json_encode($time, JSON_PRETTY_PRINT) . "\n\n";
$math = $client->call('mathOperations', ['a' => 10, 'b' => 5]);
echo "Math operations: " . json_encode($math, JSON_PRETTY_PRINT) . "\n\n";
$echo = $client->call('echo', ['test' => 'value', 'number' => 42]);
echo "Echo: " . json_encode($echo, JSON_PRETTY_PRINT) . "\n\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
// You can still override options if needed
$customClient = new RpcSafeClient('http://localhost:8080/api', [], [
'timeout' => 10,
'verifySSL' => false,
// safeEnabled is still true by default
]);
echo "\n=== Safe Mode Classes Demo ===\n";
echo "RpcSafeEndpoint: Automatically enables Safe Mode for the server\n";
echo "RpcSafeClient: Automatically enables Safe Mode for the client\n";
echo "Both classes provide a cleaner API compared to manual option setting\n";