import{format as T}from"util";import{CodeBuilder as D}from"../../helpers/code-builder.js";import{HTTPSnippet as w}from"../../index.js";import{Lang as C}from"../../helpers/constants.js";import{buildUrlExpression as N,printUrlVariablesDeclarations as z}from"../../helpers/code-helpers.js";import{startCase as S}from"../../helpers/lodash-int.js";import{normalizeMimeType as H}from"../../../../utils.js";import{MediaTypes as R}from"../../../../../constants.js";import{objectToPhpArray as v}from"./utils.js";import{buildPHPDeviceAuthorizationCodeSnippet as I}from"../../helpers/device-auth-snippets.js";function y(e,d){return d?`$${d}${S(e)}`:`$${e}`}const V=function(e,d,{target:E,client:L}){const t={showBoilerplate:!0,checkErrors:!1,printBody:!0,indent:"  ",noTags:!0,shortTags:!1,maxRedirects:10,namedErrors:!1,closingTag:!1,...d};let r,l=!1;const n=new D({indentation:t.indent,capitalize:!0,lang:C.PHP}),o=e.securityOAuth2ExtraCalls?.[0],p=y("curl",t.variablesPrefix),O=y("response",t.variablesPrefix),f=y("error",t.variablesPrefix);if(t.noTags||n.push(t.shortTags?"<?":"<?php").blank(),o){const a="oAuth2",s=new w(o).convert(E,L,{...t,showBoilerplate:!1,variablesPrefix:a});n.push(s),n.blank(),o.flowType==="deviceAuthorization"&&I(n,{tokenUrl:o.tokenUrl??"YOUR_TOKEN_URL",clientId:o.clientId??"YOUR_CLIENT_ID",level:0});const i=o.flowType==="deviceAuthorization"?"$accessToken":`${y("response",a)}->access_token`;e.allHeaders.Authorization=`Bearer " . ${i}`}const g=Object.keys(e.headersObj).sort().map(function(a){return a==="Authorization"&&o?T('"%s: %s',a,e.allHeaders.Authorization):T('"%s: %s"',a,e.headersObj[a])});if(e.basicAuth){const{username:a,password:s}=e.basicAuth;g.push(`"Authorization: Basic " . base64_encode("${a}:${s}")`)}t.showBoilerplate&&n.push("/**").push(" * Requires libcurl").push(" */").blank(),z(e,n);let c="";if(Object.keys(e.queryObj||{}).length){const a=v(e.queryObj||{},{indent:t.indent});c="$query",n.push(`${c} = ${a};`).blank()}if(n.push(`${p} = curl_init();`),n.blank(),e.postData)switch(H(e.postData.mimeType)){case R.JSON:{const a=v(e.postData.jsonObj||{},{indent:t.indent});l=!0,r="json_encode($payload)",n.push(`$payload = ${a};`).blank();break}case R.MULTIPART:{if(e.postData.params&&e.postData.params.length>0){const a=e.postData.params.map(({name:s,value:i,fileName:$})=>$?`${t.indent}"${s}" => new CURLFile("${$}"),
`:`${t.indent}"${s}" => "${i}",
`).join("");l=!0,r="$payload",n.push(`$payload = array(
${a});`).blank()}else if(e.postData.text){const a=e.postData.text,s=a.match(/^--([^\r\n]+)/);if(s){const i=s[1],$=a.split(new RegExp(`--${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(h=>h.trim().length>0),b=[];$.forEach(h=>{const P=h.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(P){const _=P[1],k=P[2],x=h.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),A=(x?x[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');k?b.push(`${t.indent}"${_}" => new CURLFile("${k}"),
`):b.push(`${t.indent}"${_}" => "${A}",
`)}}),b.length>0?(l=!0,r="$payload",n.push(`$payload = array(
${b.join("")});`).blank()):r=`"${e.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}else r=`"${e.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}break}case R.URL_ENCODED:{const a=e.postData.params.length?e.postData.params.map(({name:s,value:i})=>`${s}=${i}`).join("&"):`${e.postData.text}`;l=!0,r="$payload",n.push(`$payload = "${a}";`).blank();break}default:r=e.postData.text;break}let u=N(e,n);c&&(u.endsWith('"')?u=u.slice(0,-1)+`?" . http_build_query(${c})`:u+=` . "?" . http_build_query(${c})`);const j=[{escape:!l,name:"CURLOPT_POSTFIELDS",value:r},{escape:!0,name:"CURLOPT_PORT",value:e.uriObj.port},{escape:!1,name:"CURLOPT_URL",value:u},{escape:!1,name:"CURLOPT_RETURNTRANSFER",value:"true"},{escape:!0,name:"CURLOPT_CUSTOMREQUEST",value:e.method.toUpperCase()}];n.push(`curl_setopt_array(${p}, [`);const m=new D({indentation:t.indent,lineJoin:`
${t.indent}`,variablesPrefix:t.variablesPrefix,capitalize:!0,lang:C.PHP});g.length&&m.push("CURLOPT_HTTPHEADER => [").push(1,g.join(`,
`+t.indent+t.indent)).push("],"),j.forEach(function(a){[null,void 0,""].includes(a.value)||m.push(T("%s => %s,",a.name,a.escape?JSON.stringify(a.value):a.value))});const U=e.cookies.map(function(a){return encodeURIComponent(a.name)+"="+encodeURIComponent(a.value)});return U.length&&m.push(T('CURLOPT_COOKIE => "%s",',U.join("; "))),n.push(1,m.join()).push("]);").blank().push(`${O} = curl_exec(${p});`).push(`${f} = curl_error(${p});`).blank().push(`curl_close(${p});`).blank().push(`if (${f}) {`),t.namedErrors?n.push(1,`echo array_flip(get_defined_constants(true)["curl"])[${f}];`):n.push(1,`echo "cURL Error #:" . ${f};`),n.push("} else {").push(1,`echo ${O};`).push("}"),!t.noTags&&t.closingTag&&n.blank().push("?>"),n.join()},Z={key:"curl",title:"cURL",link:"http://php.net/manual/en/book.curl.php",description:"PHP with ext-curl"};var ee=V;export{ee as default,Z as info};
