Failed Conditions
Push — ng ( 625bbc...a06888 )
by Florent
08:03
created

HttpMethodMiddleware::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Component\Middleware;
15
16
use OAuth2Framework\Component\Core\Exception\OAuth2Exception;
17
use Psr\Http\Message\ResponseInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
use Psr\Http\Server\MiddlewareInterface;
20
use Psr\Http\Server\RequestHandlerInterface;
21
22
final class HttpMethodMiddleware implements MiddlewareInterface
23
{
24
    /**
25
     * @var MiddlewareInterface[]
26
     */
27
    private $methodMap = [];
28
29
    /**
30
     * @param string              $method
31
     * @param MiddlewareInterface $middleware
32
     */
33
    public function add(string $method, MiddlewareInterface $middleware)
34
    {
35
        if (array_key_exists($method, $this->methodMap)) {
36
            throw new \InvalidArgumentException(sprintf('The method "%s" is already defined.', $method));
37
        }
38
        $this->methodMap[$method] = $middleware;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
45
    {
46
        $method = $request->getMethod();
47
48
        if (!array_key_exists($method, $this->methodMap)) {
49
            throw new OAuth2Exception(
50
                405,
51
                'not_implemented',
52
                 sprintf('The method "%s" is not supported.', $method)
53
            );
54
        }
55
56
        $middleware = $this->methodMap[$method];
57
58
        return $middleware->process($request, $handler);
59
    }
60
}
61