summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/socket/src/ConnectionList.php
blob: 47ea4894a416b9cc2124ec91b6e572f608989413 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

namespace gipfl\Socket;

use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
use InvalidArgumentException;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;
use React\Socket\ConnectionInterface;
use SplObjectStorage;
use function React\Promise\all;

/**
 * @method ConnectionInterface current
 */
class ConnectionList extends SplObjectStorage implements EventEmitterInterface
{
    use EventEmitterTrait;

    const ON_ATTACHED = 'attached';
    const ON_DETACHED = 'detached';

    /** @var LoopInterface */
    protected $loop;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
    }

    #[\ReturnTypeWillChange]
    public function attach($object, $info = null)
    {
        if (! $object instanceof ConnectionInterface || $info !== null) {
            throw new InvalidArgumentException(sprintf(
                'Can attach only %s instances',
                ConnectionInterface::class
            ));
        }
        $object->on('close', function () use ($object) {
            $this->detach($object);
        });

        parent::attach($object, $info);
        $this->emit(self::ON_ATTACHED, [$object]);
    }

    #[\ReturnTypeWillChange]
    public function detach($object)
    {
        parent::detach($object);
        $this->emit(self::ON_DETACHED, [$object]);
    }

    public function close()
    {
        $pending = [];
        foreach ($this as $connection) {
            $pending[] = $this->closeConnection($connection, $this->loop);
        }

        return all($pending);
    }

    public static function closeConnection(ConnectionInterface $connection, LoopInterface $loop, $timeout = 5)
    {
        $deferred = new Deferred();
        $connection->end();
        if ($connection->isWritable() || $connection->isReadable()) {
            $timer = $loop->addTimer($timeout, function () use ($connection, $deferred) {
                $connection->close();
            });

            $connection->on('close', function () use ($deferred, $timer) {
                $this->loop->cancelTimer($timer);
                $deferred->resolve();
            });
        } else {
            $loop->futureTick(function () use ($deferred) {
                $deferred->resolve();
            });
        }

        return $deferred->promise();
    }
}