1
|
|
|
<?php |
2
|
|
|
namespace xmarcos\Silex; |
3
|
|
|
|
4
|
|
|
use ErrorException; |
5
|
|
|
use Silex\Application; |
6
|
|
|
use xmarcos\Carbon\Client; |
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Silex\ServiceProviderInterface; |
9
|
|
|
|
10
|
|
|
class CarbonClientServiceProvider implements ServiceProviderInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var string |
14
|
|
|
*/ |
15
|
|
|
protected $name; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param string $name Name used to register the service in Silex. |
19
|
|
|
*/ |
20
|
|
|
public function __construct($name = 'carbon') |
21
|
|
|
{ |
22
|
|
|
if (empty($name) || false === is_string($name)) { |
23
|
|
|
throw new InvalidArgumentException( |
24
|
|
|
sprintf('$name must be a non-empty string, "%s" given', gettype($name)) |
25
|
|
|
); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$this->name = $name; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
|
|
public function register(Application $app) |
35
|
|
|
{ |
36
|
|
|
$name = $this->name; |
37
|
|
|
$key = sprintf('%s.params', $name); |
38
|
|
|
$app[$key] = isset($app[$key]) ? $app[$key] : []; |
39
|
|
|
$app[$name] = $app->share(function (Application $app) use ($key) { |
40
|
|
|
return $this->createClient($app[$key]); |
41
|
|
|
}); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private function createClient(array $params = []) |
45
|
|
|
{ |
46
|
|
|
$defaults = [ |
47
|
|
|
'host' => '127.0.0.1', |
48
|
|
|
'port' => 2003, |
49
|
|
|
'transport' => 'udp', |
50
|
|
|
'namespace' => '', |
51
|
|
|
'stream' => null, |
52
|
|
|
]; |
53
|
|
|
|
54
|
|
|
$args = array_replace_recursive( |
55
|
|
|
$defaults, |
56
|
|
|
array_intersect_key($params, $defaults) |
57
|
|
|
); |
58
|
|
|
|
59
|
|
|
$stream = $args['stream']; |
60
|
|
|
$exception = null; |
61
|
|
|
|
62
|
|
|
if (!is_resource($stream)) { |
63
|
|
|
set_error_handler(function ($code, $message, $file = null, $line = 0) use (&$exception) { |
64
|
|
|
$exception = new ErrorException($message, $code, null, $file, $line); |
65
|
|
|
}); |
66
|
|
|
$address = sprintf('%s://%s:%d', $args['transport'], $args['host'], $args['port']); |
67
|
|
|
$stream = stream_socket_client($address); |
68
|
|
|
restore_error_handler(); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
try { |
72
|
|
|
$carbon = new Client($stream); |
73
|
|
|
$carbon->setNamespace($args['namespace']); |
74
|
|
|
} catch (InvalidArgumentException $e) { |
75
|
|
|
$carbon = new Client(fopen('php://memory', 'r')); |
76
|
|
|
$carbon->setNamespace($args['namespace']); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $carbon; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* {@inheritdoc} |
84
|
|
|
* @codeCoverageIgnore |
85
|
|
|
*/ |
86
|
|
|
public function boot(Application $app) |
87
|
|
|
{ |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|