| Conditions | 10 |
| Paths | 12 |
| Total Lines | 40 |
| Code Lines | 20 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 4 | ||
| Bugs | 2 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 70 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
|
|
|||
| 71 | { |
||
| 72 | if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) { |
||
| 73 | throw new RuntimeException('Csrf middleware needs FormatNegotiator executed before'); |
||
| 74 | } |
||
| 75 | |||
| 76 | if (!Middleware::hasAttribute($request, ClientIp::KEY)) { |
||
| 77 | throw new RuntimeException('Csrf middleware needs ClientIp executed before'); |
||
| 78 | } |
||
| 79 | |||
| 80 | if ($this->storage === null) { |
||
| 81 | if (session_status() !== PHP_SESSION_ACTIVE) { |
||
| 82 | throw new RuntimeException('Csrf middleware needs an active php session or a storage defined'); |
||
| 83 | } |
||
| 84 | |||
| 85 | if (!isset($_SESSION[$this->sessionIndex])) { |
||
| 86 | $_SESSION[$this->sessionIndex] = []; |
||
| 87 | } |
||
| 88 | |||
| 89 | $this->storage = &$_SESSION[$this->sessionIndex]; |
||
| 90 | } |
||
| 91 | |||
| 92 | if (FormatNegotiator::getFormat($request) !== 'html') { |
||
| 93 | return $next($request, $response); |
||
| 94 | } |
||
| 95 | |||
| 96 | if (Utils\Helpers::isPost($request) && !$this->validateRequest($request)) { |
||
| 97 | return $response->withStatus(403); |
||
| 98 | } |
||
| 99 | |||
| 100 | $response = $next($request, $response); |
||
| 101 | |||
| 102 | return $this->insertIntoPostForms($response, function ($match) use ($request) { |
||
| 103 | preg_match('/action=["\']?([^"\'\s]+)["\']?/i', $match[0], $matches); |
||
| 104 | |||
| 105 | $action = empty($matches[1]) ? $request->getUri()->getPath() : $matches[1]; |
||
| 106 | |||
| 107 | return $match[0].$this->generateTokens($request, $action); |
||
| 108 | }); |
||
| 109 | } |
||
| 110 | |||
| 207 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: