MercurialProcessor.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Level;
  12. use Monolog\LevelName;
  13. use Monolog\Logger;
  14. use Psr\Log\LogLevel;
  15. use Monolog\LogRecord;
  16. /**
  17. * Injects Hg branch and Hg revision number in all records
  18. *
  19. * @author Jonathan A. Schweder <jonathanschweder@gmail.com>
  20. */
  21. class MercurialProcessor implements ProcessorInterface
  22. {
  23. private Level $level;
  24. /** @var array{branch: string, revision: string}|array<never>|null */
  25. private static $cache = null;
  26. /**
  27. * @param int|string|Level|LevelName $level The minimum logging level at which this Processor will be triggered
  28. *
  29. * @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $level
  30. */
  31. public function __construct(int|string|Level|LevelName $level = Level::Debug)
  32. {
  33. $this->level = Logger::toMonologLevel($level);
  34. }
  35. /**
  36. * @inheritDoc
  37. */
  38. public function __invoke(LogRecord $record): LogRecord
  39. {
  40. // return if the level is not high enough
  41. if ($record->level->isLowerThan($this->level)) {
  42. return $record;
  43. }
  44. $record->extra['hg'] = self::getMercurialInfo();
  45. return $record;
  46. }
  47. /**
  48. * @return array{branch: string, revision: string}|array<never>
  49. */
  50. private static function getMercurialInfo(): array
  51. {
  52. if (self::$cache !== null) {
  53. return self::$cache;
  54. }
  55. $result = explode(' ', trim((string) shell_exec('hg id -nb')));
  56. if (count($result) >= 3) {
  57. return self::$cache = [
  58. 'branch' => $result[1],
  59. 'revision' => $result[2],
  60. ];
  61. }
  62. return self::$cache = [];
  63. }
  64. }