Completed
Push — master ( 17598f...abee1f )
by Kirill
13s queued 11s
created

ContainerScope::getContainer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Core;
13
14
use Psr\Container\ContainerInterface;
15
use Throwable;
16
17
/**
18
 * Scope class provides ability to enable or disable global container access within specific access scope.
19
 *
20
 * @internal
21
 */
22
final class ContainerScope
23
{
24
    /** @var ContainerInterface */
25
    private static $container;
26
27
    /**
28
     * Returns currently active container scope if any.
29
     *
30
     * @return null|ContainerInterface
31
     */
32
    public static function getContainer(): ?ContainerInterface
33
    {
34
        return self::$container;
35
    }
36
37
    /**
38
     * Invokes given closure or function withing global IoC scope.
39
     *
40
     * @param ContainerInterface $container
41
     * @param callable           $scope
42
     * @return mixed
43
     * @throws Throwable
44
     */
45
    public static function runScope(ContainerInterface $container, callable $scope)
46
    {
47
        [$previous, self::$container] = [self::$container, $container];
48
49
        try {
50
            return $scope();
51
        } catch (Throwable $e) {
52
            throw $e;
53
        } finally {
54
            self::$container = $previous;
55
        }
56
    }
57
}
58