Pool   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 14
c 1
b 0
f 0
dl 0
loc 44
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A count() 0 3 1
A free() 0 7 2
A get() 0 5 2
A __construct() 0 3 1
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