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) { |
|
|
|
|
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
|
|
|
} |