Lines: 100.00%
| Line | Hits | Source |
|---|---|---|
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Drupal\visitors\Helper; | |
| 6 | ||
| 7 | /** | |
| 8 | * Builds a stable pseudonym for a user id. | |
| 9 | * | |
| 10 | * Call this when the site stores a pseudonym instead of the Drupal user | |
| 11 | * id. The same id and salt always produce the same 32 character value. | |
| 12 | * Anonymous ids are left unchanged so the caller can store NULL. | |
| 13 | */ | |
| 14 | final class UserIdAnonymizer { | |
| 15 | ||
| 16 | /** | |
| 17 | * Returns a 32 character pseudonym. | |
| 18 | * | |
| 19 | * An empty id or zero is returned unchanged and is not hashed. | |
| 20 | * | |
| 21 | * @param string $uid | |
| 22 | * The user id from the tracking request. | |
| 23 | * @param string $salt | |
| 24 | * The site salt. The same salt keeps a person on one pseudonym. | |
| 25 | * | |
| 26 | * @return string | |
| 27 | * The first 32 hex characters of the SHA-256 digest, or the original | |
| 28 | * value when there is no user. | |
| 29 | */ | |
| 30 | public static function apply(string $uid, string $salt): string { | |
| 31 | 3 | if ($uid === '' || $uid === '0') { |
| 32 | 1 | return $uid; |
| 33 | } | |
| 34 | ||
| 35 | 2 | return substr(hash('sha256', $uid . $salt), 0, 32); |
| 36 | } | |
| 37 | ||
| 38 | } |