QueryLogger.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * PHP Version 5.4
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 3.0.0
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. namespace Cake\Database\Log;
  18. use Cake\Database\Type;
  19. use Cake\Log\Log;
  20. use Cake\Utility\String;
  21. /**
  22. * This class is a bridge used to write LoggedQuery objects into a real log.
  23. * by default this class use the built-in CakePHP Log class to accomplish this
  24. *
  25. */
  26. class QueryLogger {
  27. /**
  28. * Writes a LoggedQuery into a log
  29. *
  30. * @param LoggedQuery $query to be written in log
  31. * @return void
  32. */
  33. public function log(LoggedQuery $query) {
  34. if (!empty($query->params)) {
  35. $query->query = $this->_interpolate($query);
  36. }
  37. $this->_log($query);
  38. }
  39. /**
  40. * Wrapper function for the logger object, useful for unit testing
  41. * or for overriding in subclasses.
  42. *
  43. * @param LoggedQuery $query to be written in log
  44. * @return void
  45. */
  46. protected function _log($query) {
  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. * @return string
  54. */
  55. protected function _interpolate($query) {
  56. $params = array_map(function($p) {
  57. if (is_null($p)) {
  58. return 'NULL';
  59. }
  60. return is_string($p) ? "'$p'" : $p;
  61. }, $query->params);
  62. return String::insert($query->query, $params);
  63. }
  64. }