UidProcessor.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Processor;
  11. use Monolog\ResettableInterface;
  12. /**
  13. * Adds a unique identifier into records
  14. *
  15. * @author Simon Mönch <sm@webfactory.de>
  16. */
  17. class UidProcessor implements ProcessorInterface, ResettableInterface
  18. {
  19. private $uid;
  20. public function __construct(int $length = 7)
  21. {
  22. if ($length > 32 || $length < 1) {
  23. throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
  24. }
  25. $this->uid = $this->generateUid($length);
  26. }
  27. public function __invoke(array $record): array
  28. {
  29. $record['extra']['uid'] = $this->uid;
  30. return $record;
  31. }
  32. public function getUid(): string
  33. {
  34. return $this->uid;
  35. }
  36. public function reset()
  37. {
  38. $this->uid = $this->generateUid(strlen($this->uid));
  39. }
  40. private function generateUid(int $length): string
  41. {
  42. return substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length);
  43. }
  44. }