Skip to content

Commit fa122af

Browse files
committed
Avoid throwing exceptions by creating a php://memory fallback stream
1 parent 7070677 commit fa122af

File tree

2 files changed

+36
-13
lines changed

2 files changed

+36
-13
lines changed

src/CarbonClientServiceProvider.php

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22
namespace xmarcos\Silex;
33

4+
use ErrorException;
45
use Silex\Application;
56
use xmarcos\Carbon\Client;
67
use InvalidArgumentException;
@@ -55,21 +56,27 @@ private function createClient(array $params = [])
5556
array_intersect_key($params, $defaults)
5657
);
5758

58-
if (!empty($args['stream'])) {
59-
$stream = $args['stream'];
60-
} else {
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+
});
6166
$address = sprintf('%s://%s:%d', $args['transport'], $args['host'], $args['port']);
62-
$stream = @stream_socket_client($address);
67+
$stream = stream_socket_client($address);
68+
restore_error_handler();
6369
}
6470

6571
try {
6672
$carbon = new Client($stream);
6773
$carbon->setNamespace($args['namespace']);
68-
69-
return $carbon;
7074
} catch (InvalidArgumentException $e) {
71-
throw $e;
75+
$carbon = new Client(fopen('php://memory', 'r'));
76+
$carbon->setNamespace($args['namespace']);
7277
}
78+
79+
return $carbon;
7380
}
7481

7582
/**

tests/CarbonClientServiceProviderTest.php

+22-6
Original file line numberDiff line numberDiff line change
@@ -84,15 +84,31 @@ public function testRegisterWithNamespace()
8484
}
8585

8686
/**
87-
* @expectedException InvalidArgumentException
87+
* @dataProvider providerWrongParams
8888
*/
89-
public function testRegisterWithInvaidParamsThrowsException()
89+
public function testRegisterWithInvalidStreamCreatesFallbackMemoryStream($params)
9090
{
9191
$this->app->register(new CarbonClientServiceProvider(), [
92-
'carbon.params' => [
93-
'transport' => 'invalid_transport',
94-
]
92+
'carbon.params' => $params
9593
]);
96-
$trigger_exception = $this->app['carbon'];
94+
$carbon_stream = (new ReflectionClass($this->app['carbon']))->getProperty('stream');
95+
$carbon_stream->setAccessible(true);
96+
97+
$type = stream_get_meta_data($carbon_stream->getValue($this->app['carbon']))['stream_type'];
98+
$this->assertEquals('MEMORY', $type);
99+
}
100+
101+
public function providerWrongParams()
102+
{
103+
return [
104+
[['transport' => 'invalid_transport']],
105+
[
106+
[
107+
'transport' => 'tcp',
108+
'host' => 'localhost',
109+
'port' => 25,
110+
]
111+
],
112+
];
97113
}
98114
}

0 commit comments

Comments
 (0)