1: <?php
2:
3: namespace PHPFastCGI\FastCGIDaemon\Connection;
4:
5: use PHPFastCGI\FastCGIDaemon\Exception\ConnectionException;
6:
7: /**
8: * The default implementation of the ConnectionInterface using stream socket
9: * resources.
10: */
11: class StreamSocketConnection implements ConnectionInterface
12: {
13: /**
14: * @var resource
15: */
16: private $socket;
17:
18: /**
19: * @var bool
20: */
21: private $closed;
22:
23: /**
24: * Constructor.
25: *
26: * @param resource $socket The stream socket to wrap
27: */
28: public function __construct($socket)
29: {
30: $this->socket = $socket;
31: $this->closed = false;
32: }
33:
34: /**
35: * Creates a formatted exception from the last error that occurecd.
36: *
37: * @param string $function The function that failed
38: *
39: * @return ConnectionException
40: */
41: protected function createExceptionFromLastError($function)
42: {
43: $this->close();
44:
45: return new ConnectionException($function.' failed');
46: }
47:
48: /**
49: * {@inheritdoc}
50: */
51: public function read($length)
52: {
53: if ($this->isClosed()) {
54: throw new ConnectionException('Connection has been closed');
55: }
56:
57: if (0 === $length) {
58: return '';
59: }
60:
61: $buffer = @fread($this->socket, $length);
62:
63: if (empty($buffer)) {
64: throw $this->createExceptionFromLastError('fread');
65: }
66:
67: return $buffer;
68: }
69:
70: /**
71: * {@inheritdoc}
72: */
73: public function write($buffer)
74: {
75: if ($this->isClosed()) {
76: throw new ConnectionException('Connection has been closed');
77: }
78:
79: if (false == @fwrite($this->socket, $buffer)) {
80: throw $this->createExceptionFromLastError('fwrite');
81: }
82: }
83:
84: /**
85: * {@inheritdoc}
86: */
87: public function isClosed()
88: {
89: return $this->closed;
90: }
91:
92: /**
93: * {@inheritdoc}
94: */
95: public function close()
96: {
97: if (!$this->isClosed()) {
98: fclose($this->socket);
99:
100: $this->socket = null;
101: $this->closed = true;
102: }
103: }
104: }
105: