QueryAssertsTrait.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 5.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database;
  17. use Cake\Database\Query\SelectQuery;
  18. trait QueryAssertsTrait
  19. {
  20. /**
  21. * Assertion for comparing a regex pattern against a query having its identifiers
  22. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  23. * parameter is set to true, it will alter the pattern to both accept quoted and
  24. * unquoted queries
  25. *
  26. * @param string $pattern
  27. * @param string $query the result to compare against
  28. * @param bool $optional
  29. */
  30. public function assertQuotedQuery($pattern, $query, $optional = false): void
  31. {
  32. if ($optional) {
  33. $optional = '?';
  34. }
  35. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  36. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  37. $this->assertMatchesRegularExpression('#' . $pattern . '#', $query);
  38. }
  39. /**
  40. * Assertion for comparing a table's contents with what is in it.
  41. *
  42. * @param string $table
  43. * @param int $count
  44. * @param array $rows
  45. * @param array $conditions
  46. */
  47. public function assertTable($table, $count, $rows, $conditions = []): void
  48. {
  49. $result = (new SelectQuery($this->connection))->select('*')
  50. ->from($table)
  51. ->where($conditions)
  52. ->execute();
  53. $results = $result->fetchAll('assoc');
  54. $this->assertCount($count, $results, 'Row count is incorrect');
  55. $this->assertEquals($rows, $results);
  56. $result->closeCursor();
  57. }
  58. }