1 | <?php |
||
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 | } |
||
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 | } |
||
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) |
|
74 | } |
||
75 |