StreamServer::listen()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Helix\Socket;
4
5
/**
6
 * Server that accepts and wraps incoming connections as client instances.
7
 */
8
class StreamServer extends AbstractServer {
9
10
    /**
11
     * `SOCK_STREAM`
12
     *
13
     * @return int
14
     */
15
    final public static function getType (): int {
16
        return SOCK_STREAM;
17
    }
18
19
    /**
20
     * Accepts an incoming client connection.
21
     * This will block unless the server was selected for reading.
22
     *
23
     * @see https://php.net/socket_accept
24
     *
25
     * @return StreamClient
26
     * @throws SocketError
27
     */
28
    public function accept (): StreamClient {
29
        if (!$resource = @socket_accept($this->resource)) {
30
            throw new SocketError($this->resource); // reliable errno
31
        }
32
        return $this->newClient($resource);
33
    }
34
35
    /**
36
     * Enables incoming connections.
37
     *
38
     * Listening without binding first will cause the socket to bind to a random port on *all* network interfaces.
39
     *
40
     * @see https://php.net/socket_listen
41
     *
42
     * @see bind()
43
     *
44
     * @param int $backlog Connection queue size, or `0` to use the system's default.
45
     * @return $this
46
     * @throws SocketError
47
     */
48
    public function listen (int $backlog = 0) {
49
        if (!@socket_listen($this->resource, $backlog)) {
50
            throw new SocketError($this->resource); // reliable errno
51
        }
52
        return $this;
53
    }
54
55
    /**
56
     * Wraps an accepted connection.
57
     *
58
     * @param resource $resource The accepted connection.
59
     * @return StreamClient
60
     */
61
    protected function newClient ($resource): StreamClient {
62
        return new StreamClient($resource);
63
    }
64
65
}
66