Completed
Pull Request — master (#336)
by Tobias
05:28
created

DefaultHashGenerator::generateHash()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
crap 2
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 FOS\HttpCache\Exception\InvalidArgumentException;
15
16
/**
17
 * Generate a hash for a UserContext by getting all the parameters needed across all registered services.
18
 */
19
class DefaultHashGenerator
20
{
21
    /**
22
     * @var ContextProvider[]
23
     */
24
    private $providers = [];
25
26
    /**
27
     * Constructor.
28
     *
29
     * @param ContextProvider[] $providers
30
     *
31
     * @throws InvalidArgumentException If no providers are supplied
32
     */
33 2
    public function __construct(array $providers)
34
    {
35 2
        if (0 === count($providers)) {
36 1
            throw new InvalidArgumentException('You must supply at least one provider');
37
        }
38
39 1
        foreach ($providers as $provider) {
40 1
            $this->registerProvider($provider);
41 1
        }
42 1
    }
43
44
    /**
45
     * Collect UserContext parameters and generate a hash from that.
46
     *
47
     * @return string The hash generated
48
     */
49 1
    public function generateHash()
50
    {
51 1
        $userContext = new UserContext();
52
53 1
        foreach ($this->providers as $provider) {
54 1
            $provider->updateUserContext($userContext);
55 1
        }
56
57 1
        $parameters = $userContext->getParameters();
58
59
        // Sort by key (alphanumeric), as order should not make hash vary
60 1
        ksort($parameters);
61
62 1
        return hash('sha256', serialize($parameters));
63
    }
64
65
    /**
66
     * Register a provider to be called for updating a UserContext before generating the Hash.
67
     *
68
     * @param ContextProvider $provider A context provider to be called to get context information about the current request
69
     */
70 1
    private function registerProvider(ContextProvider $provider)
71
    {
72 1
        $this->providers[] = $provider;
73 1
    }
74
}
75