Completed
Branch 09branch (a008bb)
by Anton
03:16
created

AbstractCore::callAction()   B

Complexity

Conditions 5
Paths 15

Size

Total Lines 48
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 26
nc 15
nop 4
dl 0
loc 48
rs 8.551
c 0
b 0
f 0
1
<?php
2
/**
3
 * spiral
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\Core;
8
9
use Spiral\Core\Exceptions\ControllerException;
10
use Spiral\Core\HMVC\ControllerInterface;
11
use Spiral\Core\HMVC\CoreInterface;
12
use Spiral\Debug\Traits\BenchmarkTrait;
13
14
/**
15
 * Provides ability to call controllers in IoC scope.
16
 */
17
abstract class AbstractCore extends Component implements CoreInterface
18
{
19
    use BenchmarkTrait;
20
21
    /**
22
     * @invisible
23
     * @var ContainerInterface
24
     */
25
    protected $container;
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function callAction(
31
        string $controller,
32
        string $action = null,
33
        array $parameters = [],
34
        array $scope = []
35
    ) {
36
        if (!class_exists($controller)) {
37
            throw new ControllerException(
38
                "No such controller '{$controller}' found",
39
                ControllerException::NOT_FOUND
40
            );
41
        }
42
43
        $benchmark = $this->benchmark('callAction', $controller . '::' . ($action ?? '~default~'));
44
45
        //Making sure that all static functionality works well
46
        $iocScope = self::staticContainer($this->container);
47
48
        //Working with container scope
49
        foreach ($scope as $alias => &$target) {
50
            $target = $this->container->replace($alias, $target);
51
            unset($target);
52
        }
53
54
        try {
55
            //Getting instance of controller
56
            $instance = $this->container->get($controller);
57
58
            if (!$instance instanceof ControllerInterface) {
59
                throw new ControllerException(
60
                    "No such controller '{$controller}' found",
61
                    ControllerException::NOT_FOUND
62
                );
63
            }
64
65
            return $instance->callAction($action, $parameters);
66
        } finally {
67
            $this->benchmark($benchmark);
68
69
            //Restoring container scope
70
            foreach (array_reverse($scope) as $payload) {
71
                $this->container->restore($payload);
72
            }
73
74
            //Restoring shared container to it's original state
75
            self::staticContainer($iocScope);
76
        }
77
    }
78
}