|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SilverStripe\Control\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use SilverStripe\Control\HTTPRequest; |
|
6
|
|
|
use SilverStripe\Control\HTTPResponse; |
|
7
|
|
|
use Symfony\Component\ExpressionLanguage\ExpressionLanguage; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* ExpressionBased Middleware. |
|
11
|
|
|
*/ |
|
12
|
|
|
class ExpressionBasedMiddleware implements HTTPMiddleware |
|
13
|
|
|
{ |
|
14
|
|
|
public $expressionLanguage; |
|
15
|
|
|
|
|
16
|
|
|
public static $dependencies = [ |
|
17
|
|
|
'expressionLanguage' => '%$'.ExpressionLanguage::class, |
|
18
|
|
|
]; |
|
19
|
|
|
|
|
20
|
|
|
protected $context; |
|
21
|
|
|
|
|
22
|
|
|
protected $expressions = []; |
|
23
|
|
|
|
|
24
|
|
|
public function __construct(array $context = []) |
|
25
|
|
|
{ |
|
26
|
|
|
$this->context = $context; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Workaround for lack of property typing in php < 7.4. |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __set(string $name, string $value) |
|
33
|
|
|
{ |
|
34
|
|
|
if (0 === strpos($name, 'req') || 0 === strpos($name, 'res')) { |
|
35
|
|
|
$this->expressions[substr($name, 0, 3)] = $value; |
|
36
|
|
|
} |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function process(HTTPRequest $request, callable $delegate) |
|
40
|
|
|
{ |
|
41
|
|
|
$this->context['req'] = $request; |
|
42
|
|
|
if (isset($this->expressions['req'])) { |
|
43
|
|
|
$result = $this->expressionLanguage->evaluate($this->expressions['req'], $this->context); |
|
44
|
|
|
if ($result instanceof HTTPResponse) { |
|
45
|
|
|
return $result; |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
$response = $delegate($request); |
|
49
|
|
|
if (isset($this->expressions['res'])) { |
|
50
|
|
|
$this->context['res'] = $response; |
|
51
|
|
|
$this->expressionLanguage->evaluate($this->expressions['res'], $this->context); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
return $response; |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|