Skip to content

Commit

Permalink
Merge pull request #43 from localheinz/feature/extract
Browse files Browse the repository at this point in the history
Enhancement: Extract method which ensures result is or converts it to callable
  • Loading branch information
dbu committed Jun 20, 2019
2 parents 6dcd595 + 1ad4c09 commit 79f11ad
Showing 1 changed file with 30 additions and 22 deletions.
52 changes: 30 additions & 22 deletions src/Client.php
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

0 comments on commit 79f11ad

Please sign in to comment.