CaseStatementExpressionTest.php 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  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 4.3.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database\Expression;
  17. use Cake\Chronos\Chronos;
  18. use Cake\Chronos\Date as ChronosDate;
  19. use Cake\Database\Expression\CaseStatementExpression;
  20. use Cake\Database\Expression\ComparisonExpression;
  21. use Cake\Database\Expression\IdentifierExpression;
  22. use Cake\Database\Expression\QueryExpression;
  23. use Cake\Database\Expression\WhenThenExpression;
  24. use Cake\Database\TypeFactory;
  25. use Cake\Database\TypeMap;
  26. use Cake\Database\ValueBinder;
  27. use Cake\Datasource\ConnectionManager;
  28. use Cake\I18n\Date;
  29. use Cake\I18n\DateTime;
  30. use Cake\Test\test_app\TestApp\Database\Expression\CustomWhenThenExpression;
  31. use Cake\Test\test_app\TestApp\Stub\CaseStatementExpressionStub;
  32. use Cake\Test\test_app\TestApp\Stub\WhenThenExpressionStub;
  33. use Cake\TestSuite\TestCase;
  34. use InvalidArgumentException;
  35. use LogicException;
  36. use stdClass;
  37. use TestApp\Database\Type\CustomExpressionType;
  38. use TestApp\View\Object\TestObjectWithToString;
  39. use TypeError;
  40. class CaseStatementExpressionTest extends TestCase
  41. {
  42. // region Type handling
  43. public function testExpressionTypeCastingSimpleCase(): void
  44. {
  45. TypeFactory::map('custom', CustomExpressionType::class);
  46. $expression = (new CaseStatementExpression(1, 'custom'))
  47. ->when(1, 'custom')
  48. ->then(2, 'custom')
  49. ->else(3, 'custom');
  50. $valueBinder = new ValueBinder();
  51. $sql = $expression->sql($valueBinder);
  52. $this->assertSame(
  53. 'CASE CUSTOM(:param0) WHEN CUSTOM(:param1) THEN CUSTOM(:param2) ELSE CUSTOM(:param3) END',
  54. $sql
  55. );
  56. }
  57. public function testExpressionTypeCastingNullValues(): void
  58. {
  59. TypeFactory::map('custom', CustomExpressionType::class);
  60. $expression = (new CaseStatementExpression(null, 'custom'))
  61. ->when(1, 'custom')
  62. ->then(null, 'custom')
  63. ->else(null, 'custom');
  64. $valueBinder = new ValueBinder();
  65. $sql = $expression->sql($valueBinder);
  66. $this->assertSame(
  67. 'CASE CUSTOM(:param0) WHEN CUSTOM(:param1) THEN CUSTOM(:param2) ELSE CUSTOM(:param3) END',
  68. $sql
  69. );
  70. }
  71. public function testExpressionTypeCastingSearchedCase(): void
  72. {
  73. TypeFactory::map('custom', CustomExpressionType::class);
  74. $expression = (new CaseStatementExpression())
  75. ->when(['Table.column' => true], ['Table.column' => 'custom'])
  76. ->then(1, 'custom')
  77. ->else(2, 'custom');
  78. $valueBinder = new ValueBinder();
  79. $sql = $expression->sql($valueBinder);
  80. $this->assertSame(
  81. 'CASE WHEN Table.column = (CUSTOM(:param0)) THEN CUSTOM(:param1) ELSE CUSTOM(:param2) END',
  82. $sql
  83. );
  84. }
  85. public function testGetReturnType(): void
  86. {
  87. // all provided `then` and `else` types are the same, return
  88. // type can be inferred
  89. $expression = (new CaseStatementExpression())
  90. ->when(['Table.column_a' => true])
  91. ->then(1, 'integer')
  92. ->when(['Table.column_b' => true])
  93. ->then(2, 'integer')
  94. ->else(3, 'integer');
  95. $this->assertSame('integer', $expression->getReturnType());
  96. // all provided `then` an `else` types are the same, one `then`
  97. // type is `null`, return type can be inferred
  98. $expression = (new CaseStatementExpression())
  99. ->when(['Table.column_a' => true])
  100. ->then(1)
  101. ->when(['Table.column_b' => true])
  102. ->then(2, 'integer')
  103. ->else(3, 'integer');
  104. $this->assertSame('integer', $expression->getReturnType());
  105. // all `then` types are null, an `else` type was provided,
  106. // return type can be inferred
  107. $expression = (new CaseStatementExpression())
  108. ->when(['Table.column_a' => true])
  109. ->then(1)
  110. ->when(['Table.column_b' => true])
  111. ->then(2)
  112. ->else(3, 'integer');
  113. $this->assertSame('integer', $expression->getReturnType());
  114. // all provided `then` types are the same, the `else` type is
  115. // `null`, return type can be inferred
  116. $expression = (new CaseStatementExpression())
  117. ->when(['Table.column_a' => true])
  118. ->then(1, 'integer')
  119. ->when(['Table.column_b' => true])
  120. ->then(2, 'integer')
  121. ->else(3);
  122. $this->assertSame('integer', $expression->getReturnType());
  123. // no `then` or `else` types were provided, they are all `null`,
  124. // and will be derived from the passed value, return type can be
  125. // inferred
  126. $expression = (new CaseStatementExpression())
  127. ->when(['Table.column_a' => true])
  128. ->then(1)
  129. ->when(['Table.column_b' => true])
  130. ->then(2)
  131. ->else(3);
  132. $this->assertSame('integer', $expression->getReturnType());
  133. // all `then` and `else` point to columns of the same type,
  134. // return type can be inferred
  135. $typeMap = new TypeMap([
  136. 'Table.column_a' => 'boolean',
  137. 'Table.column_b' => 'boolean',
  138. 'Table.column_c' => 'boolean',
  139. ]);
  140. $expression = (new CaseStatementExpression())
  141. ->setTypeMap($typeMap)
  142. ->when(['Table.column_a' => true])
  143. ->then(new IdentifierExpression('Table.column_a'))
  144. ->when(['Table.column_b' => true])
  145. ->then(new IdentifierExpression('Table.column_b'))
  146. ->else(new IdentifierExpression('Table.column_c'));
  147. $this->assertSame('boolean', $expression->getReturnType());
  148. // all `then` and `else` use the same custom type, return type
  149. // can be inferred
  150. $expression = (new CaseStatementExpression())
  151. ->when(['Table.column_a' => true])
  152. ->then(1, 'custom')
  153. ->when(['Table.column_b' => true])
  154. ->then(2, 'custom')
  155. ->else(3, 'custom');
  156. $this->assertSame('custom', $expression->getReturnType());
  157. // all `then` and `else` types were provided, but an explicit
  158. // return type was set, return type will be overwritten
  159. $expression = (new CaseStatementExpression())
  160. ->when(['Table.column_a' => true])
  161. ->then(1, 'integer')
  162. ->when(['Table.column_b' => true])
  163. ->then(2, 'integer')
  164. ->else(3, 'integer')
  165. ->setReturnType('string');
  166. $this->assertSame('string', $expression->getReturnType());
  167. // all `then` and `else` types are different, return type
  168. // cannot be inferred
  169. $expression = (new CaseStatementExpression())
  170. ->when(['Table.column_a' => true])
  171. ->then(true)
  172. ->when(['Table.column_b' => true])
  173. ->then(1)
  174. ->else(null);
  175. $this->assertSame('string', $expression->getReturnType());
  176. }
  177. public function testSetReturnType(): void
  178. {
  179. $expression = (new CaseStatementExpression())->else('1');
  180. $this->assertSame('string', $expression->getReturnType());
  181. $expression->setReturnType('float');
  182. $this->assertSame('float', $expression->getReturnType());
  183. }
  184. public function valueTypeInferenceDataProvider(): array
  185. {
  186. return [
  187. ['1', 'string'],
  188. [1, 'integer'],
  189. [1.0, 'float'],
  190. [true, 'boolean'],
  191. [ChronosDate::now(), 'date'],
  192. [Chronos::now(), 'datetime'],
  193. [new IdentifierExpression('Table.column'), null],
  194. [new stdClass(), null],
  195. [null, null],
  196. ];
  197. }
  198. /**
  199. * @dataProvider valueTypeInferenceDataProvider
  200. * @param mixed $value The value from which to infer the type.
  201. * @param string|null $type The expected type.
  202. */
  203. public function testInferValueType($value, ?string $type): void
  204. {
  205. $expression = new CaseStatementExpressionStub();
  206. $this->assertNull($expression->getValueType());
  207. $expression = (new CaseStatementExpressionStub($value))
  208. ->setTypeMap(new TypeMap(['Table.column' => 'boolean']))
  209. ->when(1)
  210. ->then(2);
  211. $this->assertSame($type, $expression->getValueType());
  212. }
  213. public function whenTypeInferenceDataProvider(): array
  214. {
  215. return [
  216. ['1', 'string'],
  217. [1, 'integer'],
  218. [1.0, 'float'],
  219. [true, 'boolean'],
  220. [ChronosDate::now(), 'date'],
  221. [Chronos::now(), 'datetime'],
  222. [new IdentifierExpression('Table.column'), null],
  223. [['Table.column' => true], null],
  224. [new stdClass(), null],
  225. ];
  226. }
  227. /**
  228. * @dataProvider whenTypeInferenceDataProvider
  229. * @param mixed $value The value from which to infer the type.
  230. * @param string|null $type The expected type.
  231. */
  232. public function testInferWhenType($value, ?string $type): void
  233. {
  234. $expression = (new CaseStatementExpressionStub())
  235. ->setTypeMap(new TypeMap(['Table.column' => 'boolean']));
  236. $expression->when(new WhenThenExpressionStub($expression->getTypeMap()));
  237. $this->assertNull($expression->clause('when')[0]->getWhenType());
  238. $expression->clause('when')[0]
  239. ->when($value)
  240. ->then(1);
  241. $this->assertSame($type, $expression->clause('when')[0]->getWhenType());
  242. }
  243. public function resultTypeInferenceDataProvider(): array
  244. {
  245. return [
  246. ['1', 'string'],
  247. [1, 'integer'],
  248. [1.0, 'float'],
  249. [true, 'boolean'],
  250. [ChronosDate::now(), 'date'],
  251. [Chronos::now(), 'datetime'],
  252. [new IdentifierExpression('Table.column'), 'boolean'],
  253. [new stdClass(), null],
  254. [null, null],
  255. ];
  256. }
  257. /**
  258. * @dataProvider resultTypeInferenceDataProvider
  259. * @param mixed $value The value from which to infer the type.
  260. * @param string|null $type The expected type.
  261. */
  262. public function testInferResultType($value, ?string $type): void
  263. {
  264. $expression = (new CaseStatementExpressionStub())
  265. ->setTypeMap(new TypeMap(['Table.column' => 'boolean']))
  266. ->when(function (WhenThenExpression $whenThen) {
  267. return $whenThen;
  268. });
  269. $this->assertNull($expression->clause('when')[0]->getResultType());
  270. $expression->clause('when')[0]
  271. ->when(['Table.column' => true])
  272. ->then($value);
  273. $this->assertSame($type, $expression->clause('when')[0]->getResultType());
  274. }
  275. /**
  276. * @dataProvider resultTypeInferenceDataProvider
  277. * @param mixed $value The value from which to infer the type.
  278. * @param string|null $type The expected type.
  279. */
  280. public function testInferElseType($value, ?string $type): void
  281. {
  282. $expression = new CaseStatementExpressionStub();
  283. $this->assertNull($expression->getElseType());
  284. $expression = (new CaseStatementExpressionStub())
  285. ->setTypeMap(new TypeMap(['Table.column' => 'boolean']));
  286. $this->assertNull($expression->getElseType());
  287. $expression->else($value);
  288. $this->assertSame($type, $expression->getElseType());
  289. }
  290. public function testWhenArrayValueInheritTypeMap(): void
  291. {
  292. $typeMap = new TypeMap([
  293. 'Table.column_a' => 'boolean',
  294. 'Table.column_b' => 'string',
  295. ]);
  296. $expression = (new CaseStatementExpression())
  297. ->setTypeMap($typeMap)
  298. ->when(['Table.column_a' => true])
  299. ->then(1)
  300. ->when(['Table.column_b' => 'foo'])
  301. ->then(2)
  302. ->else(3);
  303. $valueBinder = new ValueBinder();
  304. $sql = $expression->sql($valueBinder);
  305. $this->assertSame(
  306. 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
  307. $sql
  308. );
  309. $this->assertSame(
  310. [
  311. ':c0' => [
  312. 'value' => true,
  313. 'type' => 'boolean',
  314. 'placeholder' => 'c0',
  315. ],
  316. ':c1' => [
  317. 'value' => 1,
  318. 'type' => 'integer',
  319. 'placeholder' => 'c1',
  320. ],
  321. ':c2' => [
  322. 'value' => 'foo',
  323. 'type' => 'string',
  324. 'placeholder' => 'c2',
  325. ],
  326. ':c3' => [
  327. 'value' => 2,
  328. 'type' => 'integer',
  329. 'placeholder' => 'c3',
  330. ],
  331. ':c4' => [
  332. 'value' => 3,
  333. 'type' => 'integer',
  334. 'placeholder' => 'c4',
  335. ],
  336. ],
  337. $valueBinder->bindings()
  338. );
  339. }
  340. public function testWhenArrayValueWithExplicitTypes(): void
  341. {
  342. $typeMap = new TypeMap([
  343. 'Table.column_a' => 'boolean',
  344. 'Table.column_b' => 'string',
  345. ]);
  346. $expression = (new CaseStatementExpression())
  347. ->setTypeMap($typeMap)
  348. ->when(['Table.column_a' => 123], ['Table.column_a' => 'integer'])
  349. ->then(1)
  350. ->when(['Table.column_b' => 'foo'])
  351. ->then(2)
  352. ->else(3);
  353. $valueBinder = new ValueBinder();
  354. $sql = $expression->sql($valueBinder);
  355. $this->assertSame(
  356. 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
  357. $sql
  358. );
  359. $this->assertSame(
  360. [
  361. ':c0' => [
  362. 'value' => 123,
  363. 'type' => 'integer',
  364. 'placeholder' => 'c0',
  365. ],
  366. ':c1' => [
  367. 'value' => 1,
  368. 'type' => 'integer',
  369. 'placeholder' => 'c1',
  370. ],
  371. ':c2' => [
  372. 'value' => 'foo',
  373. 'type' => 'string',
  374. 'placeholder' => 'c2',
  375. ],
  376. ':c3' => [
  377. 'value' => 2,
  378. 'type' => 'integer',
  379. 'placeholder' => 'c3',
  380. ],
  381. ':c4' => [
  382. 'value' => 3,
  383. 'type' => 'integer',
  384. 'placeholder' => 'c4',
  385. ],
  386. ],
  387. $valueBinder->bindings()
  388. );
  389. }
  390. public function testWhenCallableArrayValueInheritTypeMap(): void
  391. {
  392. $typeMap = new TypeMap([
  393. 'Table.column_a' => 'boolean',
  394. 'Table.column_b' => 'string',
  395. ]);
  396. $expression = (new CaseStatementExpression())
  397. ->setTypeMap($typeMap)
  398. ->when(function (WhenThenExpression $whenThen) {
  399. return $whenThen
  400. ->when(['Table.column_a' => true])
  401. ->then(1);
  402. })
  403. ->when(function (WhenThenExpression $whenThen) {
  404. return $whenThen
  405. ->when(['Table.column_b' => 'foo'])
  406. ->then(2);
  407. })
  408. ->else(3);
  409. $valueBinder = new ValueBinder();
  410. $sql = $expression->sql($valueBinder);
  411. $this->assertSame(
  412. 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
  413. $sql
  414. );
  415. $this->assertSame(
  416. [
  417. ':c0' => [
  418. 'value' => true,
  419. 'type' => 'boolean',
  420. 'placeholder' => 'c0',
  421. ],
  422. ':c1' => [
  423. 'value' => 1,
  424. 'type' => 'integer',
  425. 'placeholder' => 'c1',
  426. ],
  427. ':c2' => [
  428. 'value' => 'foo',
  429. 'type' => 'string',
  430. 'placeholder' => 'c2',
  431. ],
  432. ':c3' => [
  433. 'value' => 2,
  434. 'type' => 'integer',
  435. 'placeholder' => 'c3',
  436. ],
  437. ':c4' => [
  438. 'value' => 3,
  439. 'type' => 'integer',
  440. 'placeholder' => 'c4',
  441. ],
  442. ],
  443. $valueBinder->bindings()
  444. );
  445. }
  446. public function testWhenCallableArrayValueWithExplicitTypes(): void
  447. {
  448. $typeMap = new TypeMap([
  449. 'Table.column_a' => 'boolean',
  450. 'Table.column_b' => 'string',
  451. ]);
  452. $expression = (new CaseStatementExpression())
  453. ->setTypeMap($typeMap)
  454. ->when(function (WhenThenExpression $whenThen) {
  455. return $whenThen
  456. ->when(['Table.column_a' => 123], ['Table.column_a' => 'integer'])
  457. ->then(1);
  458. })
  459. ->when(function (WhenThenExpression $whenThen) {
  460. return $whenThen
  461. ->when(['Table.column_b' => 'foo'])
  462. ->then(2);
  463. })
  464. ->else(3);
  465. $valueBinder = new ValueBinder();
  466. $sql = $expression->sql($valueBinder);
  467. $this->assertSame(
  468. 'CASE WHEN Table.column_a = :c0 THEN :c1 WHEN Table.column_b = :c2 THEN :c3 ELSE :c4 END',
  469. $sql
  470. );
  471. $this->assertSame(
  472. [
  473. ':c0' => [
  474. 'value' => 123,
  475. 'type' => 'integer',
  476. 'placeholder' => 'c0',
  477. ],
  478. ':c1' => [
  479. 'value' => 1,
  480. 'type' => 'integer',
  481. 'placeholder' => 'c1',
  482. ],
  483. ':c2' => [
  484. 'value' => 'foo',
  485. 'type' => 'string',
  486. 'placeholder' => 'c2',
  487. ],
  488. ':c3' => [
  489. 'value' => 2,
  490. 'type' => 'integer',
  491. 'placeholder' => 'c3',
  492. ],
  493. ':c4' => [
  494. 'value' => 3,
  495. 'type' => 'integer',
  496. 'placeholder' => 'c4',
  497. ],
  498. ],
  499. $valueBinder->bindings()
  500. );
  501. }
  502. public function testWhenArrayValueRequiresArrayTypeValue(): void
  503. {
  504. $this->expectException(InvalidArgumentException::class);
  505. $this->expectExceptionMessage(
  506. 'When using an array for the `$when` argument, the `$type` ' .
  507. 'argument must be an array too, `string` given.'
  508. );
  509. (new CaseStatementExpression())
  510. ->when(['Table.column' => 123], 'integer')
  511. ->then(1);
  512. }
  513. public function testWhenNonArrayValueRequiresStringTypeValue(): void
  514. {
  515. $this->expectException(InvalidArgumentException::class);
  516. $this->expectExceptionMessage(
  517. 'When using a non-array value for the `$when` argument, ' .
  518. 'the `$type` argument must be a string, `array` given.'
  519. );
  520. (new CaseStatementExpression())
  521. ->when(123, ['Table.column' => 'integer'])
  522. ->then(1);
  523. }
  524. public function testInternalTypeMapChangesAreNonPersistent(): void
  525. {
  526. $typeMap = new TypeMap([
  527. 'Table.column' => 'integer',
  528. ]);
  529. $expression = (new CaseStatementExpression())
  530. ->setTypeMap($typeMap)
  531. ->when(['Table.column' => 123])
  532. ->then(1)
  533. ->when(['Table.column' => 'foo'], ['Table.column' => 'string'])
  534. ->then('bar')
  535. ->when(['Table.column' => 456])
  536. ->then(2);
  537. $valueBinder = new ValueBinder();
  538. $expression->sql($valueBinder);
  539. $this->assertSame(
  540. [
  541. ':c0' => [
  542. 'value' => 123,
  543. 'type' => 'integer',
  544. 'placeholder' => 'c0',
  545. ],
  546. ':c1' => [
  547. 'value' => 1,
  548. 'type' => 'integer',
  549. 'placeholder' => 'c1',
  550. ],
  551. ':c2' => [
  552. 'value' => 'foo',
  553. 'type' => 'string',
  554. 'placeholder' => 'c2',
  555. ],
  556. ':c3' => [
  557. 'value' => 'bar',
  558. 'type' => 'string',
  559. 'placeholder' => 'c3',
  560. ],
  561. ':c4' => [
  562. 'value' => 456,
  563. 'type' => 'integer',
  564. 'placeholder' => 'c4',
  565. ],
  566. ':c5' => [
  567. 'value' => 2,
  568. 'type' => 'integer',
  569. 'placeholder' => 'c5',
  570. ],
  571. ],
  572. $valueBinder->bindings()
  573. );
  574. $this->assertSame($typeMap, $expression->getTypeMap());
  575. }
  576. // endregion
  577. // region SQL injections
  578. public function testSqlInjectionViaTypedCaseValueIsNotPossible(): void
  579. {
  580. $expression = (new CaseStatementExpression('1 THEN 1 END; DELETE * FROM foo; --', 'integer'))
  581. ->when(1)
  582. ->then(2);
  583. $valueBinder = new ValueBinder();
  584. $sql = $expression->sql($valueBinder);
  585. $this->assertSame(
  586. 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
  587. $sql
  588. );
  589. $this->assertSame(
  590. [
  591. ':c0' => [
  592. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  593. 'type' => 'integer',
  594. 'placeholder' => 'c0',
  595. ],
  596. ':c1' => [
  597. 'value' => 1,
  598. 'type' => 'integer',
  599. 'placeholder' => 'c1',
  600. ],
  601. ':c2' => [
  602. 'value' => 2,
  603. 'type' => 'integer',
  604. 'placeholder' => 'c2',
  605. ],
  606. ],
  607. $valueBinder->bindings()
  608. );
  609. }
  610. public function testSqlInjectionViaUntypedCaseValueIsNotPossible(): void
  611. {
  612. $expression = (new CaseStatementExpression('1 THEN 1 END; DELETE * FROM foo; --'))
  613. ->when(1)
  614. ->then(2);
  615. $valueBinder = new ValueBinder();
  616. $sql = $expression->sql($valueBinder);
  617. $this->assertSame(
  618. 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
  619. $sql
  620. );
  621. $this->assertSame(
  622. [
  623. ':c0' => [
  624. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  625. 'type' => 'string',
  626. 'placeholder' => 'c0',
  627. ],
  628. ':c1' => [
  629. 'value' => 1,
  630. 'type' => 'integer',
  631. 'placeholder' => 'c1',
  632. ],
  633. ':c2' => [
  634. 'value' => 2,
  635. 'type' => 'integer',
  636. 'placeholder' => 'c2',
  637. ],
  638. ],
  639. $valueBinder->bindings()
  640. );
  641. }
  642. public function testSqlInjectionViaTypedWhenValueIsNotPossible(): void
  643. {
  644. $expression = (new CaseStatementExpression())
  645. ->when('1 THEN 1 END; DELETE * FROM foo; --', 'integer')
  646. ->then(1);
  647. $valueBinder = new ValueBinder();
  648. $sql = $expression->sql($valueBinder);
  649. $this->assertSame(
  650. 'CASE WHEN :c0 THEN :c1 ELSE NULL END',
  651. $sql
  652. );
  653. $this->assertSame(
  654. [
  655. ':c0' => [
  656. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  657. 'type' => 'integer',
  658. 'placeholder' => 'c0',
  659. ],
  660. ':c1' => [
  661. 'value' => 1,
  662. 'type' => 'integer',
  663. 'placeholder' => 'c1',
  664. ],
  665. ],
  666. $valueBinder->bindings()
  667. );
  668. }
  669. public function testSqlInjectionViaTypedWhenArrayValueIsNotPossible(): void
  670. {
  671. $this->expectException(InvalidArgumentException::class);
  672. $this->expectExceptionMessage(
  673. 'When using an array for the `$when` argument, the `$type` ' .
  674. 'argument must be an array too, `string` given.'
  675. );
  676. (new CaseStatementExpression())
  677. ->when(['1 THEN 1 END; DELETE * FROM foo; --' => '123'], 'integer')
  678. ->then(1);
  679. }
  680. public function testSqlInjectionViaUntypedWhenValueIsNotPossible()
  681. {
  682. $expression = (new CaseStatementExpression())
  683. ->when('1 THEN 1 END; DELETE * FROM foo; --')
  684. ->then(1);
  685. $valueBinder = new ValueBinder();
  686. $sql = $expression->sql($valueBinder);
  687. $this->assertSame(
  688. 'CASE WHEN :c0 THEN :c1 ELSE NULL END',
  689. $sql
  690. );
  691. $this->assertSame(
  692. [
  693. ':c0' => [
  694. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  695. 'type' => 'string',
  696. 'placeholder' => 'c0',
  697. ],
  698. ':c1' => [
  699. 'value' => 1,
  700. 'type' => 'integer',
  701. 'placeholder' => 'c1',
  702. ],
  703. ],
  704. $valueBinder->bindings()
  705. );
  706. }
  707. public function testSqlInjectionViaUntypedWhenArrayValueIsPossible(): void
  708. {
  709. $expression = (new CaseStatementExpression())
  710. ->when(['1 THEN 1 END; DELETE * FROM foo; --' => '123'])
  711. ->then(1);
  712. $valueBinder = new ValueBinder();
  713. $sql = $expression->sql($valueBinder);
  714. $this->assertSame(
  715. 'CASE WHEN 1 THEN 1 END; DELETE * FROM foo; -- :c0 THEN :c1 ELSE NULL END',
  716. $sql
  717. );
  718. $this->assertSame(
  719. [
  720. ':c0' => [
  721. 'value' => '123',
  722. 'type' => null,
  723. 'placeholder' => 'c0',
  724. ],
  725. ':c1' => [
  726. 'value' => 1,
  727. 'type' => 'integer',
  728. 'placeholder' => 'c1',
  729. ],
  730. ],
  731. $valueBinder->bindings()
  732. );
  733. }
  734. public function testSqlInjectionViaTypedThenValueIsNotPossible(): void
  735. {
  736. $expression = (new CaseStatementExpression(1))
  737. ->when(2)
  738. ->then('1 THEN 1 END; DELETE * FROM foo; --', 'integer');
  739. $valueBinder = new ValueBinder();
  740. $sql = $expression->sql($valueBinder);
  741. $this->assertSame(
  742. 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
  743. $sql
  744. );
  745. $this->assertSame(
  746. [
  747. ':c0' => [
  748. 'value' => 1,
  749. 'type' => 'integer',
  750. 'placeholder' => 'c0',
  751. ],
  752. ':c1' => [
  753. 'value' => 2,
  754. 'type' => 'integer',
  755. 'placeholder' => 'c1',
  756. ],
  757. ':c2' => [
  758. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  759. 'type' => 'integer',
  760. 'placeholder' => 'c2',
  761. ],
  762. ],
  763. $valueBinder->bindings()
  764. );
  765. }
  766. public function testSqlInjectionViaUntypedThenValueIsNotPossible(): void
  767. {
  768. $expression = (new CaseStatementExpression(1))
  769. ->when(2)
  770. ->then('1 THEN 1 END; DELETE * FROM foo; --');
  771. $valueBinder = new ValueBinder();
  772. $sql = $expression->sql($valueBinder);
  773. $this->assertSame(
  774. 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
  775. $sql
  776. );
  777. $this->assertSame(
  778. [
  779. ':c0' => [
  780. 'value' => 1,
  781. 'type' => 'integer',
  782. 'placeholder' => 'c0',
  783. ],
  784. ':c1' => [
  785. 'value' => 2,
  786. 'type' => 'integer',
  787. 'placeholder' => 'c1',
  788. ],
  789. ':c2' => [
  790. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  791. 'type' => 'string',
  792. 'placeholder' => 'c2',
  793. ],
  794. ],
  795. $valueBinder->bindings()
  796. );
  797. }
  798. public function testSqlInjectionViaTypedElseValueIsNotPossible(): void
  799. {
  800. $expression = (new CaseStatementExpression(1))
  801. ->when(2)
  802. ->then(3)
  803. ->else('1 THEN 1 END; DELETE * FROM foo; --', 'integer');
  804. $valueBinder = new ValueBinder();
  805. $sql = $expression->sql($valueBinder);
  806. $this->assertSame(
  807. 'CASE :c0 WHEN :c1 THEN :c2 ELSE :c3 END',
  808. $sql
  809. );
  810. $this->assertSame(
  811. [
  812. ':c0' => [
  813. 'value' => 1,
  814. 'type' => 'integer',
  815. 'placeholder' => 'c0',
  816. ],
  817. ':c1' => [
  818. 'value' => 2,
  819. 'type' => 'integer',
  820. 'placeholder' => 'c1',
  821. ],
  822. ':c2' => [
  823. 'value' => 3,
  824. 'type' => 'integer',
  825. 'placeholder' => 'c2',
  826. ],
  827. ':c3' => [
  828. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  829. 'type' => 'integer',
  830. 'placeholder' => 'c3',
  831. ],
  832. ],
  833. $valueBinder->bindings()
  834. );
  835. }
  836. public function testSqlInjectionViaUntypedElseValueIsNotPossible(): void
  837. {
  838. $expression = (new CaseStatementExpression(1))
  839. ->when(2)
  840. ->then(3)
  841. ->else('1 THEN 1 END; DELETE * FROM foo; --');
  842. $valueBinder = new ValueBinder();
  843. $sql = $expression->sql($valueBinder);
  844. $this->assertSame(
  845. 'CASE :c0 WHEN :c1 THEN :c2 ELSE :c3 END',
  846. $sql
  847. );
  848. $this->assertSame(
  849. [
  850. ':c0' => [
  851. 'value' => 1,
  852. 'type' => 'integer',
  853. 'placeholder' => 'c0',
  854. ],
  855. ':c1' => [
  856. 'value' => 2,
  857. 'type' => 'integer',
  858. 'placeholder' => 'c1',
  859. ],
  860. ':c2' => [
  861. 'value' => 3,
  862. 'type' => 'integer',
  863. 'placeholder' => 'c2',
  864. ],
  865. ':c3' => [
  866. 'value' => '1 THEN 1 END; DELETE * FROM foo; --',
  867. 'type' => 'string',
  868. 'placeholder' => 'c3',
  869. ],
  870. ],
  871. $valueBinder->bindings()
  872. );
  873. }
  874. // endregion
  875. // region Getters
  876. public function testGetInvalidCaseExpressionClause()
  877. {
  878. $this->expectException(InvalidArgumentException::class);
  879. $this->expectExceptionMessage(
  880. 'The `$clause` argument must be one of `value`, `when`, `else`, the given value `invalid` is invalid.'
  881. );
  882. (new CaseStatementExpression())->clause('invalid');
  883. }
  884. public function testGetInvalidWhenThenExpressionClause()
  885. {
  886. $this->expectException(InvalidArgumentException::class);
  887. $this->expectExceptionMessage(
  888. 'The `$clause` argument must be one of `when`, `then`, the given value `invalid` is invalid.'
  889. );
  890. (new WhenThenExpression())->clause('invalid');
  891. }
  892. public function testGetValueClause(): void
  893. {
  894. $expression = new CaseStatementExpression();
  895. $this->assertNull($expression->clause('value'));
  896. $expression = (new CaseStatementExpression(1))
  897. ->when(1)
  898. ->then(2);
  899. $this->assertSame(1, $expression->clause('value'));
  900. }
  901. public function testGetWhenClause(): void
  902. {
  903. $when = ['Table.column' => true];
  904. $expression = new CaseStatementExpression();
  905. $this->assertSame([], $expression->clause('when'));
  906. $expression
  907. ->when($when)
  908. ->then(1);
  909. $this->assertCount(1, $expression->clause('when'));
  910. $this->assertInstanceOf(WhenThenExpression::class, $expression->clause('when')[0]);
  911. }
  912. public function testWhenArrayValueGetWhenClause(): void
  913. {
  914. $when = ['Table.column' => true];
  915. $expression = new CaseStatementExpression();
  916. $this->assertSame([], $expression->clause('when'));
  917. $expression
  918. ->when($when)
  919. ->then(1);
  920. $this->assertEquals(
  921. new QueryExpression($when),
  922. $expression->clause('when')[0]->clause('when')
  923. );
  924. }
  925. public function testWhenNonArrayValueGetWhenClause(): void
  926. {
  927. $expression = new CaseStatementExpression();
  928. $this->assertSame([], $expression->clause('when'));
  929. $expression
  930. ->when(1)
  931. ->then(2);
  932. $this->assertSame(1, $expression->clause('when')[0]->clause('when'));
  933. }
  934. public function testWhenGetThenClause(): void
  935. {
  936. $expression = (new CaseStatementExpression())
  937. ->when(function (WhenThenExpression $whenThen) {
  938. return $whenThen;
  939. });
  940. $this->assertNull($expression->clause('when')[0]->clause('then'));
  941. $expression->clause('when')[0]->then(1);
  942. $this->assertSame(1, $expression->clause('when')[0]->clause('then'));
  943. }
  944. public function testGetElseClause(): void
  945. {
  946. $expression = new CaseStatementExpression();
  947. $this->assertNull($expression->clause('else'));
  948. $expression
  949. ->when(['Table.column' => true])
  950. ->then(1)
  951. ->else(2);
  952. $this->assertSame(2, $expression->clause('else'));
  953. }
  954. // endregion
  955. // region Order based syntax
  956. public function testWhenThenElse(): void
  957. {
  958. $expression = (new CaseStatementExpression())
  959. ->when(['Table.column_a' => true, 'Table.column_b IS' => null])
  960. ->then(1)
  961. ->when(['Table.column_c' => true, 'Table.column_d IS NOT' => null])
  962. ->then(2)
  963. ->else(3);
  964. $valueBinder = new ValueBinder();
  965. $sql = $expression->sql($valueBinder);
  966. $this->assertSame(
  967. 'CASE ' .
  968. 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
  969. 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
  970. 'ELSE :c4 ' .
  971. 'END',
  972. $sql
  973. );
  974. }
  975. public function testWhenBeforeClosingThenFails(): void
  976. {
  977. $this->expectException(LogicException::class);
  978. $this->expectExceptionMessage('Cannot call `when()` between `when()` and `then()`.');
  979. (new CaseStatementExpression())
  980. ->when(['Table.column_a' => true])
  981. ->when(['Table.column_b' => true]);
  982. }
  983. public function testElseBeforeClosingThenFails(): void
  984. {
  985. $this->expectException(LogicException::class);
  986. $this->expectExceptionMessage('Cannot call `else()` between `when()` and `then()`.');
  987. (new CaseStatementExpression())
  988. ->when(['Table.column' => true])
  989. ->else(1);
  990. }
  991. public function testThenBeforeOpeningWhenFails(): void
  992. {
  993. $this->expectException(LogicException::class);
  994. $this->expectExceptionMessage('Cannot call `then()` before `when()`.');
  995. (new CaseStatementExpression())
  996. ->then(1);
  997. }
  998. // endregion
  999. // region Callable syntax
  1000. public function testWhenCallables(): void
  1001. {
  1002. $expression = (new CaseStatementExpression())
  1003. ->when(function (WhenThenExpression $whenThen) {
  1004. return $whenThen
  1005. ->when([
  1006. 'Table.column_a' => true,
  1007. 'Table.column_b IS' => null,
  1008. ])
  1009. ->then(1);
  1010. })
  1011. ->when(function (WhenThenExpression $whenThen) {
  1012. return $whenThen
  1013. ->when([
  1014. 'Table.column_c' => true,
  1015. 'Table.column_d IS NOT' => null,
  1016. ])
  1017. ->then(2);
  1018. })
  1019. ->else(3);
  1020. $valueBinder = new ValueBinder();
  1021. $sql = $expression->sql($valueBinder);
  1022. $this->assertSame(
  1023. 'CASE ' .
  1024. 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
  1025. 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
  1026. 'ELSE :c4 ' .
  1027. 'END',
  1028. $sql
  1029. );
  1030. }
  1031. public function testWhenCallablesWithCustomWhenThenExpressions(): void
  1032. {
  1033. $expression = (new CaseStatementExpression())
  1034. ->when(function () {
  1035. return (new CustomWhenThenExpression())
  1036. ->when([
  1037. 'Table.column_a' => true,
  1038. 'Table.column_b IS' => null,
  1039. ])
  1040. ->then(1);
  1041. })
  1042. ->when(function () {
  1043. return (new CustomWhenThenExpression())
  1044. ->when([
  1045. 'Table.column_c' => true,
  1046. 'Table.column_d IS NOT' => null,
  1047. ])
  1048. ->then(2);
  1049. })
  1050. ->else(3);
  1051. $valueBinder = new ValueBinder();
  1052. $sql = $expression->sql($valueBinder);
  1053. $this->assertSame(
  1054. 'CASE ' .
  1055. 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
  1056. 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
  1057. 'ELSE :c4 ' .
  1058. 'END',
  1059. $sql
  1060. );
  1061. }
  1062. public function testWhenCallablesWithInvalidReturnTypeFails(): void
  1063. {
  1064. $this->expectException(LogicException::class);
  1065. $this->expectExceptionMessage(
  1066. '`when()` callables must return an instance of ' .
  1067. '`\Cake\Database\Expression\WhenThenExpression`, `null` given.'
  1068. );
  1069. $this->deprecated(function () {
  1070. (new CaseStatementExpression())
  1071. ->when(function () {
  1072. return null;
  1073. });
  1074. });
  1075. }
  1076. // endregion
  1077. // region Self-contained values
  1078. public function testSelfContainedWhenThenExpressions(): void
  1079. {
  1080. $expression = (new CaseStatementExpression())
  1081. ->when(
  1082. (new WhenThenExpression())
  1083. ->when([
  1084. 'Table.column_a' => true,
  1085. 'Table.column_b IS' => null,
  1086. ])
  1087. ->then(1)
  1088. )
  1089. ->when(
  1090. (new WhenThenExpression())
  1091. ->when([
  1092. 'Table.column_c' => true,
  1093. 'Table.column_d IS NOT' => null,
  1094. ])
  1095. ->then(2)
  1096. )
  1097. ->else(3);
  1098. $valueBinder = new ValueBinder();
  1099. $sql = $expression->sql($valueBinder);
  1100. $this->assertSame(
  1101. 'CASE ' .
  1102. 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
  1103. 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
  1104. 'ELSE :c4 ' .
  1105. 'END',
  1106. $sql
  1107. );
  1108. }
  1109. public function testSelfContainedCustomWhenThenExpressions(): void
  1110. {
  1111. $expression = (new CaseStatementExpression())
  1112. ->when(
  1113. (new CustomWhenThenExpression())
  1114. ->when([
  1115. 'Table.column_a' => true,
  1116. 'Table.column_b IS' => null,
  1117. ])
  1118. ->then(1)
  1119. )
  1120. ->when(
  1121. (new CustomWhenThenExpression())
  1122. ->when([
  1123. 'Table.column_c' => true,
  1124. 'Table.column_d IS NOT' => null,
  1125. ])
  1126. ->then(2)
  1127. )
  1128. ->else(3);
  1129. $valueBinder = new ValueBinder();
  1130. $sql = $expression->sql($valueBinder);
  1131. $this->assertSame(
  1132. 'CASE ' .
  1133. 'WHEN (Table.column_a = :c0 AND (Table.column_b) IS NULL) THEN :c1 ' .
  1134. 'WHEN (Table.column_c = :c2 AND (Table.column_d) IS NOT NULL) THEN :c3 ' .
  1135. 'ELSE :c4 ' .
  1136. 'END',
  1137. $sql
  1138. );
  1139. }
  1140. // endregion
  1141. // region Incomplete states
  1142. public function testCompilingEmptyCaseExpressionFails(): void
  1143. {
  1144. $this->expectException(LogicException::class);
  1145. $this->expectExceptionMessage('Case expression must have at least one when statement.');
  1146. $this->deprecated(function () {
  1147. (new CaseStatementExpression())->sql(new ValueBinder());
  1148. });
  1149. }
  1150. public function testCompilingNonClosedWhenFails(): void
  1151. {
  1152. $this->expectException(LogicException::class);
  1153. $this->expectExceptionMessage('Case expression has incomplete when clause. Missing `then()` after `when()`.');
  1154. $this->deprecated(function () {
  1155. (new CaseStatementExpression())
  1156. ->when(['Table.column' => true])
  1157. ->sql(new ValueBinder());
  1158. });
  1159. }
  1160. public function testCompilingWhenThenExpressionWithMissingWhenFails(): void
  1161. {
  1162. $this->expectException(LogicException::class);
  1163. $this->expectExceptionMessage('Case expression has incomplete when clause. Missing `when()`.');
  1164. $this->deprecated(function () {
  1165. (new CaseStatementExpression())
  1166. ->when(function (WhenThenExpression $whenThen) {
  1167. return $whenThen->then(1);
  1168. })
  1169. ->sql(new ValueBinder());
  1170. });
  1171. }
  1172. public function testCompilingWhenThenExpressionWithMissingThenFails(): void
  1173. {
  1174. $this->expectException(LogicException::class);
  1175. $this->expectExceptionMessage('Case expression has incomplete when clause. Missing `then()` after `when()`.');
  1176. $this->deprecated(function () {
  1177. (new CaseStatementExpression())
  1178. ->when(function (WhenThenExpression $whenThen) {
  1179. return $whenThen->when(1);
  1180. })
  1181. ->sql(new ValueBinder());
  1182. });
  1183. }
  1184. // endregion
  1185. // region Valid values
  1186. public function validCaseValuesDataProvider(): array
  1187. {
  1188. return [
  1189. [null, 'NULL', null],
  1190. ['0', null, 'string'],
  1191. [0, null, 'integer'],
  1192. [0.0, null, 'float'],
  1193. ['foo', null, 'string'],
  1194. [true, null, 'boolean'],
  1195. [Date::now(), null, 'date'],
  1196. [ChronosDate::now(), null, 'date'],
  1197. [DateTime::now(), null, 'datetime'],
  1198. [Chronos::now(), null, 'datetime'],
  1199. [new IdentifierExpression('Table.column'), 'Table.column', null],
  1200. [new QueryExpression('Table.column'), 'Table.column', null],
  1201. [ConnectionManager::get('test')->newQuery()->select('a'), '(SELECT a)', null],
  1202. [new TestObjectWithToString(), null, 'string'],
  1203. [new stdClass(), null, null],
  1204. ];
  1205. }
  1206. /**
  1207. * @dataProvider validCaseValuesDataProvider
  1208. * @param mixed $value The case value.
  1209. * @param string|null $sqlValue The expected SQL string value.
  1210. * @param string|null $type The expected bound type.
  1211. */
  1212. public function testValidCaseValue($value, ?string $sqlValue, ?string $type): void
  1213. {
  1214. $expression = (new CaseStatementExpression($value))
  1215. ->when(1)
  1216. ->then(2);
  1217. $valueBinder = new ValueBinder();
  1218. $sql = $expression->sql($valueBinder);
  1219. if ($sqlValue) {
  1220. $this->assertEqualsSql(
  1221. "CASE $sqlValue WHEN :c0 THEN :c1 ELSE NULL END",
  1222. $sql
  1223. );
  1224. $this->assertSame(
  1225. [
  1226. ':c0' => [
  1227. 'value' => 1,
  1228. 'type' => 'integer',
  1229. 'placeholder' => 'c0',
  1230. ],
  1231. ':c1' => [
  1232. 'value' => 2,
  1233. 'type' => 'integer',
  1234. 'placeholder' => 'c1',
  1235. ],
  1236. ],
  1237. $valueBinder->bindings()
  1238. );
  1239. } else {
  1240. $this->assertEqualsSql(
  1241. 'CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END',
  1242. $sql
  1243. );
  1244. $this->assertSame(
  1245. [
  1246. ':c0' => [
  1247. 'value' => $value,
  1248. 'type' => $type,
  1249. 'placeholder' => 'c0',
  1250. ],
  1251. ':c1' => [
  1252. 'value' => 1,
  1253. 'type' => 'integer',
  1254. 'placeholder' => 'c1',
  1255. ],
  1256. ':c2' => [
  1257. 'value' => 2,
  1258. 'type' => 'integer',
  1259. 'placeholder' => 'c2',
  1260. ],
  1261. ],
  1262. $valueBinder->bindings()
  1263. );
  1264. }
  1265. }
  1266. public function validWhenValuesSimpleCaseDataProvider(): array
  1267. {
  1268. return [
  1269. ['0', null, 'string'],
  1270. [0, null, 'integer'],
  1271. [0.0, null, 'float'],
  1272. ['foo', null, 'string'],
  1273. [true, null, 'boolean'],
  1274. [new stdClass(), null, null],
  1275. [new TestObjectWithToString(), null, 'string'],
  1276. [Date::now(), null, 'date'],
  1277. [ChronosDate::now(), null, 'date'],
  1278. [DateTime::now(), null, 'datetime'],
  1279. [Chronos::now(), null, 'datetime'],
  1280. [
  1281. new IdentifierExpression('Table.column'),
  1282. 'CASE :c0 WHEN Table.column THEN :c1 ELSE NULL END',
  1283. [
  1284. ':c0' => [
  1285. 'value' => true,
  1286. 'type' => 'boolean',
  1287. 'placeholder' => 'c0',
  1288. ],
  1289. ':c1' => [
  1290. 'value' => 2,
  1291. 'type' => 'integer',
  1292. 'placeholder' => 'c1',
  1293. ],
  1294. ],
  1295. ],
  1296. [
  1297. new QueryExpression('Table.column'),
  1298. 'CASE :c0 WHEN Table.column THEN :c1 ELSE NULL END',
  1299. [
  1300. ':c0' => [
  1301. 'value' => true,
  1302. 'type' => 'boolean',
  1303. 'placeholder' => 'c0',
  1304. ],
  1305. ':c1' => [
  1306. 'value' => 2,
  1307. 'type' => 'integer',
  1308. 'placeholder' => 'c1',
  1309. ],
  1310. ],
  1311. ],
  1312. [
  1313. ConnectionManager::get('test')->newQuery()->select('a'),
  1314. 'CASE :c0 WHEN (SELECT a) THEN :c1 ELSE NULL END',
  1315. [
  1316. ':c0' => [
  1317. 'value' => true,
  1318. 'type' => 'boolean',
  1319. 'placeholder' => 'c0',
  1320. ],
  1321. ':c1' => [
  1322. 'value' => 2,
  1323. 'type' => 'integer',
  1324. 'placeholder' => 'c1',
  1325. ],
  1326. ],
  1327. ],
  1328. [
  1329. [
  1330. 'Table.column_a' => 1,
  1331. 'Table.column_b' => 'foo',
  1332. ],
  1333. 'CASE :c0 WHEN (Table.column_a = :c1 AND Table.column_b = :c2) THEN :c3 ELSE NULL END',
  1334. [
  1335. ':c0' => [
  1336. 'value' => true,
  1337. 'type' => 'boolean',
  1338. 'placeholder' => 'c0',
  1339. ],
  1340. ':c1' => [
  1341. 'value' => 1,
  1342. 'type' => 'integer',
  1343. 'placeholder' => 'c1',
  1344. ],
  1345. ':c2' => [
  1346. 'value' => 'foo',
  1347. 'type' => 'string',
  1348. 'placeholder' => 'c2',
  1349. ],
  1350. ':c3' => [
  1351. 'value' => 2,
  1352. 'type' => 'integer',
  1353. 'placeholder' => 'c3',
  1354. ],
  1355. ],
  1356. ],
  1357. ];
  1358. }
  1359. /**
  1360. * @dataProvider validWhenValuesSimpleCaseDataProvider
  1361. * @param mixed $value The when value.
  1362. * @param string|null $expectedSql The expected SQL string.
  1363. * @param array|string|null $typeOrBindings The expected bound type(s).
  1364. */
  1365. public function testValidWhenValueSimpleCase($value, ?string $expectedSql, $typeOrBindings = null): void
  1366. {
  1367. $typeMap = new TypeMap([
  1368. 'Table.column_a' => 'integer',
  1369. 'Table.column_b' => 'string',
  1370. ]);
  1371. $expression = (new CaseStatementExpression(true))
  1372. ->setTypeMap($typeMap)
  1373. ->when($value)
  1374. ->then(2);
  1375. $valueBinder = new ValueBinder();
  1376. $sql = $expression->sql($valueBinder);
  1377. if ($expectedSql) {
  1378. $this->assertEqualsSql($expectedSql, $sql);
  1379. $this->assertSame($typeOrBindings, $valueBinder->bindings());
  1380. } else {
  1381. $this->assertEqualsSql('CASE :c0 WHEN :c1 THEN :c2 ELSE NULL END', $sql);
  1382. $this->assertSame(
  1383. [
  1384. ':c0' => [
  1385. 'value' => true,
  1386. 'type' => 'boolean',
  1387. 'placeholder' => 'c0',
  1388. ],
  1389. ':c1' => [
  1390. 'value' => $value,
  1391. 'type' => $typeOrBindings,
  1392. 'placeholder' => 'c1',
  1393. ],
  1394. ':c2' => [
  1395. 'value' => 2,
  1396. 'type' => 'integer',
  1397. 'placeholder' => 'c2',
  1398. ],
  1399. ],
  1400. $valueBinder->bindings()
  1401. );
  1402. }
  1403. }
  1404. public function validWhenValuesSearchedCaseDataProvider(): array
  1405. {
  1406. return [
  1407. ['0', null, 'string'],
  1408. [0, null, 'integer'],
  1409. [0.0, null, 'float'],
  1410. ['foo', null, 'string'],
  1411. [true, null, 'boolean'],
  1412. [new stdClass(), null, null],
  1413. [new TestObjectWithToString(), null, 'string'],
  1414. [Date::now(), null, 'date'],
  1415. [ChronosDate::now(), null, 'date'],
  1416. [DateTime::now(), null, 'datetime'],
  1417. [Chronos::now(), null, 'datetime'],
  1418. [
  1419. new IdentifierExpression('Table.column'),
  1420. 'CASE WHEN Table.column THEN :c0 ELSE NULL END',
  1421. [
  1422. ':c0' => [
  1423. 'value' => 2,
  1424. 'type' => 'integer',
  1425. 'placeholder' => 'c0',
  1426. ],
  1427. ],
  1428. ],
  1429. [
  1430. new QueryExpression('Table.column'),
  1431. 'CASE WHEN Table.column THEN :c0 ELSE NULL END',
  1432. [
  1433. ':c0' => [
  1434. 'value' => 2,
  1435. 'type' => 'integer',
  1436. 'placeholder' => 'c0',
  1437. ],
  1438. ],
  1439. ],
  1440. [
  1441. ConnectionManager::get('test')->newQuery()->select('a'),
  1442. 'CASE WHEN (SELECT a) THEN :c0 ELSE NULL END',
  1443. [
  1444. ':c0' => [
  1445. 'value' => 2,
  1446. 'type' => 'integer',
  1447. 'placeholder' => 'c0',
  1448. ],
  1449. ],
  1450. ],
  1451. [
  1452. [
  1453. 'Table.column_a' => 1,
  1454. 'Table.column_b' => 'foo',
  1455. ],
  1456. 'CASE WHEN (Table.column_a = :c0 AND Table.column_b = :c1) THEN :c2 ELSE NULL END',
  1457. [
  1458. ':c0' => [
  1459. 'value' => 1,
  1460. 'type' => 'integer',
  1461. 'placeholder' => 'c0',
  1462. ],
  1463. ':c1' => [
  1464. 'value' => 'foo',
  1465. 'type' => 'string',
  1466. 'placeholder' => 'c1',
  1467. ],
  1468. ':c2' => [
  1469. 'value' => 2,
  1470. 'type' => 'integer',
  1471. 'placeholder' => 'c2',
  1472. ],
  1473. ],
  1474. ],
  1475. ];
  1476. }
  1477. /**
  1478. * @dataProvider validWhenValuesSearchedCaseDataProvider
  1479. * @param mixed $value The when value.
  1480. * @param string|null $expectedSql The expected SQL string.
  1481. * @param array|string|null $typeOrBindings The expected bound type(s).
  1482. */
  1483. public function testValidWhenValueSearchedCase($value, ?string $expectedSql, $typeOrBindings = null): void
  1484. {
  1485. $typeMap = new TypeMap([
  1486. 'Table.column_a' => 'integer',
  1487. 'Table.column_b' => 'string',
  1488. ]);
  1489. $expression = (new CaseStatementExpression())
  1490. ->setTypeMap($typeMap)
  1491. ->when($value)
  1492. ->then(2);
  1493. $valueBinder = new ValueBinder();
  1494. $sql = $expression->sql($valueBinder);
  1495. if ($expectedSql) {
  1496. $this->assertEqualsSql($expectedSql, $sql);
  1497. $this->assertSame($typeOrBindings, $valueBinder->bindings());
  1498. } else {
  1499. $this->assertEqualsSql('CASE WHEN :c0 THEN :c1 ELSE NULL END', $sql);
  1500. $this->assertSame(
  1501. [
  1502. ':c0' => [
  1503. 'value' => $value,
  1504. 'type' => $typeOrBindings,
  1505. 'placeholder' => 'c0',
  1506. ],
  1507. ':c1' => [
  1508. 'value' => 2,
  1509. 'type' => 'integer',
  1510. 'placeholder' => 'c1',
  1511. ],
  1512. ],
  1513. $valueBinder->bindings()
  1514. );
  1515. }
  1516. }
  1517. public function validThenValuesDataProvider(): array
  1518. {
  1519. return [
  1520. [null, 'NULL', null],
  1521. ['0', null, 'string'],
  1522. [0, null, 'integer'],
  1523. [0.0, null, 'float'],
  1524. ['foo', null, 'string'],
  1525. [true, null, 'boolean'],
  1526. [Date::now(), null, 'date'],
  1527. [ChronosDate::now(), null, 'date'],
  1528. [DateTime::now(), null, 'datetime'],
  1529. [Chronos::now(), null, 'datetime'],
  1530. [new IdentifierExpression('Table.column'), 'Table.column', null],
  1531. [new QueryExpression('Table.column'), 'Table.column', null],
  1532. [ConnectionManager::get('test')->newQuery()->select('a'), '(SELECT a)', null],
  1533. [new TestObjectWithToString(), null, 'string'],
  1534. [new stdClass(), null, null],
  1535. ];
  1536. }
  1537. /**
  1538. * @dataProvider validThenValuesDataProvider
  1539. * @param mixed $value The then value.
  1540. * @param string|null $sqlValue The expected SQL string value.
  1541. * @param string|null $type The expected bound type.
  1542. */
  1543. public function testValidThenValue($value, ?string $sqlValue, ?string $type): void
  1544. {
  1545. $expression = (new CaseStatementExpression())
  1546. ->when(1)
  1547. ->then($value);
  1548. $valueBinder = new ValueBinder();
  1549. $sql = $expression->sql($valueBinder);
  1550. if ($sqlValue) {
  1551. $this->assertEqualsSql(
  1552. "CASE WHEN :c0 THEN $sqlValue ELSE NULL END",
  1553. $sql
  1554. );
  1555. $this->assertSame(
  1556. [
  1557. ':c0' => [
  1558. 'value' => 1,
  1559. 'type' => 'integer',
  1560. 'placeholder' => 'c0',
  1561. ],
  1562. ],
  1563. $valueBinder->bindings()
  1564. );
  1565. } else {
  1566. $this->assertEqualsSql(
  1567. 'CASE WHEN :c0 THEN :c1 ELSE NULL END',
  1568. $sql
  1569. );
  1570. $this->assertSame(
  1571. [
  1572. ':c0' => [
  1573. 'value' => 1,
  1574. 'type' => 'integer',
  1575. 'placeholder' => 'c0',
  1576. ],
  1577. ':c1' => [
  1578. 'value' => $value,
  1579. 'type' => $type,
  1580. 'placeholder' => 'c1',
  1581. ],
  1582. ],
  1583. $valueBinder->bindings()
  1584. );
  1585. }
  1586. }
  1587. public function validElseValuesDataProvider(): array
  1588. {
  1589. return [
  1590. [null, 'NULL', null],
  1591. ['0', null, 'string'],
  1592. [0, null, 'integer'],
  1593. [0.0, null, 'float'],
  1594. ['foo', null, 'string'],
  1595. [true, null, 'boolean'],
  1596. [Date::now(), null, 'date'],
  1597. [ChronosDate::now(), null, 'date'],
  1598. [DateTime::now(), null, 'datetime'],
  1599. [Chronos::now(), null, 'datetime'],
  1600. [new IdentifierExpression('Table.column'), 'Table.column', null],
  1601. [new QueryExpression('Table.column'), 'Table.column', null],
  1602. [ConnectionManager::get('test')->newQuery()->select('a'), '(SELECT a)', null],
  1603. [new TestObjectWithToString(), null, 'string'],
  1604. [new stdClass(), null, null],
  1605. ];
  1606. }
  1607. /**
  1608. * @dataProvider validElseValuesDataProvider
  1609. * @param mixed $value The else value.
  1610. * @param string|null $sqlValue The expected SQL string value.
  1611. * @param string|null $type The expected bound type.
  1612. */
  1613. public function testValidElseValue($value, ?string $sqlValue, ?string $type): void
  1614. {
  1615. $expression = (new CaseStatementExpression())
  1616. ->when(1)
  1617. ->then(2)
  1618. ->else($value);
  1619. $valueBinder = new ValueBinder();
  1620. $sql = $expression->sql($valueBinder);
  1621. if ($sqlValue) {
  1622. $this->assertEqualsSql(
  1623. "CASE WHEN :c0 THEN :c1 ELSE $sqlValue END",
  1624. $sql
  1625. );
  1626. $this->assertSame(
  1627. [
  1628. ':c0' => [
  1629. 'value' => 1,
  1630. 'type' => 'integer',
  1631. 'placeholder' => 'c0',
  1632. ],
  1633. ':c1' => [
  1634. 'value' => 2,
  1635. 'type' => 'integer',
  1636. 'placeholder' => 'c1',
  1637. ],
  1638. ],
  1639. $valueBinder->bindings()
  1640. );
  1641. } else {
  1642. $this->assertEqualsSql(
  1643. 'CASE WHEN :c0 THEN :c1 ELSE :c2 END',
  1644. $sql
  1645. );
  1646. $this->assertSame(
  1647. [
  1648. ':c0' => [
  1649. 'value' => 1,
  1650. 'type' => 'integer',
  1651. 'placeholder' => 'c0',
  1652. ],
  1653. ':c1' => [
  1654. 'value' => 2,
  1655. 'type' => 'integer',
  1656. 'placeholder' => 'c1',
  1657. ],
  1658. ':c2' => [
  1659. 'value' => $value,
  1660. 'type' => $type,
  1661. 'placeholder' => 'c2',
  1662. ],
  1663. ],
  1664. $valueBinder->bindings()
  1665. );
  1666. }
  1667. }
  1668. // endregion
  1669. // region Invalid values
  1670. public function invalidCaseValuesDataProvider(): array
  1671. {
  1672. $res = fopen('data:text/plain,123', 'rb');
  1673. fclose($res);
  1674. return [
  1675. [[], 'array'],
  1676. [
  1677. function () {
  1678. },
  1679. 'Closure',
  1680. ],
  1681. [$res, 'resource (closed)'],
  1682. ];
  1683. }
  1684. /**
  1685. * @dataProvider invalidCaseValuesDataProvider
  1686. * @param mixed $value The case value.
  1687. * @param string $typeName The expected error type name.
  1688. */
  1689. public function testInvalidCaseValue($value, string $typeName): void
  1690. {
  1691. $this->expectException(InvalidArgumentException::class);
  1692. $this->expectExceptionMessage(
  1693. 'The `$value` argument must be either `null`, a scalar value, an object, ' .
  1694. "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
  1695. );
  1696. new CaseStatementExpression($value);
  1697. }
  1698. public function invalidWhenValueDataProvider(): array
  1699. {
  1700. $res = fopen('data:text/plain,123', 'rb');
  1701. fclose($res);
  1702. return [
  1703. [null, 'null'],
  1704. [[], '[]'],
  1705. [$res, 'resource (closed)'],
  1706. ];
  1707. }
  1708. /**
  1709. * @dataProvider invalidWhenValueDataProvider
  1710. * @param mixed $value The when value.
  1711. * @param string $typeName The expected error type name.
  1712. */
  1713. public function testInvalidWhenValue($value, string $typeName): void
  1714. {
  1715. $this->expectException(InvalidArgumentException::class);
  1716. $this->expectExceptionMessage(
  1717. 'The `$when` argument must be either a non-empty array, a scalar value, an object, ' .
  1718. "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
  1719. );
  1720. (new CaseStatementExpression())
  1721. ->when($value)
  1722. ->then(1);
  1723. }
  1724. public function invalidWhenTypeDataProvider(): array
  1725. {
  1726. $res = fopen('data:text/plain,123', 'rb');
  1727. fclose($res);
  1728. return [
  1729. [1, 'int'],
  1730. [1.0, 'float'],
  1731. [new stdClass(), 'stdClass'],
  1732. [
  1733. function () {
  1734. },
  1735. 'Closure',
  1736. ],
  1737. [$res, 'resource (closed)'],
  1738. ];
  1739. }
  1740. /**
  1741. * @dataProvider invalidWhenTypeDataProvider
  1742. * @param mixed $type The when type.
  1743. * @param string $typeName The expected error type name.
  1744. */
  1745. public function testInvalidWhenType($type, string $typeName): void
  1746. {
  1747. $this->expectException(InvalidArgumentException::class);
  1748. $this->expectExceptionMessage(
  1749. "The `\$type` argument must be either an array, a string, or `null`, `$typeName` given."
  1750. );
  1751. (new CaseStatementExpression())
  1752. ->when(1, $type)
  1753. ->then(1);
  1754. }
  1755. public function invalidThenValueDataProvider(): array
  1756. {
  1757. $res = fopen('data:text/plain,123', 'rb');
  1758. fclose($res);
  1759. return [
  1760. [[], 'array'],
  1761. [
  1762. function () {
  1763. },
  1764. 'Closure',
  1765. ],
  1766. [$res, 'resource (closed)'],
  1767. ];
  1768. }
  1769. /**
  1770. * @dataProvider invalidThenValueDataProvider
  1771. * @param mixed $value The then value.
  1772. * @param string $typeName The expected error type name.
  1773. */
  1774. public function testInvalidThenValue($value, string $typeName): void
  1775. {
  1776. $this->expectException(InvalidArgumentException::class);
  1777. $this->expectExceptionMessage(
  1778. 'The `$result` argument must be either `null`, a scalar value, an object, ' .
  1779. "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
  1780. );
  1781. (new CaseStatementExpression())
  1782. ->when(1)
  1783. ->then($value);
  1784. }
  1785. public function invalidThenTypeDataProvider(): array
  1786. {
  1787. $res = fopen('data:text/plain,123', 'rb');
  1788. fclose($res);
  1789. return [
  1790. [1],
  1791. [1.0],
  1792. [new stdClass()],
  1793. [
  1794. function () {
  1795. },
  1796. ],
  1797. [$res, 'resource (closed)'],
  1798. ];
  1799. }
  1800. /**
  1801. * @dataProvider invalidThenTypeDataProvider
  1802. * @param mixed $type The then type.
  1803. */
  1804. public function testInvalidThenType($type): void
  1805. {
  1806. $this->expectException(TypeError::class);
  1807. (new CaseStatementExpression())
  1808. ->when(1)
  1809. ->then(1, $type);
  1810. }
  1811. public function invalidElseValueDataProvider(): array
  1812. {
  1813. $res = fopen('data:text/plain,123', 'rb');
  1814. fclose($res);
  1815. return [
  1816. [[], 'array'],
  1817. [
  1818. function () {
  1819. },
  1820. 'Closure',
  1821. ],
  1822. [$res, 'resource (closed)'],
  1823. ];
  1824. }
  1825. /**
  1826. * @dataProvider invalidElseValueDataProvider
  1827. * @param mixed $value The else value.
  1828. * @param string $typeName The expected error type name.
  1829. */
  1830. public function testInvalidElseValue($value, string $typeName): void
  1831. {
  1832. $this->expectException(InvalidArgumentException::class);
  1833. $this->expectExceptionMessage(
  1834. 'The `$result` argument must be either `null`, a scalar value, an object, ' .
  1835. "or an instance of `\\Cake\\Database\\ExpressionInterface`, `$typeName` given."
  1836. );
  1837. (new CaseStatementExpression())
  1838. ->when(1)
  1839. ->then(1)
  1840. ->else($value);
  1841. }
  1842. public function invalidElseTypeDataProvider(): array
  1843. {
  1844. $res = fopen('data:text/plain,123', 'rb');
  1845. fclose($res);
  1846. return [
  1847. [1],
  1848. [1.0],
  1849. [new stdClass()],
  1850. [
  1851. function () {
  1852. },
  1853. 'Closure',
  1854. ],
  1855. [$res, 'resource (closed)'],
  1856. ];
  1857. }
  1858. /**
  1859. * @dataProvider invalidElseTypeDataProvider
  1860. * @param mixed $type The else type.
  1861. */
  1862. public function testInvalidElseType($type): void
  1863. {
  1864. $this->expectException(TypeError::class);
  1865. (new CaseStatementExpression())
  1866. ->when(1)
  1867. ->then(1)
  1868. ->else(1, $type);
  1869. }
  1870. // endregion
  1871. // region Traversal
  1872. public function testTraverse(): void
  1873. {
  1874. $value = new IdentifierExpression('Table.column');
  1875. $conditionsA = ['Table.column_a' => true, 'Table.column_b IS' => null];
  1876. $resultA = new QueryExpression('1');
  1877. $conditionsB = ['Table.column_c' => true, 'Table.column_d IS NOT' => null];
  1878. $resultB = new QueryExpression('2');
  1879. $else = new QueryExpression('3');
  1880. $expression = (new CaseStatementExpression($value))
  1881. ->when($conditionsA)
  1882. ->then($resultA)
  1883. ->when($conditionsB)
  1884. ->then($resultB)
  1885. ->else($else);
  1886. $expressions = [];
  1887. $expression->traverse(function ($expression) use (&$expressions) {
  1888. $expressions[] = $expression;
  1889. });
  1890. $this->assertCount(14, $expressions);
  1891. $this->assertInstanceOf(IdentifierExpression::class, $expressions[0]);
  1892. $this->assertSame($value, $expressions[0]);
  1893. $this->assertInstanceOf(WhenThenExpression::class, $expressions[1]);
  1894. $this->assertEquals(new QueryExpression($conditionsA), $expressions[2]);
  1895. $this->assertEquals(new ComparisonExpression('Table.column_a', true), $expressions[3]);
  1896. $this->assertSame($resultA, $expressions[6]);
  1897. $this->assertInstanceOf(WhenThenExpression::class, $expressions[7]);
  1898. $this->assertEquals(new QueryExpression($conditionsB), $expressions[8]);
  1899. $this->assertEquals(new ComparisonExpression('Table.column_c', true), $expressions[9]);
  1900. $this->assertSame($resultB, $expressions[12]);
  1901. $this->assertSame($else, $expressions[13]);
  1902. }
  1903. public function testTraverseBeforeClosingThenFails(): void
  1904. {
  1905. $this->expectException(LogicException::class);
  1906. $this->expectExceptionMessage('Case expression has incomplete when clause. Missing `then()` after `when()`.');
  1907. $this->deprecated(function () {
  1908. $expression = (new CaseStatementExpression())
  1909. ->when(['Table.column' => true]);
  1910. $expression->traverse(
  1911. function () {
  1912. }
  1913. );
  1914. });
  1915. }
  1916. // endregion
  1917. // region Cloning
  1918. public function testClone(): void
  1919. {
  1920. $value = new IdentifierExpression('Table.column');
  1921. $conditionsA = ['Table.column_a' => true, 'Table.column_b IS' => null];
  1922. $resultA = new QueryExpression('1');
  1923. $conditionsB = ['Table.column_c' => true, 'Table.column_d IS NOT' => null];
  1924. $resultB = new QueryExpression('2');
  1925. $else = new QueryExpression('3');
  1926. $expression = (new CaseStatementExpression($value))
  1927. ->when($conditionsA)
  1928. ->then($resultA)
  1929. ->when($conditionsB)
  1930. ->then($resultB)
  1931. ->else($else);
  1932. $clone = clone $expression;
  1933. $this->assertEquals($clone, $expression);
  1934. $this->assertNotSame($clone, $expression);
  1935. }
  1936. public function testCloneBeforeClosingThenFails(): void
  1937. {
  1938. $this->expectException(LogicException::class);
  1939. $this->expectExceptionMessage('Case expression has incomplete when clause. Missing `then()` after `when()`.');
  1940. $this->deprecated(function () {
  1941. $expression = (new CaseStatementExpression())
  1942. ->when(['Table.column' => true]);
  1943. clone $expression;
  1944. });
  1945. }
  1946. // endregion
  1947. }