<?php
namespace Engine\Soap;

// TODO: trebuie inlocuit in toata TINA

/**
 * Class handles SoapClient functionalities, but options are an object
 * @author oana
 */
class SoapClient extends \SoapClient
{

	/**
	 * The SOAP client options.
	 * @var \Engine\Soap\SoapClientOptions
	 */
	protected $options = null;

	public function __construct($wsdl, \Engine\Soap\SoapClientOptions $soapOptionsObj)
	{
		$this->options = $soapOptionsObj;
		$this->iniSet();
		$options = $this->options->getOptions();
		$streamContext = [];
		$streamContext['ssl'] = [];

		if ($options['verify_peer'] !== NULL) {
			if ($options['verify_peer'] === false) {
				$streamContext['ssl']['verify_peer'] = false;
				$streamContext['ssl']['verify_peer_name'] = false;
				$streamContext['ssl']['allow_self_signed'] = true;
			}
			else {
				// TODO inject certificates manually
				throw new \Exception("Not implemented yet.");
			}
		}

		if ($options['localCertificate'] !== NULL) {
			$streamContext['ssl']['local_cert'] = 	$options['localCertificate']['certificatePath'];
			$streamContext['ssl']['passphrase'] = 	$options['localCertificate']['certificatePassword'];
			$streamContext['ssl']['local_pk'] = 	$options['localCertificate']['privateKeyPath'];
		}

		if ($options['HTTPHeaders']) {
			$HTTPHeaders = [];
			foreach ($options['HTTPHeaders'] as $HTTPHeader) {
				// escape headers, remove newlines
				$HTTPHeaders[] = sprintf("%s: %s", $HTTPHeader['key'], str_replace("\n", "", $HTTPHeader['value']));
			}
			$streamContext['http'] = [
				'header' => $HTTPHeaders,
			];
		}


		if ($streamContext) {
			$context = stream_context_create($streamContext);
			$options['stream_context'] = $context;
		}

		parent::__construct($wsdl, $options);

	}

	/**
	 * Set ini configurations.
	 */
	protected function iniSet()
	{
		// activate cache
		ini_set("soap.wsdl_cache_enabled", 1);
		ini_set("soap.wsdl_cache", WSDL_CACHE_DISK);

		if ($this->options->socket_timeout !== NULL) {
			ini_set("default_socket_timeout", $this->options->socket_timeout);
		}
	}
}
