Skip to content

Commit

Permalink
added stream transport implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
hiqsol committed Jan 22, 2017
1 parent 8718fc3 commit cd0f032
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 5 deletions.
66 changes: 65 additions & 1 deletion src/stream/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace hiqdev\hiart\stream;

use hiqdev\hiart\AbstractRequest;
use yii\helpers\Inflector;

/**
* PHP stream request implementation.
Expand All @@ -21,7 +22,70 @@ class Request extends AbstractRequest
{
protected $workerClass = RequestWorker::class;

protected function createWorker()
public $defaultOptions = [
'http' => [
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => false,
],
];

public function send($options = [])
{
$this->build();

try {
$context = stream_context_create($this->prepareContextOptions($options));
$stream = fopen($this->getFullUri(), 'rb', false, $context);
$responseContent = stream_get_contents($stream);
// see http://php.net/manual/en/reserved.variables.httpresponseheader.php
$responseHeaders = $http_response_header;
fclose($stream);
} catch (\Exception $e) {
throw new Exception($e->getMessage(), $e->getCode(), $e);
}

return new $this->responseClass($this, $responseContent, $responseHeaders);
}

protected function prepareContextOptions($options)
{
$requestOptions = [
'http' => [
'method' => $this->method,
'header' => $this->headers,
],
];

if (isset($this->body)) {
$requestOptions['http']['content'] = $this->body;
}

$dbOptions = $this->convertContextOptions($this->getDb()->requestOptions);
$sendOptions = $this->convertContextOptions($options);

return ArrayHelper::merge($this->defaultOptions, $dbOptions, $requestOptions, $sendOptions);
}

/**
* Converts raw options to stream context options.
* @param array $options raw options.
* @return array stream context options.
*/
protected function convertContextOptions(array $options)
{
$contextOptions = [];
foreach ($options as $key => $value) {
$section = 'http';
if (strpos($key, 'ssl') === 0) {
$section = 'ssl';
$key = substr($key, 3);
}
$key = Inflector::underscore($key);
$contextOptions[$section][$key] = $value;
}

return $contextOptions;
}
}
24 changes: 20 additions & 4 deletions src/stream/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,24 @@
*/
class Response extends AbstractResponse
{
/**
* @var ResponseWorker
*/
protected $worker;
protected $rawData;

protected $headers;

public function __construct(Request $request, $rawData, array $headers)
{
$this->request = $request;
$this->rawData = $rawData;
$this->headers = $headers;
}

public function getRawData()
{
return $this->rawData;
}

public function getHeader($name)
{
return isset($this->headers[$name]) ? $this->headers[$name] : null;
}
}

0 comments on commit cd0f032

Please sign in to comment.