Pool::count()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * Decorator Implementation
6
 * @category    Ticaje
7
 * @author      Max Demian <[email protected]>
8
 */
9
10
namespace Ticaje\Contract\Patterns\Implementation\Pool;
11
12
use Countable;
13
14
use Ticaje\Contract\Patterns\Interfaces\Pool\PoolInterface;
15
use Ticaje\Contract\Patterns\Interfaces\Pool\WorkerInterface;
16
use Ticaje\Contract\Application\Service\ServiceLocator;
17
use Ticaje\Contract\Traits\CloneLess;
18
19
/**
20
 * Class Pool
21
 * @package Ticaje\Contract\Patterns\Implementation\Pool
22
 */
23
class Pool implements PoolInterface, Countable
24
{
25
    use CloneLess;
26
27
    private $serviceLocator;
28
29
    private $busyOnes = [];
30
31
    private $availableOnes = [];
32
33
    public function __construct()
34
    {
35
        $this->serviceLocator = new ServiceLocator();
36
    }
37
38
    /**
39
     * @inheritDoc
40
     */
41
    public function get($class): WorkerInterface
42
    {
43
        $instance = count($this->availableOnes) == 0 ? $this->serviceLocator->create($class) : array_pop($this->availableOnes);
44
        $this->busyOnes[spl_object_hash($instance)] = $instance;
45
        return $instance;
46
    }
47
48
    /**
49
     * @inheritDoc
50
     */
51
    public function free(WorkerInterface $worker)
52
    {
53
        $key = spl_object_hash($worker);
54
55
        if (isset($this->busyOnes[$key])) {
56
            unset($this->busyOnes[$key]);
57
            $this->availableOnes[$key] = $worker;
58
        }
59
    }
60
61
    /**
62
     * @return int
63
     */
64
    public function count(): int
65
    {
66
        return count($this->busyOnes) + count($this->availableOnes);
67
    }
68
}
69