phpRenderer.jsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { Fence } from '@/components/Fence'
  2. const PhpRequestRenderer = ({
  3. url,
  4. headers,
  5. bodyMethod,
  6. rpcVersion,
  7. bodyParams,
  8. id,
  9. }) => {
  10. const httpBody = bodyParams
  11. // Handle default values for `rpcVersion` and `id`
  12. const rpcVersionValue = rpcVersion || '2.0'
  13. const idValue = id || 1
  14. // Convert httpBody to a PHP-compatible format
  15. const formatParamsForPhp = (params) => {
  16. if (Array.isArray(params)) {
  17. return `[${params.map((item) => `'${item}'`).join(', ')}]` // Correct array formatting for PHP
  18. }
  19. if (typeof params === 'object') {
  20. return `[${Object.entries(params)
  21. .map(([key, value]) => `'${key}' => '${value}'`)
  22. .join(', ')}]` // Use PHP array syntax for key-value pairs
  23. }
  24. return `'${params}'`
  25. }
  26. const formattedParams = formatParamsForPhp(httpBody)
  27. const headersCode = Object.entries(headers)
  28. .map(([key, value]) => `"${key}: ${value}"`)
  29. .join(',\n ')
  30. const code = `
  31. <?php
  32. $url = "${url}";
  33. $data = [
  34. "jsonrpc" => "${rpcVersionValue}",
  35. "id" => ${idValue},
  36. "method" => "${bodyMethod}",
  37. "params" => ${formattedParams}
  38. ];
  39. // Initialize cURL session
  40. $ch = curl_init($url);
  41. // Set cURL options
  42. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  43. curl_setopt($ch, CURLOPT_POST, true);
  44. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
  45. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  46. "Content-Type: application/json",
  47. ]);
  48. // Execute cURL request
  49. $response = curl_exec($ch);
  50. // Check for errors
  51. if ($response === false) {
  52. echo "cURL Error: " . curl_error($ch);
  53. } else {
  54. echo "Response: " . $response;
  55. }
  56. // Close cURL session
  57. curl_close($ch);
  58. ?>
  59. `
  60. return (
  61. <Fence className="w-full" language="php">
  62. {code}
  63. </Fence>
  64. )
  65. }
  66. export default PhpRequestRenderer