Passed
Pull Request — master (#211)
by Dmitriy
06:55
created

StateResetter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 13
c 4
b 0
f 0
dl 0
loc 27
ccs 15
cts 15
cp 1
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setResetters() 0 5 2
A reset() 0 8 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Di;
6
7
use Psr\Container\ContainerInterface;
8
9
/**
10
 * State resetter allows to reset state of the services that are currently stored in the container and have "reset"
11
 * callback defined. The reset should be triggered after each request-response cycle in case you build long-running
12
 * applications with tools like [Swoole](https://www.swoole.co.uk/) or [RoadRunner](https://roadrunner.dev/).
13
 */
14
class StateResetter implements StateResetterInterface
15
{
16
    private array $resetters;
17
    private ContainerInterface $container;
18
19 5
    public function __construct(array $resetters, ContainerInterface $container)
20
    {
21 5
        $this->resetters = $resetters;
22 5
        $this->container = $container;
23 5
    }
24
25 5
    public function reset(): void
26
    {
27 5
        foreach ($this->resetters as $resetter) {
28 5
            if ($resetter instanceof StateResetterInterface) {
29 3
                $resetter->reset();
30 3
                continue;
31
            }
32 5
            $resetter($this->container);
33
        }
34 5
    }
35
36 3
    public function setResetters(array $resetters): void
37
    {
38 3
        foreach ($resetters as $serviceId => $callback) {
39 3
            $instance = $this->container->get($serviceId);
40 3
            $this->resetters[] = $callback->bindTo($instance, get_class($instance));
41
        }
42 3
    }
43
}
44