DbalLogger.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Bridge\Doctrine\Logger;
  11. use Doctrine\DBAL\Logging\SQLLogger;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\Stopwatch\Stopwatch;
  14. /**
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class DbalLogger implements SQLLogger
  18. {
  19. public const MAX_STRING_LENGTH = 32;
  20. public const BINARY_DATA_VALUE = '(binary value)';
  21. protected $logger;
  22. protected $stopwatch;
  23. public function __construct(LoggerInterface $logger = null, Stopwatch $stopwatch = null)
  24. {
  25. $this->logger = $logger;
  26. $this->stopwatch = $stopwatch;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. *
  31. * @return void
  32. */
  33. public function startQuery($sql, array $params = null, array $types = null)
  34. {
  35. if (null !== $this->stopwatch) {
  36. $this->stopwatch->start('doctrine', 'doctrine');
  37. }
  38. if (null !== $this->logger) {
  39. $this->log($sql, null === $params ? [] : $this->normalizeParams($params));
  40. }
  41. }
  42. /**
  43. * {@inheritdoc}
  44. *
  45. * @return void
  46. */
  47. public function stopQuery()
  48. {
  49. if (null !== $this->stopwatch) {
  50. $this->stopwatch->stop('doctrine');
  51. }
  52. }
  53. /**
  54. * Logs a message.
  55. */
  56. protected function log(string $message, array $params)
  57. {
  58. $this->logger->debug($message, $params);
  59. }
  60. private function normalizeParams(array $params): array
  61. {
  62. foreach ($params as $index => $param) {
  63. // normalize recursively
  64. if (\is_array($param)) {
  65. $params[$index] = $this->normalizeParams($param);
  66. continue;
  67. }
  68. if (!\is_string($params[$index])) {
  69. continue;
  70. }
  71. // non utf-8 strings break json encoding
  72. if (!preg_match('//u', $params[$index])) {
  73. $params[$index] = self::BINARY_DATA_VALUE;
  74. continue;
  75. }
  76. // detect if the too long string must be shorten
  77. if (self::MAX_STRING_LENGTH < mb_strlen($params[$index], 'UTF-8')) {
  78. $params[$index] = mb_substr($params[$index], 0, self::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]';
  79. continue;
  80. }
  81. }
  82. return $params;
  83. }
  84. }