summaryrefslogtreecommitdiff
path: root/vendor/aura/router/hold/Headers.php
blob: 6ddf1d30cf1535314a7fcd932e7c22fc2a6ba719 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace Aura\Router\Rule;

use Aura\Router\Route;
use Psr\Http\Message\ServerRequestInterface;

// must match **all** headers
class Headers
{
    /**
     *
     * Checks that header values match their related regular expressions, and
     * captures the headers as attributes.
     *
     * @param ServerRequestInterface $request The HTTP request.
     *
     * @param Route $route The route.
     *
     * @return bool True on success, false on failure.
     *
     */
    public function __invoke(ServerRequestInterface $request, Route $route)
    {
        $routeHeaders = $route->headers;
        if (! $routeHeaders) {
            return true;
        }

        $requestHeaders = $request->getHeaders();
        $attributes = [];
        foreach ($routeHeaders as $name => $regex) {
            $match = $this->match($requestHeaders, $name, $regex);
            if ($match === false) {
                return false;
            }
            $attributes[$name] = $match;
        }

        $route->addAttributes($attributes);
        return true;
    }

    /**
     *
     * Does a header value match a regex?
     *
     * @param $headers The array of all request headers.
     *
     * @param string $name The header name to look for.
     *
     * @param string $regex The regex to match against.
     *
     * @return string The match.
     *
     */
    protected function match($headers, $name, $regex)
    {
        $name = strtolower($name);
        if (! isset($headers[$name])) {
            return false;
        }

        foreach ($headers[$name] as $value) {
            if (preg_match($regex, $value, $matches)) {
                return $value;
            }
        }

        return false;
    }
}