1
|
|
|
<?php namespace Limoncello\Core\Routing\Traits; |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright 2015-2017 [email protected] |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
7
|
|
|
* you may not use this file except in compliance with the License. |
8
|
|
|
* You may obtain a copy of the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15
|
|
|
* See the License for the specific language governing permissions and |
16
|
|
|
* limitations under the License. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
use Closure; |
20
|
|
|
use LogicException; |
21
|
|
|
use Psr\Container\ContainerInterface; |
22
|
|
|
use Psr\Http\Message\ResponseInterface; |
23
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @package Limoncello\Core |
27
|
|
|
* |
28
|
|
|
* @method string getCallableToCacheMessage(); |
29
|
|
|
*/ |
30
|
|
|
trait HasMiddlewareTrait |
31
|
|
|
{ |
32
|
|
|
/** |
33
|
|
|
* @var callable[] |
34
|
|
|
*/ |
35
|
|
|
private $middleware = []; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param callable[] $middleware |
39
|
|
|
* |
40
|
|
|
* @return self |
41
|
|
|
*/ |
42
|
20 |
|
public function setMiddleware(array $middleware): self |
43
|
|
|
{ |
44
|
20 |
|
foreach ($middleware as $item) { |
45
|
16 |
|
$isValid = $this->checkPublicStaticCallable($item, [ |
|
|
|
|
46
|
16 |
|
ServerRequestInterface::class, |
47
|
|
|
Closure::class, |
48
|
|
|
ContainerInterface::class, |
49
|
16 |
|
], ResponseInterface::class); |
50
|
16 |
|
if ($isValid === false) { |
51
|
16 |
|
throw new LogicException($this->getCallableToCacheMessage()); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
18 |
|
$this->middleware = $middleware; |
56
|
|
|
|
57
|
18 |
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param callable[] $middleware |
62
|
|
|
* |
63
|
|
|
* @return self |
64
|
|
|
*/ |
65
|
|
|
public function addMiddleware(array $middleware): self |
66
|
|
|
{ |
67
|
|
|
return $this->setMiddleware(array_merge($this->middleware, $middleware)); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.