QueryLogger.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.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. * Writes a LoggedQuery into a log
  26. *
  27. * @param LoggedQuery $query to be written in log
  28. * @return void
  29. */
  30. public function log(LoggedQuery $query) {
  31. if (!empty($query->params)) {
  32. $query->query = $this->_interpolate($query);
  33. }
  34. $this->_log($query);
  35. }
  36. /**
  37. * Wrapper function for the logger object, useful for unit testing
  38. * or for overriding in subclasses.
  39. *
  40. * @param LoggedQuery $query to be written in log
  41. * @return void
  42. */
  43. protected function _log($query) {
  44. Log::write('debug', $query, ['queriesLog']);
  45. }
  46. /**
  47. * Helper function used to replace query placeholders by the real
  48. * params used to execute the query
  49. *
  50. * @param LoggedQuery $query The query to log
  51. * @return string
  52. */
  53. protected function _interpolate($query) {
  54. $params = array_map(function($p) {
  55. if ($p === null) {
  56. return 'NULL';
  57. }
  58. return is_string($p) ? "'$p'" : $p;
  59. }, $query->params);
  60. $keys = [];
  61. foreach ($params as $key => $param) {
  62. $keys[] = is_string($key) ? "/:$key/" : '/[?]/';
  63. }
  64. return preg_replace($keys, $params, $query->query, 1);
  65. }
  66. }