ProcessableHandlerTrait.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\Handler;
  11. use Monolog\ResettableInterface;
  12. use Monolog\Processor\ProcessorInterface;
  13. use Monolog\LogRecord;
  14. /**
  15. * Helper trait for implementing ProcessableInterface
  16. *
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. */
  19. trait ProcessableHandlerTrait
  20. {
  21. /**
  22. * @var callable[]
  23. * @phpstan-var array<(callable(LogRecord): LogRecord)|ProcessorInterface>
  24. */
  25. protected array $processors = [];
  26. /**
  27. * @inheritDoc
  28. */
  29. public function pushProcessor(callable $callback): HandlerInterface
  30. {
  31. array_unshift($this->processors, $callback);
  32. return $this;
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. public function popProcessor(): callable
  38. {
  39. if (\count($this->processors) === 0) {
  40. throw new \LogicException('You tried to pop from an empty processor stack.');
  41. }
  42. return array_shift($this->processors);
  43. }
  44. protected function processRecord(LogRecord $record): LogRecord
  45. {
  46. foreach ($this->processors as $processor) {
  47. $record = $processor($record);
  48. }
  49. return $record;
  50. }
  51. protected function resetProcessors(): void
  52. {
  53. foreach ($this->processors as $processor) {
  54. if ($processor instanceof ResettableInterface) {
  55. $processor->reset();
  56. }
  57. }
  58. }
  59. }