QueryLogger.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Log;
  16. use Cake\Log\Log;
  17. /**
  18. * This class is a bridge used to write LoggedQuery objects into a real log.
  19. * by default this class use the built-in CakePHP Log class to accomplish this
  20. *
  21. * @internal
  22. */
  23. class QueryLogger
  24. {
  25. /**
  26. * Writes a LoggedQuery into a log
  27. *
  28. * @param \Cake\Database\Log\LoggedQuery $query to be written in log
  29. * @return void
  30. */
  31. public function log(LoggedQuery $query)
  32. {
  33. if (!empty($query->params)) {
  34. $query->query = $this->_interpolate($query);
  35. }
  36. $this->_log($query);
  37. }
  38. /**
  39. * Wrapper function for the logger object, useful for unit testing
  40. * or for overriding in subclasses.
  41. *
  42. * @param \Cake\Database\Log\LoggedQuery $query to be written in log
  43. * @return void
  44. */
  45. protected function _log($query)
  46. {
  47. Log::write('debug', $query, ['queriesLog']);
  48. }
  49. /**
  50. * Helper function used to replace query placeholders by the real
  51. * params used to execute the query
  52. *
  53. * @param \Cake\Database\Log\LoggedQuery $query The query to log
  54. * @return string
  55. */
  56. protected function _interpolate($query)
  57. {
  58. $params = array_map(function ($p) {
  59. if ($p === null) {
  60. return 'NULL';
  61. }
  62. if (is_bool($p)) {
  63. return $p ? '1' : '0';
  64. }
  65. if (is_string($p)) {
  66. $replacements = [
  67. '$' => '\\$',
  68. '\\' => '\\\\\\\\',
  69. "'" => "''",
  70. ];
  71. $p = strtr($p, $replacements);
  72. return "'$p'";
  73. }
  74. return $p;
  75. }, $query->params);
  76. $keys = [];
  77. $limit = is_int(key($params)) ? 1 : -1;
  78. foreach ($params as $key => $param) {
  79. $keys[] = is_string($key) ? "/:$key\b/" : '/[?]/';
  80. }
  81. return preg_replace($keys, $params, $query->query, $limit);
  82. }
  83. }