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