Skip to content

Commit

Permalink
Allow handlers to be not only closures
Browse files Browse the repository at this point in the history
  • Loading branch information
jsanahuja committed May 14, 2021
1 parent 3bbb45f commit 4ced297
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "sowe/websocketio",
"description": "SocketIO implementation using RFC6455-compliant websockets only. Built on top of Swoole Websocket Server.",
"version": "1.0.1",
"version": "1.0.2",
"type": "library",
"license": "MIT",
"keywords": [
Expand Down
27 changes: 21 additions & 6 deletions src/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,28 @@

class Handler
{
protected $closure;
protected $callable;
protected $requiredArguments;

public function __construct(callable $closure)
public function __construct(callable $callable)
{
$this->closure = $closure;
$reflection = new \ReflectionFunction($closure);
$this->callable = $callable;

if ($callable instanceof \Closure) {
$reflection = new \ReflectionFunction($callable);
} elseif (is_string($callable)) {
$parts = explode('::', $callable);
if (sizeof($parts) > 1) {
$reflection = new \ReflectionMethod(...$parts);
} else {
$reflection = new \ReflectionFunction($callable);
}
} elseif (!is_array($callable)) {
$reflection = new ReflectionMethod($callable, '__invoke');
} else {
$reflection = new ReflectionMethod(...$callable);
}

$this->requiredArguments = $reflection->getNumberOfRequiredParameters();
}

Expand All @@ -20,8 +35,8 @@ public function handle(array $arguments)
if ($argc < $this->requiredArguments) {
throw new \Exception("Expected " . $this->requiredArguments . " arguments, got " . $argc);
}
$closure = $this->closure;
$closure(...$arguments);
$callable = $this->callable;
$callable(...$arguments);
return true;
}
}

0 comments on commit 4ced297

Please sign in to comment.