<?php
namespace Engine\Soap;

class SoapClientCurl extends SoapClient
{
	/**
	 * Set configuration
	 */
	protected function iniSet()
	{
		// SET FLAGS
		ini_set("soap.wsdl_cache_enabled", 1);
		ini_set("soap.wsdl_cache", WSDL_CACHE_DISK);

	}


	/**
	 * (non-PHPdoc)
	 * @see SoapClient::__doRequest()
	 * @see http://php.net/manual/en/function.curl-setopt.php
	 * @see http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
	 * @see http://stackoverflow.com/questions/10308915/php-default-curl-timeout-value
	 */
	public function __doRequest(string $request, string $location, string $action, int $version, bool $one_way = FALSE) :?string
	{

		// Call via Curl and use the timeout
		$curl = curl_init ( $location );

		curl_setopt($curl, CURLOPT_VERBOSE, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl, CURLOPT_POST, TRUE);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
		curl_setopt($curl, CURLOPT_HEADER, FALSE);

		$HTTPheaders = [];
		$HTTPheaders[] = "Content-Type: text/xml";
		foreach ($this->options->HTTPHeaders as $HTTPheader) {
			// escape headers, remove newlines
			$HTTPheaders[] = sprintf("%s: %s", $HTTPheader['key'], str_replace("\n", "", $HTTPheader['value']));
		}
		curl_setopt($curl, CURLOPT_HTTPHEADER, $HTTPheaders);

		if ($this->options->socket_timeout) {
			curl_setopt($curl, CURLOPT_TIMEOUT, $this->options->socket_timeout);
		}
		if ($this->options->connection_timeout) {
			curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->options->connection_timeout);
		}

// 		curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false); // TODO: to be configured in the future; is this needed/used?
// 		curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);

		$response = curl_exec($curl);

		if (curl_errno( $curl )) {
			throw new \SoapFault(sprintf("CURL error %d", curl_errno($curl)), curl_error($curl));
		}

//		curl_close($curl);

		// Return?
		if (! $one_way) {
			return ($response);
		}
		return null;

	}
}
