DbQueryExecutedListener.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace App\Listener;
  12. use Hyperf\Collection\Arr;
  13. use Hyperf\Database\Events\QueryExecuted;
  14. use Hyperf\Event\Annotation\Listener;
  15. use Hyperf\Event\Contract\ListenerInterface;
  16. use Hyperf\Logger\LoggerFactory;
  17. use Psr\Container\ContainerInterface;
  18. use Psr\Log\LoggerInterface;
  19. #[Listener]
  20. class DbQueryExecutedListener implements ListenerInterface
  21. {
  22. /**
  23. * @var LoggerInterface
  24. */
  25. private $logger;
  26. public function __construct(ContainerInterface $container)
  27. {
  28. $this->logger = $container->get(LoggerFactory::class)->get('sql');
  29. }
  30. public function listen(): array
  31. {
  32. return [
  33. QueryExecuted::class,
  34. ];
  35. }
  36. /**
  37. * @param QueryExecuted $event
  38. */
  39. public function process(object $event): void
  40. {
  41. if ($event instanceof QueryExecuted) {
  42. $sql = $event->sql;
  43. if (! Arr::isAssoc($event->bindings)) {
  44. $position = 0;
  45. foreach ($event->bindings as $value) {
  46. $position = strpos($sql, '?', $position);
  47. if ($position === false) {
  48. break;
  49. }
  50. $value = "'{$value}'";
  51. $sql = substr_replace($sql, $value, $position, 1);
  52. $position += strlen($value);
  53. }
  54. }
  55. $this->logger->info(sprintf('[%s] %s', $event->time, $sql));
  56. }
  57. }
  58. }