AbstractServer::bind()   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 2
1
<?php
2
3
namespace Helix\Socket;
4
5
use Throwable;
6
7
/**
8
 * Abstract server socket.
9
 */
10
abstract class AbstractServer extends AbstractSocket {
11
12
    /**
13
     * The server's name as `<address>:<port>`,
14
     * or `<filepath>:0` for Unix sockets,
15
     * or `?<id>` if a name can't be derived (e.g. the socket is closed).
16
     *
17
     * @see getSockName()
18
     *
19
     * @return string
20
     */
21
    public function __toString () {
22
        try {
23
            return implode(':', $this->getSockName());
24
        }
25
        catch (Throwable $e) {
26
            return "?{$this->resource}";
27
        }
28
    }
29
30
    /**
31
     * Binds to an address and port, or file path (Unix) for the OS to create, so the server can listen.
32
     *
33
     * Unix sockets do not honor `SO_REUSEADDR`.
34
     * It is your responsibility to remove unused socket files.
35
     *
36
     * @see https://php.net/socket_bind
37
     *
38
     * @param string $address
39
     * @param int $port Zero for a random unused network port. Unix sockets ignore the port entirely.
40
     * @return $this
41
     * @throws SocketError
42
     */
43
    public function bind (string $address, int $port = 0) {
44
        if (!@socket_bind($this->resource, $address, $port)) {
45
            throw new SocketError($this->resource, SOCKET_EOPNOTSUPP);
46
        }
47
        return $this;
48
    }
49
50
}
51