Completed
Push — master ( 2b1385...7c6a84 )
by Thomas
07:21
created

Mock::onBefore()   D

Complexity

Conditions 10
Paths 12

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 32
rs 4.8197
cc 10
eloc 19
nc 12
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace GuzzleHttp\Subscriber;
3
4
use GuzzleHttp\Event\RequestEvents;
5
use GuzzleHttp\Event\SubscriberInterface;
6
use GuzzleHttp\Event\BeforeEvent;
7
use GuzzleHttp\Exception\RequestException;
8
use GuzzleHttp\Message\MessageFactory;
9
use GuzzleHttp\Message\ResponseInterface;
10
use GuzzleHttp\Stream\StreamInterface;
11
12
/**
13
 * Queues mock responses or exceptions and delivers mock responses or
14
 * exceptions in a fifo order.
15
 */
16
class Mock implements SubscriberInterface, \Countable
17
{
18
    /** @var array Array of mock responses / exceptions */
19
    private $queue = [];
20
21
    /** @var bool Whether or not to consume an entity body when mocking */
22
    private $readBodies;
23
24
    /** @var MessageFactory */
25
    private $factory;
26
27
    /**
28
     * @param array $items      Array of responses or exceptions to queue
29
     * @param bool  $readBodies Set to false to not consume the entity body of
30
     *                          a request when a mock is served.
31
     */
32
    public function __construct(array $items = [], $readBodies = true)
33
    {
34
        $this->factory = new MessageFactory();
35
        $this->readBodies = $readBodies;
36
        $this->addMultiple($items);
37
    }
38
39
    public function getEvents()
40
    {
41
        // Fire the event last, after signing
42
        return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST - 10]];
43
    }
44
45
    /**
46
     * @throws \OutOfBoundsException|\Exception
47
     */
48
    public function onBefore(BeforeEvent $event)
49
    {
50
        if (!$item = array_shift($this->queue)) {
51
            throw new \OutOfBoundsException('Mock queue is empty');
52
        } elseif ($item instanceof RequestException) {
53
            throw $item;
54
        }
55
56
        // Emulate reading a response body
57
        $request = $event->getRequest();
58
        if ($this->readBodies && $request->getBody()) {
59
            while (!$request->getBody()->eof()) {
60
                $request->getBody()->read(8096);
61
            }
62
        }
63
64
        $saveTo = $event->getRequest()->getConfig()->get('save_to');
65
66
        if (null !== $saveTo) {
67
            $body = $item->getBody();
68
69
            if (is_resource($saveTo)) {
70
                fwrite($saveTo, $body);
71
            } elseif (is_string($saveTo)) {
72
                file_put_contents($saveTo, $body);
73
            } elseif ($saveTo instanceof StreamInterface) {
74
                $saveTo->write($body);
75
            }
76
        }
77
78
        $event->intercept($item);
79
    }
80
81
    public function count()
82
    {
83
        return count($this->queue);
84
    }
85
86
    /**
87
     * Add a response to the end of the queue
88
     *
89
     * @param string|ResponseInterface $response Response or path to response file
90
     *
91
     * @return self
92
     * @throws \InvalidArgumentException if a string or Response is not passed
93
     */
94
    public function addResponse($response)
95
    {
96
        if (is_string($response)) {
97
            $response = file_exists($response)
98
                ? $this->factory->fromMessage(file_get_contents($response))
99
                : $this->factory->fromMessage($response);
100
        } elseif (!($response instanceof ResponseInterface)) {
101
            throw new \InvalidArgumentException('Response must a message '
102
                . 'string, response object, or path to a file');
103
        }
104
105
        $this->queue[] = $response;
106
107
        return $this;
108
    }
109
110
    /**
111
     * Add an exception to the end of the queue
112
     *
113
     * @param RequestException $e Exception to throw when the request is executed
114
     *
115
     * @return self
116
     */
117
    public function addException(RequestException $e)
118
    {
119
        $this->queue[] = $e;
120
121
        return $this;
122
    }
123
124
    /**
125
     * Add multiple items to the queue
126
     *
127
     * @param array $items Items to add
128
     */
129
    public function addMultiple(array $items)
130
    {
131
        foreach ($items as $item) {
132
            if ($item instanceof RequestException) {
133
                $this->addException($item);
134
            } else {
135
                $this->addResponse($item);
136
            }
137
        }
138
    }
139
140
    /**
141
     * Clear the queue
142
     */
143
    public function clearQueue()
144
    {
145
        $this->queue = [];
146
    }
147
}
148