Files

80 lines
2.6 KiB
Python

from ..parser.models import ParsedCurl
def generate_php(parsed: ParsedCurl) -> str:
"""Generate PHP cURL code from parsed curl command."""
lines = [
"<?php",
"",
"function makeRequest() {",
f' $url = "{parsed.url}"',
"",
" $ch = curl_init();",
"",
]
headers_list = []
for h in parsed.headers:
headers_list.append(f'"{h.key}: {h.value}"')
if parsed.user_agent:
headers_list.append(f'"User-Agent: {parsed.user_agent}"')
if parsed.auth and parsed.auth.username and parsed.auth.password:
lines.append(f' $username = "{parsed.auth.username}";')
lines.append(f' $password = "{parsed.auth.password}";')
lines.append(' curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");')
lines.append("")
if parsed.method.value != "GET":
lines.append(f' curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "{parsed.method.value}");')
if parsed.data:
if parsed.data.data_type.value == "json" and parsed.data.json_data:
import json
json_str = json.dumps(parsed.data.json_data)
lines.append(f' $data = \'{json_str}\';')
headers_list.append('"Content-Type: application/json"')
else:
lines.append(f' $data = {repr(parsed.data.content)};')
lines.append(" curl_setopt($ch, CURLOPT_POSTFIELDS, $data);")
lines.append("")
if headers_list:
lines.append(f" $headers = [{', '.join(headers_list)}];")
lines.append(" curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);")
lines.append("")
lines.append(" curl_setopt($ch, CURLOPT_URL, $url);")
lines.append(" curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);")
lines.append(" curl_setopt($ch, CURLOPT_HEADER, false);")
if parsed.timeout:
lines.append(f" curl_setopt($ch, CURLOPT_TIMEOUT, {parsed.timeout});")
if parsed.follow_redirects:
lines.append(" curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);")
lines.extend([
"",
" $response = curl_exec($ch);",
" $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);",
"",
" if (curl_errno($ch)) {",
' echo "cURL Error: " . curl_error($ch) . "\\n";',
" } elseif ($httpCode >= 400) {",
f' echo "HTTP Error: $httpCode\\n";',
" } else {",
" echo $response . PHP_EOL;",
" }",
"",
" curl_close($ch);",
"}",
"",
"makeRequest();",
"",
"?>",
])
return "\n".join(lines)