11
11
namespace hiqdev \hiart \stream ;
12
12
13
13
use hiqdev \hiart \AbstractRequest ;
14
+ use yii \helpers \Inflector ;
14
15
15
16
/**
16
17
* PHP stream request implementation.
@@ -21,7 +22,70 @@ class Request extends AbstractRequest
21
22
{
22
23
protected $ workerClass = RequestWorker::class;
23
24
24
- protected function createWorker ()
25
+ public $ defaultOptions = [
26
+ 'http ' => [
27
+ 'ignore_errors ' => true ,
28
+ ],
29
+ 'ssl ' => [
30
+ 'verify_peer ' => false ,
31
+ ],
32
+ ];
33
+
34
+ public function send ($ options = [])
25
35
{
36
+ $ this ->build ();
37
+
38
+ try {
39
+ $ context = stream_context_create ($ this ->prepareContextOptions ($ options ));
40
+ $ stream = fopen ($ this ->getFullUri (), 'rb ' , false , $ context );
41
+ $ responseContent = stream_get_contents ($ stream );
42
+ // see http://php.net/manual/en/reserved.variables.httpresponseheader.php
43
+ $ responseHeaders = $ http_response_header ;
44
+ fclose ($ stream );
45
+ } catch (\Exception $ e ) {
46
+ throw new Exception ($ e ->getMessage (), $ e ->getCode (), $ e );
47
+ }
48
+
49
+ return new $ this ->responseClass ($ this , $ responseContent , $ responseHeaders );
50
+ }
51
+
52
+ protected function prepareContextOptions ($ options )
53
+ {
54
+ $ requestOptions = [
55
+ 'http ' => [
56
+ 'method ' => $ this ->method ,
57
+ 'header ' => $ this ->headers ,
58
+ ],
59
+ ];
60
+
61
+ if (isset ($ this ->body )) {
62
+ $ requestOptions ['http ' ]['content ' ] = $ this ->body ;
63
+ }
64
+
65
+ $ dbOptions = $ this ->convertContextOptions ($ this ->getDb ()->requestOptions );
66
+ $ sendOptions = $ this ->convertContextOptions ($ options );
67
+
68
+ return ArrayHelper::merge ($ this ->defaultOptions , $ dbOptions , $ requestOptions , $ sendOptions );
69
+ }
70
+
71
+ /**
72
+ * Converts raw options to stream context options.
73
+ * @param array $options raw options.
74
+ * @return array stream context options.
75
+ */
76
+ protected function convertContextOptions (array $ options )
77
+ {
78
+ $ contextOptions = [];
79
+ foreach ($ options as $ key => $ value ) {
80
+ $ section = 'http ' ;
81
+ if (strpos ($ key , 'ssl ' ) === 0 ) {
82
+ $ section = 'ssl ' ;
83
+ $ key = substr ($ key , 3 );
84
+ }
85
+ $ key = Inflector::underscore ($ key );
86
+ $ contextOptions [$ section ][$ key ] = $ value ;
87
+ }
88
+
89
+ return $ contextOptions ;
26
90
}
27
91
}
0 commit comments