1<?php
2namespace GuzzleHttp\Ring\Client;
3
4use GuzzleHttp\Ring\Core;
5use GuzzleHttp\Ring\Future\CompletedFutureArray;
6use GuzzleHttp\Ring\Future\FutureArrayInterface;
7
8/**
9 * Ring handler that returns a canned response or evaluated function result.
10 */
11class MockHandler
12{
13    /** @var callable|array|FutureArrayInterface */
14    private $result;
15
16    /**
17     * Provide an array or future to always return the same value. Provide a
18     * callable that accepts a request object and returns an array or future
19     * to dynamically create a response.
20     *
21     * @param array|FutureArrayInterface|callable $result Mock return value.
22     */
23    public function __construct($result)
24    {
25        $this->result = $result;
26    }
27
28    public function __invoke(array $request)
29    {
30        Core::doSleep($request);
31        $response = is_callable($this->result)
32            ? call_user_func($this->result, $request)
33            : $this->result;
34
35        if (is_array($response)) {
36            $response = new CompletedFutureArray($response + [
37                'status'        => null,
38                'body'          => null,
39                'headers'       => [],
40                'reason'        => null,
41                'effective_url' => null,
42            ]);
43        } elseif (!$response instanceof FutureArrayInterface) {
44            throw new \InvalidArgumentException(
45                'Response must be an array or FutureArrayInterface. Found '
46                . Core::describeType($request)
47            );
48        }
49
50        return $response;
51    }
52}
53