AnonymousRequestMatcher::matches()   A
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 20
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 8
c 2
b 0
f 0
nc 7
nop 1
dl 0
loc 20
ccs 9
cts 9
cp 1
crap 6
rs 9.2222
1
<?php
2
3
/*
4
 * This file is part of the FOSHttpCache package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\HttpCache\UserContext;
13
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
16
use Symfony\Component\OptionsResolver\OptionsResolver;
17
18
/**
19
 * Matches anonymous requests using a list of identification headers.
20
 */
21
class AnonymousRequestMatcher implements RequestMatcherInterface
22
{
23
    /**
24
     * @var array
25
     */
26
    private $options;
27
28
    /**
29
     * @param array $options Configuration for the matcher. All options are required because this matcher is usually
30
     *                       created by the UserContextListener which provides the default values.
31
     *
32
     * @throws \InvalidArgumentException if unknown keys are found in $options
33
     */
34 10
    public function __construct(array $options = [])
35
    {
36 10
        $resolver = new OptionsResolver();
37 10
        $resolver->setRequired(['user_identifier_headers', 'session_name_prefix']);
38
39
        // actually string[] but that is not supported by symfony < 3.4
40 10
        $resolver->setAllowedTypes('user_identifier_headers', ['array']);
41 10
        $resolver->setAllowedTypes('session_name_prefix', ['string', 'boolean']);
42
43 10
        $this->options = $resolver->resolve($options);
44 10
    }
45
46 10
    public function matches(Request $request): bool
47
    {
48
        // You might have to enable rewriting of the Authorization header in your server config or .htaccess:
49
        // RewriteEngine On
50
        // RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
51 10
        foreach ($this->options['user_identifier_headers'] as $header) {
52 10
            if ($request->headers->has($header)) {
53 3
                return false;
54
            }
55
        }
56
57 7
        if ($this->options['session_name_prefix']) {
58 5
            foreach ($request->cookies as $name => $value) {
59 3
                if (0 === strpos($name, $this->options['session_name_prefix'])) {
60 2
                    return false;
61
                }
62
            }
63
        }
64
65 5
        return true;
66
    }
67
}
68