Skip to content

Commit 439141c

Browse files
committed
Accept optional rejection reason for ConnectionManagerReject
1 parent 8b73b8a commit 439141c

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,21 @@ $delayed = new ConnectionManagerDelayed($connector, 0.5, $loop);
9696

9797
### Reject
9898

99-
The `ConnectionManagerReject()` simply rejects every single connection attempt.
99+
The `ConnectionManagerReject(?string $reason)` simply rejects every single connection attempt.
100100
This is particularly useful for the below [`ConnectionManagerSelective`](#selective) to reject connection attempts
101101
to only certain destinations (for example blocking advertisements or harmful sites).
102102

103+
The constructor accepts an optional rejection reason which will be used for the
104+
`Exception` instance that is used to reject the resulting promise.
105+
106+
```php
107+
$connector = new ConnectionManagerReject('Blocked');
108+
$connector->connect('www.google.com:80')->then(null, function ($e) {
109+
assert($e instanceof \Exception);
110+
assert($e->getMessage() === 'Blocked');
111+
});
112+
```
113+
103114
### Swappable
104115

105116
The `ConnectionManagerSwappable($connector)` is a simple decorator for other `ConnectionManager`s to

src/ConnectionManagerReject.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,21 @@
99
// a simple connection manager that rejects every single connection attempt
1010
class ConnectionManagerReject implements ConnectorInterface
1111
{
12+
private $reason = 'Connection rejected';
13+
14+
/**
15+
*
16+
* @param ?string $reason
17+
*/
18+
public function __construct($reason = null)
19+
{
20+
if ($reason !== null) {
21+
$this->reason = $reason;
22+
}
23+
}
24+
1225
public function connect($_)
1326
{
14-
return Promise\reject(new Exception('Connection rejected'));
27+
return Promise\reject(new Exception($this->reason));
1528
}
1629
}

tests/ConnectionManagerRejectTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,17 @@ public function testReject()
1313

1414
$promise->then($this->expectCallableNever(), $this->expectCallableOnce());
1515
}
16+
17+
public function testRejectWithCustomMessage()
18+
{
19+
$cm = new ConnectionManagerReject('Blocked');
20+
$promise = $cm->connect('www.google.com:80');
21+
22+
$text = null;
23+
$promise->then($this->expectCallableNever(), function (Exception $e) use (&$text) {
24+
$text = $e->getMessage();
25+
});
26+
27+
$this->assertEquals('Blocked', $text);
28+
}
1629
}

0 commit comments

Comments
 (0)