CaseExpressionTest.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 Open Group Test Suite License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since 3.0.0
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Test\TestCase\Database\Expression;
  15. use Cake\Database\Expression\CaseExpression;
  16. use Cake\Database\Expression\QueryExpression;
  17. use Cake\Database\ValueBinder;
  18. use Cake\TestSuite\TestCase;
  19. /**
  20. * Tests CaseExpression class
  21. */
  22. class CaseExpressionTest extends TestCase
  23. {
  24. /**
  25. * Test that the sql output works correctly
  26. *
  27. * @return void
  28. */
  29. public function testSqlOutput()
  30. {
  31. $expr = new QueryExpression();
  32. $expr->eq('test', 'true');
  33. $expr2 = new QueryExpression();
  34. $expr2->eq('test2', 'false');
  35. $caseExpression = new CaseExpression($expr, 'foobar');
  36. $expected = 'CASE WHEN test = :c0 THEN :c1 END';
  37. $this->assertSame($expected, $caseExpression->sql(new ValueBinder()));
  38. $caseExpression->add($expr2);
  39. $expected = 'CASE WHEN test = :c0 THEN :c1 WHEN test2 = :c2 THEN :c3 END';
  40. $this->assertSame($expected, $caseExpression->sql(new ValueBinder()));
  41. $caseExpression = new CaseExpression([$expr], ['foobar', 'else']);
  42. $expected = 'CASE WHEN test = :c0 THEN :c1 ELSE :c2 END';
  43. $this->assertSame($expected, $caseExpression->sql(new ValueBinder()));
  44. $caseExpression = new CaseExpression([$expr], ['foobar' => 'literal', 'else']);
  45. $expected = 'CASE WHEN test = :c0 THEN foobar ELSE :c1 END';
  46. $this->assertSame($expected, $caseExpression->sql(new ValueBinder()));
  47. }
  48. /**
  49. * Tests that the expression is correctly traversed
  50. *
  51. * @return void
  52. */
  53. public function testTraverse()
  54. {
  55. $count = 0;
  56. $visitor = function () use (&$count) {
  57. $count++;
  58. };
  59. $expr = new QueryExpression();
  60. $expr->eq('test', 'true');
  61. $expr2 = new QueryExpression();
  62. $expr2->eq('test', 'false');
  63. $caseExpression = new CaseExpression([$expr, $expr2]);
  64. $caseExpression->traverse($visitor);
  65. $this->assertSame(4, $count);
  66. }
  67. }