Completed
Branch 0.4-dev (999b58)
by Evgenij
18:41
created

onSocketRequestInitialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Async sockets
4
 *
5
 * @copyright Copyright (c) 2015-2016, Efimov Evgenij <[email protected]>
6
 *
7
 * This source file is subject to the MIT license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
namespace AsyncSockets\RequestExecutor;
11
12
use AsyncSockets\Event\Event;
13
use AsyncSockets\Event\EventType;
14
use AsyncSockets\Socket\SocketInterface;
15
16
/**
17
 * Class ConstantLimitationSolver
18
 */
19
class ConstantLimitationSolver implements LimitationSolverInterface, EventHandlerInterface
20
{
21
    /**
22
     * Limit of running requests
23
     *
24
     * @var int
25
     */
26
    private $limit;
27
28
    /**
29
     * Number of active requests now
30
     *
31
     * @var int
32
     */
33
    private $activeRequests;
34
35
    /**
36
     * ConstantLimitationSolver constructor.
37
     *
38
     * @param int $limit Limit of running requests
39
     */
40 6
    public function __construct($limit)
41
    {
42 6
        $this->limit = $limit;
43 6
    }
44
45
    /** {@inheritdoc} */
46 6
    public function initialize(RequestExecutorInterface $executor)
47
    {
48 6
        $this->activeRequests = 0;
49 6
    }
50
51
    /** {@inheritdoc} */
52 6
    public function finalize(RequestExecutorInterface $executor)
53
    {
54
        // empty body
55 6
    }
56
57
    /** {@inheritdoc} */
58 2
    public function decide(RequestExecutorInterface $executor, SocketInterface $socket, $totalSockets)
59
    {
60 2
        if ($this->activeRequests + 1 <= $this->limit) {
61 2
            return self::DECISION_OK;
62
        } else {
63 1
            return self::DECISION_PROCESS_SCHEDULED;
64
        }
65
    }
66
67
    /** {@inheritdoc} */
68 2
    public function invokeEvent(Event $event)
69
    {
70 2
        switch ($event->getType()) {
71 2
            case EventType::INITIALIZE:
72 2
                $this->onSocketRequestInitialize();
73 2
                break;
74 1
            case EventType::FINALIZE:
75 1
                $this->onSocketRequestFinalize();
76 1
                break;
77 2
        }
78 2
    }
79
80
81
    /**
82
     * Process socket initialize event
83
     *
84
     * @return void
85
     */
86 2
    private function onSocketRequestInitialize()
87
    {
88 2
        $this->activeRequests += 1;
89 2
    }
90
91
    /**
92
     * Process request termination
93
     *
94
     * @return void
95
     */
96 1
    private function onSocketRequestFinalize()
97
    {
98 1
        $this->activeRequests -= 1;
99 1
    }
100
}
101