Skip to content

Enhancement: Extract method which ensures result is or converts it to callable #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 20, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 30 additions & 22 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,34 +122,42 @@ public function doSendRequest(RequestInterface $request)
*/
public function on(RequestMatcher $requestMatcher, $result)
{
$callable = null;

switch (true) {
case is_callable($result):
$callable = $result;

break;
case $result instanceof ResponseInterface:
$callable = function () use ($result) {
return $result;
};

break;
case $result instanceof \Exception:
$callable = function () use ($result) {
throw $result;
};

break;
default:
throw new \InvalidArgumentException('Result must be either a response, an exception, or a callable');
}
$callable = self::makeCallable($result);

$this->conditionalResults[] = [
'matcher' => $requestMatcher,
'callable' => $callable,
];
}

/**
* @param ResponseInterface|Exception|ClientExceptionInterface|callable $result
*
* @throws \InvalidArgumentException
*
* @return callable
*/
private static function makeCallable($result)
{
if (is_callable($result)) {
return $result;
}

if ($result instanceof ResponseInterface) {
return function () use ($result) {
return $result;
};
}

if ($result instanceof \Exception) {
return function () use ($result) {
throw $result;
};
}

throw new \InvalidArgumentException('Result must be either a response, an exception, or a callable');
}

/**
* Adds an exception that will be thrown.
*/
Expand Down