CaseStatementExpressionTest.php 72 KB

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