Passed
Pull Request — master (#9)
by Roman
03:21
created

DefaultRequestProcessor::addStep()   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 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Kami\ApiCoreBundle\RequestProcessor;
4
5
6
use Kami\ApiCoreBundle\RequestProcessor\Step\StepInterface;
7
use Symfony\Component\HttpFoundation\Request;
8
9
class DefaultRequestProcessor implements RequestProcessorInterface
10
{
11
    protected $availableSteps;
12
13
    protected $executedSteps;
14
15
    public function addStep($shortcut, StepInterface $step)
16
    {
17
        $this->availableSteps[$shortcut] = $step;
18
    }
19
20
    public function executeStrategy(array $strategy, Request $request)
21
    {
22
        $response = new ProcessorResponse($request, []);
23
        $this->executedSteps = [];
24
25
        foreach ($strategy as $shortcut) {
26
            $step = $this->availableSteps[$shortcut];
27
28
            $response = $this->executeStep($step, $request, $response);
29
            if (200 !== $response->getStatus()) {
30
                break;
31
            }
32
        }
33
34
        return $response->toHttpResponse();
35
    }
36
37
    protected function executeStep(StepInterface $step, $request, $response)
38
    {
39
        $this->checkHasPassedRequiredSteps($step);
40
        $step->setRequest($request);
41
        $step->setPreviousResponse($response);
42
        $response = $step->execute();
43
44
        if(!$response) {
0 ignored issues
show
introduced by
$response is of type Kami\ApiCoreBundle\Reque...essor\ResponseInterface, thus it always evaluated to true.
Loading history...
45
            throw new ProcessingException(
46
                sprintf('RequestProcessor didn\'t receive any response from %s', get_class($step)));
47
        }
48
49
        $this->executedSteps[] = $step->getName();
50
51
        return $response;
52
    }
53
54
    protected function checkHasPassedRequiredSteps(StepInterface $step)
55
    {
56
        if (0 === count($step->requiresBefore())) {
57
            return;
58
        }
59
        foreach ($step->requiresBefore() as $requiredStep) {
60
            if (!in_array($requiredStep, $this->executedSteps)) {
61
                throw new ProcessingException(sprintf(
62
                    "Request didn't pass required steps yet. Try to adjust your processing strategy\n" .
63
                    "Required steps for %s are: %s", $step->getName(), implode(',',  $step->requiresBefore())
64
                ));
65
            }
66
        }
67
    }
68
}