Debian Codegraph @

vendor/clue/buzz-react/src/Io/ChunkedEncoder.php

raw
1 <?php
2
3 namespace Clue\React\Buzz\Io;
4
5 use Evenement\EventEmitter;
6 use React\Stream\ReadableStreamInterface;
7 use React\Stream\Util;
8 use React\Stream\WritableStreamInterface;
9
10 /**
11 * [Internal] Encodes given payload stream with "Transfer-Encoding: chunked" and emits encoded data
12 *
13 * This is used internally to encode outgoing requests with this encoding.
14 *
15 * @internal
16 * @link https://github.com/reactphp/http/blob/master/src/Io/ChunkedEncoder.php Originally from react/http
17 */
18 class ChunkedEncoder extends EventEmitter implements ReadableStreamInterface
19 {
20 private $input;
21 private $closed = false;
22
23 public function __construct(ReadableStreamInterface $input)
24 {
25 $this->input = $input;
26
27 $this->input->on('data', array($this, 'handleData'));
28 $this->input->on('end', array($this, 'handleEnd'));
29 $this->input->on('error', array($this, 'handleError'));
30 $this->input->on('close', array($this, 'close'));
31 }
32
33 public function isReadable()
34 {
35 return !$this->closed && $this->input->isReadable();
36 }
37
38 public function pause()
39 {
40 $this->input->pause();
41 }
42
43 public function resume()
44 {
45 $this->input->resume();
46 }
47
48 public function pipe(WritableStreamInterface $dest, array $options = array())
49 {
50 return Util::pipe($this, $dest, $options);
51 }
52
53 public function close()
54 {
55 if ($this->closed) {
56 return;
57 }
58
59 $this->closed = true;
60 $this->input->close();
61
62 $this->emit('close');
63 $this->removeAllListeners();
64 }
65
66 /** @internal */
67 public function handleData($data)
68 {
69 if ($data !== '') {
70 $this->emit('data', array(
71 dechex(strlen($data)) . "\r\n" . $data . "\r\n"
72 ));
73 }
74 }
75
76 /** @internal */
77 public function handleError(\Exception $e)
78 {
79 $this->emit('error', array($e));
80 $this->close();
81 }
82
83 /** @internal */
84 public function handleEnd()
85 {
86 $this->emit('data', array("0\r\n\r\n"));
87
88 if (!$this->closed) {
89 $this->emit('end');
90 $this->close();
91 }
92 }
93 }