1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Async sockets |
4
|
|
|
* |
5
|
|
|
* @copyright Copyright (c) 2015-2017, Efimov Evgenij <[email protected]> |
6
|
|
|
* |
7
|
|
|
* This source file is subject to the MIT license that is bundled |
8
|
|
|
* with this source code in the file LICENSE. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace AsyncSockets\Configuration; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class StreamContext |
15
|
|
|
*/ |
16
|
|
|
class StreamContext |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Stream context resource |
20
|
|
|
* |
21
|
|
|
* @var resource |
22
|
|
|
*/ |
23
|
|
|
private $resource; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* StreamContext constructor. |
27
|
|
|
* |
28
|
|
|
* @param array|resource|\Traversable|null $settings Context options |
29
|
|
|
*/ |
30
|
187 |
|
public function __construct($settings) |
31
|
|
|
{ |
32
|
187 |
|
$this->resource = $this->createResource($settings); |
33
|
186 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Return stream context resource |
37
|
|
|
* |
38
|
|
|
* @return resource |
39
|
|
|
*/ |
40
|
167 |
|
public function getResource() |
41
|
|
|
{ |
42
|
167 |
|
return $this->resource; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Creates resource from given settings |
47
|
|
|
* |
48
|
|
|
* @param array|resource|\Traversable|null $settings Context settings |
49
|
|
|
* |
50
|
|
|
* @return resource |
51
|
|
|
*/ |
52
|
187 |
|
protected function createResource($settings) |
53
|
|
|
{ |
54
|
187 |
|
if ($settings instanceof \Traversable) { |
55
|
|
|
$settings = iterator_to_array($settings); |
56
|
|
|
} |
57
|
|
|
|
58
|
187 |
|
if (is_resource($settings)) { |
59
|
156 |
|
return $settings; |
60
|
187 |
|
} elseif (is_array($settings)) { |
61
|
9 |
|
return stream_context_create( |
62
|
9 |
|
isset($settings[ 'options' ]) ? $settings[ 'options' ] : [ ], |
63
|
9 |
|
isset($settings[ 'params' ]) ? $settings[ 'params' ] : [ ] |
64
|
9 |
|
); |
65
|
183 |
|
} elseif ($settings === null) { |
66
|
182 |
|
return stream_context_get_default(); |
67
|
|
|
} else { |
68
|
1 |
|
throw new \InvalidArgumentException( |
69
|
1 |
|
sprintf( |
70
|
1 |
|
'Can not create stream context for variable type %s', |
71
|
1 |
|
is_object($settings) ? get_class($settings) : gettype($settings) |
72
|
1 |
|
) |
73
|
1 |
|
); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|