DbQueryExecutedListener.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\Database\Events\QueryExecuted;
  13. use Hyperf\Event\Annotation\Listener;
  14. use Hyperf\Event\Contract\ListenerInterface;
  15. use Hyperf\Logger\LoggerFactory;
  16. use Hyperf\Utils\Arr;
  17. use Hyperf\Utils\Str;
  18. use Psr\Container\ContainerInterface;
  19. use Psr\Log\LoggerInterface;
  20. /**
  21. * @Listener
  22. */
  23. class DbQueryExecutedListener implements ListenerInterface
  24. {
  25. /**
  26. * @var LoggerInterface
  27. */
  28. private $logger;
  29. public function __construct(ContainerInterface $container)
  30. {
  31. $this->logger = $container->get(LoggerFactory::class)->get('sql','sql');
  32. }
  33. public function listen(): array
  34. {
  35. return [
  36. QueryExecuted::class,
  37. ];
  38. }
  39. /**
  40. * @param QueryExecuted $event
  41. */
  42. public function process(object $event)
  43. {
  44. if ($event instanceof QueryExecuted) {
  45. $sql = $event->sql;
  46. if (! Arr::isAssoc($event->bindings)) {
  47. foreach ($event->bindings as $key => $value) {
  48. $sql = Str::replaceFirst('?', "'{$value}'", $sql);
  49. }
  50. }
  51. // $this->logger->info(sprintf('[%s] %s', $event->time, $sql));
  52. }
  53. }
  54. }