Skip to content

Commit

Permalink
Added private method to capture errors and convert to exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
asgrim committed Dec 16, 2019
1 parent 64e31cf commit 423c047
Showing 1 changed file with 24 additions and 11 deletions.
35 changes: 24 additions & 11 deletions src/Connector/SocketConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,27 @@ public function __construct(string $socketPath)
}
}

/** @return mixed */
private function convertErrorsToExceptions(callable $functionToRun)
{
// phpcs:disable SlevomatCodingStandard.TypeHints.TypeHintDeclaration.IncorrectReturnTypeHint
set_error_handler(
static function (int $severity, string $message, string $file = '', int $line = 0, array $context = []) : bool {
throw new ErrorException($message, 0, $severity, $file, $line);
},
E_STRICT | E_NOTICE | E_WARNING
);
// phpcs:enable

try {
$returnValue = $functionToRun();
} finally {
restore_error_handler();
}

return $returnValue;
}

public function connect() : void
{
if ($this->connected()) {
Expand All @@ -63,22 +84,14 @@ public function connect() : void
try {
socket_clear_error($this->socket);

// phpcs:disable SlevomatCodingStandard.TypeHints.TypeHintDeclaration.IncorrectReturnTypeHint
set_error_handler(
static function (int $severity, string $message, string $file = '', int $line = 0, array $context = []) : bool {
throw new ErrorException($message, 0, $severity, $file, $line);
},
E_STRICT | E_NOTICE | E_WARNING
);
// phpcs:enable
$this->connected = $this->convertErrorsToExceptions(function () {
return socket_connect($this->socket, $this->socketPath);
});

$this->connected = socket_connect($this->socket, $this->socketPath);
register_shutdown_function([&$this, 'shutdown']);
} catch (Throwable $e) {
$this->connected = false;
throw FailedToConnect::fromSocketPathAndPrevious($this->socketPath, $e);
} finally {
restore_error_handler();
}
}

Expand Down

0 comments on commit 423c047

Please sign in to comment.