Completed
Push — master ( 629a06...9c9afe )
by David
13s
created

AnonymousRequestMatcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 1
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
    public function __construct(array $options = [])
35
    {
36
        $resolver = new OptionsResolver();
37
        $resolver->setRequired(['user_identifier_headers', 'session_name_prefix']);
38
39
        // actually string[] but that is not supported by symfony < 3.4
40
        $resolver->setAllowedTypes('user_identifier_headers', ['array']);
41
        $resolver->setAllowedTypes('session_name_prefix', ['string', 'boolean']);
42
43
        $this->options = $resolver->resolve($options);
44
    }
45
46
    public function matches(Request $request)
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
        foreach ($this->options['user_identifier_headers'] as $header) {
52
            if ($request->headers->has($header)) {
53
                return false;
54
            }
55
        }
56
57
        if ($this->options['session_name_prefix']) {
58
            foreach ($request->cookies as $name => $value) {
59
                if (0 === strpos($name, $this->options['session_name_prefix'])) {
60
                    return false;
61
                }
62
            }
63
        }
64
65
        return true;
66
    }
67
}
68