TableTest.php 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Core\Configure;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\Event\EventManager;
  22. use Cake\I18n\Time;
  23. use Cake\ORM\Table;
  24. use Cake\ORM\TableRegistry;
  25. use Cake\TestSuite\TestCase;
  26. use Cake\Validation\Validator;
  27. /**
  28. * Used to test correct class is instantiated when using TableRegistry::get();
  29. */
  30. class UsersTable extends Table
  31. {
  32. }
  33. /**
  34. * Tests Table class
  35. *
  36. */
  37. class TableTest extends TestCase
  38. {
  39. public $fixtures = [
  40. 'core.users', 'core.categories', 'core.articles', 'core.authors',
  41. 'core.tags', 'core.articles_tags'
  42. ];
  43. /**
  44. * Handy variable containing the next primary key that will be inserted in the
  45. * users table
  46. *
  47. * @var int
  48. */
  49. public static $nextUserId = 5;
  50. public function setUp()
  51. {
  52. parent::setUp();
  53. $this->connection = ConnectionManager::get('test');
  54. Configure::write('App.namespace', 'TestApp');
  55. $this->usersTypeMap = new TypeMap([
  56. 'Users.id' => 'integer',
  57. 'id' => 'integer',
  58. 'Users.username' => 'string',
  59. 'username' => 'string',
  60. 'Users.password' => 'string',
  61. 'password' => 'string',
  62. 'Users.created' => 'timestamp',
  63. 'created' => 'timestamp',
  64. 'Users.updated' => 'timestamp',
  65. 'updated' => 'timestamp',
  66. ]);
  67. $this->articlesTypeMap = new TypeMap([
  68. 'Articles.id' => 'integer',
  69. 'id' => 'integer',
  70. 'Articles.title' => 'string',
  71. 'title' => 'string',
  72. 'Articles.author_id' => 'integer',
  73. 'author_id' => 'integer',
  74. 'Articles.body' => 'text',
  75. 'body' => 'text',
  76. 'Articles.published' => 'string',
  77. 'published' => 'string',
  78. ]);
  79. }
  80. /**
  81. * teardown method
  82. *
  83. * @return void
  84. */
  85. public function tearDown()
  86. {
  87. parent::tearDown();
  88. TableRegistry::clear();
  89. }
  90. /**
  91. * Tests the table method
  92. *
  93. * @return void
  94. */
  95. public function testTableMethod()
  96. {
  97. $table = new Table(['table' => 'users']);
  98. $this->assertEquals('users', $table->table());
  99. $table = new UsersTable;
  100. $this->assertEquals('users', $table->table());
  101. $table = $this->getMockBuilder('\Cake\ORM\Table')
  102. ->setMethods(['find'])
  103. ->setMockClassName('SpecialThingsTable')
  104. ->getMock();
  105. $this->assertEquals('special_things', $table->table());
  106. $table = new Table(['alias' => 'LoveBoats']);
  107. $this->assertEquals('love_boats', $table->table());
  108. $table->table('other');
  109. $this->assertEquals('other', $table->table());
  110. }
  111. /**
  112. * Tests the alias method
  113. *
  114. * @return void
  115. */
  116. public function testAliasMethod()
  117. {
  118. $table = new Table(['alias' => 'users']);
  119. $this->assertEquals('users', $table->alias());
  120. $table = new Table(['table' => 'stuffs']);
  121. $this->assertEquals('stuffs', $table->alias());
  122. $table = new UsersTable;
  123. $this->assertEquals('Users', $table->alias());
  124. $table = $this->getMockBuilder('\Cake\ORM\Table')
  125. ->setMethods(['find'])
  126. ->setMockClassName('SpecialThingTable')
  127. ->getMock();
  128. $this->assertEquals('SpecialThing', $table->alias());
  129. $table->alias('AnotherOne');
  130. $this->assertEquals('AnotherOne', $table->alias());
  131. }
  132. /**
  133. * Tests connection method
  134. *
  135. * @return void
  136. */
  137. public function testConnection()
  138. {
  139. $table = new Table(['table' => 'users']);
  140. $this->assertNull($table->connection());
  141. $table->connection($this->connection);
  142. $this->assertSame($this->connection, $table->connection());
  143. }
  144. /**
  145. * Tests primaryKey method
  146. *
  147. * @return void
  148. */
  149. public function testPrimaryKey()
  150. {
  151. $table = new Table([
  152. 'table' => 'users',
  153. 'schema' => [
  154. 'id' => ['type' => 'integer'],
  155. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  156. ]
  157. ]);
  158. $this->assertEquals('id', $table->primaryKey());
  159. $table->primaryKey('thingID');
  160. $this->assertEquals('thingID', $table->primaryKey());
  161. $table->primaryKey(['thingID', 'user_id']);
  162. $this->assertEquals(['thingID', 'user_id'], $table->primaryKey());
  163. }
  164. /**
  165. * Tests that name will be selected as a displayField
  166. *
  167. * @return void
  168. */
  169. public function testDisplayFieldName()
  170. {
  171. $table = new Table([
  172. 'table' => 'users',
  173. 'schema' => [
  174. 'foo' => ['type' => 'string'],
  175. 'name' => ['type' => 'string']
  176. ]
  177. ]);
  178. $this->assertEquals('name', $table->displayField());
  179. }
  180. /**
  181. * Tests that title will be selected as a displayField
  182. *
  183. * @return void
  184. */
  185. public function testDisplayFieldTitle()
  186. {
  187. $table = new Table([
  188. 'table' => 'users',
  189. 'schema' => [
  190. 'foo' => ['type' => 'string'],
  191. 'title' => ['type' => 'string']
  192. ]
  193. ]);
  194. $this->assertEquals('title', $table->displayField());
  195. }
  196. /**
  197. * Tests that no displayField will fallback to primary key
  198. *
  199. * @return void
  200. */
  201. public function testDisplayFallback()
  202. {
  203. $table = new Table([
  204. 'table' => 'users',
  205. 'schema' => [
  206. 'id' => ['type' => 'string'],
  207. 'foo' => ['type' => 'string'],
  208. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  209. ]
  210. ]);
  211. $this->assertEquals('id', $table->displayField());
  212. }
  213. /**
  214. * Tests that displayField can be changed
  215. *
  216. * @return void
  217. */
  218. public function testDisplaySet()
  219. {
  220. $table = new Table([
  221. 'table' => 'users',
  222. 'schema' => [
  223. 'id' => ['type' => 'string'],
  224. 'foo' => ['type' => 'string'],
  225. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  226. ]
  227. ]);
  228. $this->assertEquals('id', $table->displayField());
  229. $table->displayField('foo');
  230. $this->assertEquals('foo', $table->displayField());
  231. }
  232. /**
  233. * Tests schema method
  234. *
  235. * @return void
  236. */
  237. public function testSchema()
  238. {
  239. $schema = $this->connection->schemaCollection()->describe('users');
  240. $table = new Table([
  241. 'table' => 'users',
  242. 'connection' => $this->connection,
  243. ]);
  244. $this->assertEquals($schema, $table->schema());
  245. $table = new Table(['table' => 'stuff']);
  246. $table->schema($schema);
  247. $this->assertSame($schema, $table->schema());
  248. $table = new Table(['table' => 'another']);
  249. $schema = ['id' => ['type' => 'integer']];
  250. $table->schema($schema);
  251. $this->assertEquals(
  252. new \Cake\Database\Schema\Table('another', $schema),
  253. $table->schema()
  254. );
  255. }
  256. /**
  257. * Tests that _initializeSchema can be used to alter the database schema
  258. *
  259. * @return void
  260. */
  261. public function testSchemaInitialize()
  262. {
  263. $schema = $this->connection->schemaCollection()->describe('users');
  264. $table = $this->getMock('Cake\ORM\Table', ['_initializeSchema'], [
  265. ['table' => 'users', 'connection' => $this->connection]
  266. ]);
  267. $table->expects($this->once())
  268. ->method('_initializeSchema')
  269. ->with($schema)
  270. ->will($this->returnCallback(function ($schema) {
  271. $schema->columnType('username', 'integer');
  272. return $schema;
  273. }));
  274. $result = $table->schema();
  275. $schema->columnType('username', 'integer');
  276. $this->assertEquals($schema, $result);
  277. $this->assertEquals($schema, $table->schema(), '_initializeSchema should be called once');
  278. }
  279. /**
  280. * Tests that all fields for a table are added by default in a find when no
  281. * other fields are specified
  282. *
  283. * @return void
  284. */
  285. public function testFindAllNoFieldsAndNoHydration()
  286. {
  287. $table = new Table([
  288. 'table' => 'users',
  289. 'connection' => $this->connection,
  290. ]);
  291. $results = $table
  292. ->find('all')
  293. ->where(['id IN' => [1, 2]])
  294. ->order('id')
  295. ->hydrate(false)
  296. ->toArray();
  297. $expected = [
  298. [
  299. 'id' => 1,
  300. 'username' => 'mariano',
  301. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  302. 'created' => new Time('2007-03-17 01:16:23'),
  303. 'updated' => new Time('2007-03-17 01:18:31'),
  304. ],
  305. [
  306. 'id' => 2,
  307. 'username' => 'nate',
  308. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  309. 'created' => new Time('2008-03-17 01:18:23'),
  310. 'updated' => new Time('2008-03-17 01:20:31'),
  311. ],
  312. ];
  313. $this->assertEquals($expected, $results);
  314. }
  315. /**
  316. * Tests that it is possible to select only a few fields when finding over a table
  317. *
  318. * @return void
  319. */
  320. public function testFindAllSomeFieldsNoHydration()
  321. {
  322. $table = new Table([
  323. 'table' => 'users',
  324. 'connection' => $this->connection,
  325. ]);
  326. $results = $table->find('all')
  327. ->select(['username', 'password'])
  328. ->hydrate(false)
  329. ->order('username')->toArray();
  330. $expected = [
  331. ['username' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  332. ['username' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  333. ['username' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  334. ['username' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  335. ];
  336. $this->assertSame($expected, $results);
  337. $results = $table->find('all')
  338. ->select(['foo' => 'username', 'password'])
  339. ->order('username')
  340. ->hydrate(false)
  341. ->toArray();
  342. $expected = [
  343. ['foo' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  344. ['foo' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  345. ['foo' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  346. ['foo' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  347. ];
  348. $this->assertSame($expected, $results);
  349. }
  350. /**
  351. * Tests that the query will automatically casts complex conditions to the correct
  352. * types when the columns belong to the default table
  353. *
  354. * @return void
  355. */
  356. public function testFindAllConditionAutoTypes()
  357. {
  358. $table = new Table([
  359. 'table' => 'users',
  360. 'connection' => $this->connection,
  361. ]);
  362. $query = $table->find('all')
  363. ->select(['id', 'username'])
  364. ->where(['created >=' => new Time('2010-01-22 00:00')])
  365. ->hydrate(false)
  366. ->order('id');
  367. $expected = [
  368. ['id' => 3, 'username' => 'larry'],
  369. ['id' => 4, 'username' => 'garrett']
  370. ];
  371. $this->assertSame($expected, $query->toArray());
  372. $query->orWhere(['users.created' => new Time('2008-03-17 01:18:23')]);
  373. $expected = [
  374. ['id' => 2, 'username' => 'nate'],
  375. ['id' => 3, 'username' => 'larry'],
  376. ['id' => 4, 'username' => 'garrett']
  377. ];
  378. $this->assertSame($expected, $query->toArray());
  379. }
  380. /**
  381. * Test that beforeFind events can mutate the query.
  382. *
  383. * @return void
  384. */
  385. public function testFindBeforeFindEventMutateQuery()
  386. {
  387. $table = new Table([
  388. 'table' => 'users',
  389. 'connection' => $this->connection,
  390. ]);
  391. $table->eventManager()->attach(function ($event, $query, $options) {
  392. $query->limit(1);
  393. }, 'Model.beforeFind');
  394. $result = $table->find('all')->all();
  395. $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
  396. }
  397. /**
  398. * Test that beforeFind events are fired and can stop the find and
  399. * return custom results.
  400. *
  401. * @return void
  402. */
  403. public function testFindBeforeFindEventOverrideReturn()
  404. {
  405. $table = new Table([
  406. 'table' => 'users',
  407. 'connection' => $this->connection,
  408. ]);
  409. $expected = ['One', 'Two', 'Three'];
  410. $table->eventManager()->attach(function ($event, $query, $options) use ($expected) {
  411. $query->setResult($expected);
  412. $event->stopPropagation();
  413. }, 'Model.beforeFind');
  414. $query = $table->find('all');
  415. $query->limit(1);
  416. $this->assertEquals($expected, $query->all()->toArray());
  417. }
  418. /**
  419. * Tests that belongsTo() creates and configures correctly the association
  420. *
  421. * @return void
  422. */
  423. public function testBelongsTo()
  424. {
  425. $options = ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']];
  426. $table = new Table(['table' => 'dates']);
  427. $belongsTo = $table->belongsTo('user', $options);
  428. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  429. $this->assertSame($belongsTo, $table->association('user'));
  430. $this->assertEquals('user', $belongsTo->name());
  431. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  432. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  433. $this->assertSame($table, $belongsTo->source());
  434. }
  435. /**
  436. * Tests that hasOne() creates and configures correctly the association
  437. *
  438. * @return void
  439. */
  440. public function testHasOne()
  441. {
  442. $options = ['foreignKey' => 'user_id', 'conditions' => ['b' => 'c']];
  443. $table = new Table(['table' => 'users']);
  444. $hasOne = $table->hasOne('profile', $options);
  445. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  446. $this->assertSame($hasOne, $table->association('profile'));
  447. $this->assertEquals('profile', $hasOne->name());
  448. $this->assertEquals('user_id', $hasOne->foreignKey());
  449. $this->assertEquals(['b' => 'c'], $hasOne->conditions());
  450. $this->assertSame($table, $hasOne->source());
  451. }
  452. /**
  453. * Tests that hasMany() creates and configures correctly the association
  454. *
  455. * @return void
  456. */
  457. public function testHasMany()
  458. {
  459. $options = [
  460. 'foreignKey' => 'author_id',
  461. 'conditions' => ['b' => 'c'],
  462. 'sort' => ['foo' => 'asc']
  463. ];
  464. $table = new Table(['table' => 'authors']);
  465. $hasMany = $table->hasMany('article', $options);
  466. $this->assertInstanceOf('Cake\ORM\Association\HasMany', $hasMany);
  467. $this->assertSame($hasMany, $table->association('article'));
  468. $this->assertEquals('article', $hasMany->name());
  469. $this->assertEquals('author_id', $hasMany->foreignKey());
  470. $this->assertEquals(['b' => 'c'], $hasMany->conditions());
  471. $this->assertEquals(['foo' => 'asc'], $hasMany->sort());
  472. $this->assertSame($table, $hasMany->source());
  473. }
  474. /**
  475. * Tests that BelongsToMany() creates and configures correctly the association
  476. *
  477. * @return void
  478. */
  479. public function testBelongsToMany()
  480. {
  481. $options = [
  482. 'foreignKey' => 'thing_id',
  483. 'joinTable' => 'things_tags',
  484. 'conditions' => ['b' => 'c'],
  485. 'sort' => ['foo' => 'asc']
  486. ];
  487. $table = new Table(['table' => 'authors', 'connection' => $this->connection]);
  488. $belongsToMany = $table->belongsToMany('tag', $options);
  489. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  490. $this->assertSame($belongsToMany, $table->association('tag'));
  491. $this->assertEquals('tag', $belongsToMany->name());
  492. $this->assertEquals('thing_id', $belongsToMany->foreignKey());
  493. $this->assertEquals(['b' => 'c'], $belongsToMany->conditions());
  494. $this->assertEquals(['foo' => 'asc'], $belongsToMany->sort());
  495. $this->assertSame($table, $belongsToMany->source());
  496. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  497. }
  498. /**
  499. * Test addAssociations()
  500. *
  501. * @return void
  502. */
  503. public function testAddAssociations()
  504. {
  505. $params = [
  506. 'belongsTo' => [
  507. 'users' => ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']]
  508. ],
  509. 'hasOne' => ['profiles'],
  510. 'hasMany' => ['authors'],
  511. 'belongsToMany' => [
  512. 'tags' => ['joinTable' => 'things_tags']
  513. ]
  514. ];
  515. $table = new Table(['table' => 'dates']);
  516. $table->addAssociations($params);
  517. $associations = $table->associations();
  518. $belongsTo = $associations->get('users');
  519. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  520. $this->assertEquals('users', $belongsTo->name());
  521. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  522. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  523. $this->assertSame($table, $belongsTo->source());
  524. $hasOne = $associations->get('profiles');
  525. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  526. $this->assertEquals('profiles', $hasOne->name());
  527. $hasMany = $associations->get('authors');
  528. $this->assertInstanceOf('Cake\ORM\Association\hasMany', $hasMany);
  529. $this->assertEquals('authors', $hasMany->name());
  530. $belongsToMany = $associations->get('tags');
  531. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  532. $this->assertEquals('tags', $belongsToMany->name());
  533. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  534. }
  535. /**
  536. * Test basic multi row updates.
  537. *
  538. * @return void
  539. */
  540. public function testUpdateAll()
  541. {
  542. $table = new Table([
  543. 'table' => 'users',
  544. 'connection' => $this->connection,
  545. ]);
  546. $fields = ['username' => 'mark'];
  547. $result = $table->updateAll($fields, ['id <' => 4]);
  548. $this->assertSame(3, $result);
  549. $result = $table->find('all')
  550. ->select(['username'])
  551. ->order(['id' => 'asc'])
  552. ->hydrate(false)
  553. ->toArray();
  554. $expected = array_fill(0, 3, $fields);
  555. $expected[] = ['username' => 'garrett'];
  556. $this->assertEquals($expected, $result);
  557. }
  558. /**
  559. * Test that exceptions from the Query bubble up.
  560. *
  561. * @expectedException \Cake\Database\Exception
  562. */
  563. public function testUpdateAllFailure()
  564. {
  565. $table = $this->getMock(
  566. 'Cake\ORM\Table',
  567. ['query'],
  568. [['table' => 'users', 'connection' => $this->connection]]
  569. );
  570. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  571. $table->expects($this->once())
  572. ->method('query')
  573. ->will($this->returnValue($query));
  574. $query->expects($this->once())
  575. ->method('execute')
  576. ->will($this->throwException(new \Cake\Database\Exception('Not good')));
  577. $table->updateAll(['username' => 'mark'], []);
  578. }
  579. /**
  580. * Test deleting many records.
  581. *
  582. * @return void
  583. */
  584. public function testDeleteAll()
  585. {
  586. $table = new Table([
  587. 'table' => 'users',
  588. 'connection' => $this->connection,
  589. ]);
  590. $result = $table->deleteAll(['id <' => 4]);
  591. $this->assertSame(3, $result);
  592. $result = $table->find('all')->toArray();
  593. $this->assertCount(1, $result, 'Only one record should remain');
  594. $this->assertEquals(4, $result[0]['id']);
  595. }
  596. /**
  597. * Test deleting many records with conditions using the alias
  598. *
  599. * @return void
  600. */
  601. public function testDeleteAllAliasedConditions()
  602. {
  603. $table = new Table([
  604. 'table' => 'users',
  605. 'alias' => 'Managers',
  606. 'connection' => $this->connection,
  607. ]);
  608. $result = $table->deleteAll(['Managers.id <' => 4]);
  609. $this->assertSame(3, $result);
  610. $result = $table->find('all')->toArray();
  611. $this->assertCount(1, $result, 'Only one record should remain');
  612. $this->assertEquals(4, $result[0]['id']);
  613. }
  614. /**
  615. * Test that exceptions from the Query bubble up.
  616. *
  617. * @expectedException \Cake\Database\Exception
  618. */
  619. public function testDeleteAllFailure()
  620. {
  621. $table = $this->getMock(
  622. 'Cake\ORM\Table',
  623. ['query'],
  624. [['table' => 'users', 'connection' => $this->connection]]
  625. );
  626. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  627. $table->expects($this->once())
  628. ->method('query')
  629. ->will($this->returnValue($query));
  630. $query->expects($this->once())
  631. ->method('execute')
  632. ->will($this->throwException(new \Cake\Database\Exception('Not good')));
  633. $table->deleteAll(['id >' => 4]);
  634. }
  635. /**
  636. * Tests that array options are passed to the query object using applyOptions
  637. *
  638. * @return void
  639. */
  640. public function testFindApplyOptions()
  641. {
  642. $table = $this->getMock(
  643. 'Cake\ORM\Table',
  644. ['query', 'findAll'],
  645. [['table' => 'users', 'connection' => $this->connection]]
  646. );
  647. $query = $this->getMock('Cake\ORM\Query', [], [$this->connection, $table]);
  648. $table->expects($this->once())
  649. ->method('query')
  650. ->will($this->returnValue($query));
  651. $options = ['fields' => ['a', 'b'], 'connections' => ['a >' => 1]];
  652. $query->expects($this->any())
  653. ->method('select')
  654. ->will($this->returnSelf());
  655. $query->expects($this->once())->method('getOptions')
  656. ->will($this->returnValue(['connections' => ['a >' => 1]]));
  657. $query->expects($this->once())
  658. ->method('applyOptions')
  659. ->with($options);
  660. $table->expects($this->once())->method('findAll')
  661. ->with($query, ['connections' => ['a >' => 1]]);
  662. $table->find('all', $options);
  663. }
  664. /**
  665. * Tests find('list')
  666. *
  667. * @return void
  668. */
  669. public function testFindListNoHydration()
  670. {
  671. $table = new Table([
  672. 'table' => 'users',
  673. 'connection' => $this->connection,
  674. ]);
  675. $table->displayField('username');
  676. $query = $table->find('list')
  677. ->hydrate(false)
  678. ->order('id');
  679. $expected = [
  680. 1 => 'mariano',
  681. 2 => 'nate',
  682. 3 => 'larry',
  683. 4 => 'garrett'
  684. ];
  685. $this->assertSame($expected, $query->toArray());
  686. $query = $table->find('list', ['fields' => ['id', 'username']])
  687. ->hydrate(false)
  688. ->order('id');
  689. $expected = [
  690. 1 => 'mariano',
  691. 2 => 'nate',
  692. 3 => 'larry',
  693. 4 => 'garrett'
  694. ];
  695. $this->assertSame($expected, $query->toArray());
  696. $query = $table->find('list', ['groupField' => 'odd'])
  697. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  698. ->hydrate(false)
  699. ->order('id');
  700. $expected = [
  701. 1 => [
  702. 1 => 'mariano',
  703. 3 => 'larry'
  704. ],
  705. 0 => [
  706. 2 => 'nate',
  707. 4 => 'garrett'
  708. ]
  709. ];
  710. $this->assertSame($expected, $query->toArray());
  711. }
  712. /**
  713. * Tests find('threaded')
  714. *
  715. * @return void
  716. */
  717. public function testFindThreadedNoHydration()
  718. {
  719. $table = new Table([
  720. 'table' => 'categories',
  721. 'connection' => $this->connection,
  722. ]);
  723. $expected = [
  724. [
  725. 'id' => 1,
  726. 'parent_id' => 0,
  727. 'name' => 'Category 1',
  728. 'children' => [
  729. [
  730. 'id' => 2,
  731. 'parent_id' => 1,
  732. 'name' => 'Category 1.1',
  733. 'children' => [
  734. [
  735. 'id' => 7,
  736. 'parent_id' => 2,
  737. 'name' => 'Category 1.1.1',
  738. 'children' => []
  739. ],
  740. [
  741. 'id' => 8,
  742. 'parent_id' => '2',
  743. 'name' => 'Category 1.1.2',
  744. 'children' => []
  745. ]
  746. ],
  747. ],
  748. [
  749. 'id' => 3,
  750. 'parent_id' => '1',
  751. 'name' => 'Category 1.2',
  752. 'children' => []
  753. ],
  754. ]
  755. ],
  756. [
  757. 'id' => 4,
  758. 'parent_id' => 0,
  759. 'name' => 'Category 2',
  760. 'children' => []
  761. ],
  762. [
  763. 'id' => 5,
  764. 'parent_id' => 0,
  765. 'name' => 'Category 3',
  766. 'children' => [
  767. [
  768. 'id' => '6',
  769. 'parent_id' => '5',
  770. 'name' => 'Category 3.1',
  771. 'children' => []
  772. ]
  773. ]
  774. ]
  775. ];
  776. $results = $table->find('all')
  777. ->select(['id', 'parent_id', 'name'])
  778. ->hydrate(false)
  779. ->find('threaded')
  780. ->toArray();
  781. $this->assertEquals($expected, $results);
  782. }
  783. /**
  784. * Tests that finders can be stacked
  785. *
  786. * @return void
  787. */
  788. public function testStackingFinders()
  789. {
  790. $table = $this->getMock('\Cake\ORM\Table', ['find', 'findList'], [], '', false);
  791. $params = [$this->connection, $table];
  792. $query = $this->getMock('\Cake\ORM\Query', ['addDefaultTypes'], $params);
  793. $table->expects($this->once())
  794. ->method('find')
  795. ->with('threaded', ['order' => ['name' => 'ASC']])
  796. ->will($this->returnValue($query));
  797. $table->expects($this->once())
  798. ->method('findList')
  799. ->with($query, ['keyPath' => 'id'])
  800. ->will($this->returnValue($query));
  801. $result = $table
  802. ->find('threaded', ['order' => ['name' => 'ASC']])
  803. ->find('list', ['keyPath' => 'id']);
  804. $this->assertSame($query, $result);
  805. }
  806. /**
  807. * Tests find('threaded') with hydrated results
  808. *
  809. * @return void
  810. */
  811. public function testFindThreadedHydrated()
  812. {
  813. $table = new Table([
  814. 'table' => 'categories',
  815. 'connection' => $this->connection,
  816. ]);
  817. $results = $table->find('all')
  818. ->find('threaded')
  819. ->select(['id', 'parent_id', 'name'])
  820. ->toArray();
  821. $this->assertEquals(1, $results[0]->id);
  822. $expected = [
  823. 'id' => 8,
  824. 'parent_id' => 2,
  825. 'name' => 'Category 1.1.2',
  826. 'children' => []
  827. ];
  828. $this->assertEquals($expected, $results[0]->children[0]->children[1]->toArray());
  829. }
  830. /**
  831. * Tests find('list') with hydrated records
  832. *
  833. * @return void
  834. */
  835. public function testFindListHydrated()
  836. {
  837. $table = new Table([
  838. 'table' => 'users',
  839. 'connection' => $this->connection,
  840. ]);
  841. $table->displayField('username');
  842. $query = $table
  843. ->find('list', ['fields' => ['id', 'username']])
  844. ->order('id');
  845. $expected = [
  846. 1 => 'mariano',
  847. 2 => 'nate',
  848. 3 => 'larry',
  849. 4 => 'garrett'
  850. ];
  851. $this->assertSame($expected, $query->toArray());
  852. $query = $table->find('list', ['groupField' => 'odd'])
  853. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  854. ->hydrate(true)
  855. ->order('id');
  856. $expected = [
  857. 1 => [
  858. 1 => 'mariano',
  859. 3 => 'larry'
  860. ],
  861. 0 => [
  862. 2 => 'nate',
  863. 4 => 'garrett'
  864. ]
  865. ];
  866. $this->assertSame($expected, $query->toArray());
  867. }
  868. /**
  869. * Test the default entityClass.
  870. *
  871. * @return void
  872. */
  873. public function testEntityClassDefault()
  874. {
  875. $table = new Table();
  876. $this->assertEquals('\Cake\ORM\Entity', $table->entityClass());
  877. }
  878. /**
  879. * Tests that using a simple string for entityClass will try to
  880. * load the class from the App namespace
  881. *
  882. * @return void
  883. */
  884. public function testTableClassInApp()
  885. {
  886. $class = $this->getMockClass('\Cake\ORM\Entity');
  887. if (!class_exists('TestApp\Model\Entity\TestUser')) {
  888. class_alias($class, 'TestApp\Model\Entity\TestUser');
  889. }
  890. $table = new Table();
  891. $this->assertEquals('TestApp\Model\Entity\TestUser', $table->entityClass('TestUser'));
  892. }
  893. /**
  894. * Tests that using a simple string for entityClass will try to
  895. * load the class from the Plugin namespace when using plugin notation
  896. *
  897. * @return void
  898. */
  899. public function testTableClassInPlugin()
  900. {
  901. $class = $this->getMockClass('\Cake\ORM\Entity');
  902. if (!class_exists('MyPlugin\Model\Entity\SuperUser')) {
  903. class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
  904. }
  905. $table = new Table();
  906. $this->assertEquals(
  907. 'MyPlugin\Model\Entity\SuperUser',
  908. $table->entityClass('MyPlugin.SuperUser')
  909. );
  910. }
  911. /**
  912. * Tests that using a simple string for entityClass will throw an exception
  913. * when the class does not exist in the namespace
  914. *
  915. * @expectedException \Cake\ORM\Exception\MissingEntityException
  916. * @expectedExceptionMessage Entity class FooUser could not be found.
  917. * @return void
  918. */
  919. public function testTableClassNonExisting()
  920. {
  921. $table = new Table;
  922. $this->assertFalse($table->entityClass('FooUser'));
  923. }
  924. /**
  925. * Tests getting the entityClass based on conventions for the entity
  926. * namespace
  927. *
  928. * @return void
  929. */
  930. public function testTableClassConventionForAPP()
  931. {
  932. $table = new \TestApp\Model\Table\ArticlesTable;
  933. $this->assertEquals('TestApp\Model\Entity\Article', $table->entityClass());
  934. }
  935. /**
  936. * Tests setting a entity class object using the setter method
  937. *
  938. * @return void
  939. */
  940. public function testSetEntityClass()
  941. {
  942. $table = new Table;
  943. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  944. $table->entityClass($class);
  945. $this->assertEquals($class, $table->entityClass());
  946. }
  947. /**
  948. * Proves that associations, even though they are lazy loaded, will fetch
  949. * records using the correct table class and hydrate with the correct entity
  950. *
  951. * @return void
  952. */
  953. public function testReciprocalBelongsToLoading()
  954. {
  955. $table = new \TestApp\Model\Table\ArticlesTable([
  956. 'connection' => $this->connection,
  957. ]);
  958. $result = $table->find('all')->contain(['authors'])->first();
  959. $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author);
  960. }
  961. /**
  962. * Proves that associations, even though they are lazy loaded, will fetch
  963. * records using the correct table class and hydrate with the correct entity
  964. *
  965. * @return void
  966. */
  967. public function testReciprocalHasManyLoading()
  968. {
  969. $table = new \TestApp\Model\Table\ArticlesTable([
  970. 'connection' => $this->connection,
  971. ]);
  972. $result = $table->find('all')->contain(['authors' => ['articles']])->first();
  973. $this->assertCount(2, $result->author->articles);
  974. foreach ($result->author->articles as $article) {
  975. $this->assertInstanceOf('TestApp\Model\Entity\Article', $article);
  976. }
  977. }
  978. /**
  979. * Tests that the correct table and entity are loaded for the join association in
  980. * a belongsToMany setup
  981. *
  982. * @return void
  983. */
  984. public function testReciprocalBelongsToMany()
  985. {
  986. $table = new \TestApp\Model\Table\ArticlesTable([
  987. 'connection' => $this->connection,
  988. ]);
  989. $result = $table->find('all')->contain(['tags'])->first();
  990. $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]);
  991. $this->assertInstanceOf(
  992. 'TestApp\Model\Entity\ArticlesTag',
  993. $result->tags[0]->_joinData
  994. );
  995. }
  996. /**
  997. * Tests that recently fetched entities are always clean
  998. *
  999. * @return void
  1000. */
  1001. public function testFindCleanEntities()
  1002. {
  1003. $table = new \TestApp\Model\Table\ArticlesTable([
  1004. 'connection' => $this->connection,
  1005. ]);
  1006. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1007. $this->assertCount(3, $results);
  1008. foreach ($results as $article) {
  1009. $this->assertFalse($article->dirty('id'));
  1010. $this->assertFalse($article->dirty('title'));
  1011. $this->assertFalse($article->dirty('author_id'));
  1012. $this->assertFalse($article->dirty('body'));
  1013. $this->assertFalse($article->dirty('published'));
  1014. $this->assertFalse($article->dirty('author'));
  1015. $this->assertFalse($article->author->dirty('id'));
  1016. $this->assertFalse($article->author->dirty('name'));
  1017. $this->assertFalse($article->dirty('tag'));
  1018. if ($article->tag) {
  1019. $this->assertFalse($article->tag[0]->_joinData->dirty('tag_id'));
  1020. }
  1021. }
  1022. }
  1023. /**
  1024. * Tests that recently fetched entities are marked as not new
  1025. *
  1026. * @return void
  1027. */
  1028. public function testFindPersistedEntities()
  1029. {
  1030. $table = new \TestApp\Model\Table\ArticlesTable([
  1031. 'connection' => $this->connection,
  1032. ]);
  1033. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1034. $this->assertCount(3, $results);
  1035. foreach ($results as $article) {
  1036. $this->assertFalse($article->isNew());
  1037. foreach ((array)$article->tag as $tag) {
  1038. $this->assertFalse($tag->isNew());
  1039. $this->assertFalse($tag->_joinData->isNew());
  1040. }
  1041. }
  1042. }
  1043. /**
  1044. * Tests the exists function
  1045. *
  1046. * @return void
  1047. */
  1048. public function testExists()
  1049. {
  1050. $table = TableRegistry::get('users');
  1051. $this->assertTrue($table->exists(['id' => 1]));
  1052. $this->assertFalse($table->exists(['id' => 501]));
  1053. $this->assertTrue($table->exists(['id' => 3, 'username' => 'larry']));
  1054. }
  1055. /**
  1056. * Test adding a behavior to a table.
  1057. *
  1058. * @return void
  1059. */
  1060. public function testAddBehavior()
  1061. {
  1062. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1063. $mock->expects($this->once())
  1064. ->method('load')
  1065. ->with('Sluggable');
  1066. $table = new Table([
  1067. 'table' => 'articles',
  1068. 'behaviors' => $mock
  1069. ]);
  1070. $table->addBehavior('Sluggable');
  1071. }
  1072. /**
  1073. * Test adding a behavior that is a duplicate.
  1074. *
  1075. * @return void
  1076. */
  1077. public function testAddBehaviorDuplicate()
  1078. {
  1079. $table = new Table(['table' => 'articles']);
  1080. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1081. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1082. try {
  1083. $table->addBehavior('Sluggable', ['thing' => 'thing']);
  1084. $this->fail('No exception raised');
  1085. } catch (\RuntimeException $e) {
  1086. $this->assertContains('The "Sluggable" alias has already been loaded', $e->getMessage());
  1087. }
  1088. }
  1089. /**
  1090. * Test removing a behavior from a table.
  1091. *
  1092. * @return void
  1093. */
  1094. public function testRemoveBehavior()
  1095. {
  1096. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1097. $mock->expects($this->once())
  1098. ->method('unload')
  1099. ->with('Sluggable');
  1100. $table = new Table([
  1101. 'table' => 'articles',
  1102. 'behaviors' => $mock
  1103. ]);
  1104. $table->removeBehavior('Sluggable');
  1105. }
  1106. /**
  1107. * Test getting a behavior instance from a table.
  1108. *
  1109. * @return void
  1110. */
  1111. public function testBehaviors()
  1112. {
  1113. $table = TableRegistry::get('article');
  1114. $result = $table->behaviors();
  1115. $this->assertInstanceOf('Cake\ORM\BehaviorRegistry', $result);
  1116. }
  1117. /**
  1118. * Ensure exceptions are raised on missing behaviors.
  1119. *
  1120. * @expectedException \Cake\ORM\Exception\MissingBehaviorException
  1121. */
  1122. public function testAddBehaviorMissing()
  1123. {
  1124. $table = TableRegistry::get('article');
  1125. $this->assertNull($table->addBehavior('NopeNotThere'));
  1126. }
  1127. /**
  1128. * Test mixin methods from behaviors.
  1129. *
  1130. * @return void
  1131. */
  1132. public function testCallBehaviorMethod()
  1133. {
  1134. $table = TableRegistry::get('article');
  1135. $table->addBehavior('Sluggable');
  1136. $this->assertEquals('some-value', $table->slugify('some value'));
  1137. }
  1138. /**
  1139. * Test you can alias a behavior method
  1140. *
  1141. * @return void
  1142. */
  1143. public function testCallBehaviorAliasedMethod()
  1144. {
  1145. $table = TableRegistry::get('article');
  1146. $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
  1147. $this->assertEquals('some-value', $table->wednesday('some value'));
  1148. }
  1149. /**
  1150. * Test finder methods from behaviors.
  1151. *
  1152. * @return void
  1153. */
  1154. public function testCallBehaviorFinder()
  1155. {
  1156. $table = TableRegistry::get('articles');
  1157. $table->addBehavior('Sluggable');
  1158. $query = $table->find('noSlug');
  1159. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1160. $this->assertNotEmpty($query->clause('where'));
  1161. }
  1162. /**
  1163. * testCallBehaviorAliasedFinder
  1164. *
  1165. * @return void
  1166. */
  1167. public function testCallBehaviorAliasedFinder()
  1168. {
  1169. $table = TableRegistry::get('articles');
  1170. $table->addBehavior('Sluggable', ['implementedFinders' => ['special' => 'findNoSlug']]);
  1171. $query = $table->find('special');
  1172. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1173. $this->assertNotEmpty($query->clause('where'));
  1174. }
  1175. /**
  1176. * Test implementedEvents
  1177. *
  1178. * @return void
  1179. */
  1180. public function testImplementedEvents()
  1181. {
  1182. $table = $this->getMock(
  1183. 'Cake\ORM\Table',
  1184. ['beforeFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete']
  1185. );
  1186. $result = $table->implementedEvents();
  1187. $expected = [
  1188. 'Model.beforeFind' => 'beforeFind',
  1189. 'Model.beforeSave' => 'beforeSave',
  1190. 'Model.afterSave' => 'afterSave',
  1191. 'Model.beforeDelete' => 'beforeDelete',
  1192. 'Model.afterDelete' => 'afterDelete',
  1193. ];
  1194. $this->assertEquals($expected, $result, 'Events do not match.');
  1195. }
  1196. /**
  1197. * Tests that it is possible to insert a new row using the save method
  1198. *
  1199. * @group save
  1200. * @return void
  1201. */
  1202. public function testSaveNewEntity()
  1203. {
  1204. $entity = new \Cake\ORM\Entity([
  1205. 'username' => 'superuser',
  1206. 'password' => 'root',
  1207. 'created' => new Time('2013-10-10 00:00'),
  1208. 'updated' => new Time('2013-10-10 00:00')
  1209. ]);
  1210. $table = TableRegistry::get('users');
  1211. $this->assertSame($entity, $table->save($entity));
  1212. $this->assertEquals($entity->id, self::$nextUserId);
  1213. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1214. $this->assertEquals($entity->toArray(), $row->toArray());
  1215. }
  1216. /**
  1217. * Test that saving a new empty entity does nothing.
  1218. *
  1219. * @group save
  1220. * @return void
  1221. */
  1222. public function testSaveNewEmptyEntity()
  1223. {
  1224. $entity = new \Cake\ORM\Entity();
  1225. $table = TableRegistry::get('users');
  1226. $this->assertFalse($table->save($entity));
  1227. }
  1228. /**
  1229. * Test that saving a new empty entity does not call exists.
  1230. *
  1231. * @group save
  1232. * @return void
  1233. */
  1234. public function testSaveNewEntityNoExists()
  1235. {
  1236. $table = $this->getMock(
  1237. 'Cake\ORM\Table',
  1238. ['exists'],
  1239. [[
  1240. 'connection' => $this->connection,
  1241. 'alias' => 'Users',
  1242. 'table' => 'users',
  1243. ]]
  1244. );
  1245. $entity = $table->newEntity(['username' => 'mark']);
  1246. $this->assertTrue($entity->isNew());
  1247. $table->expects($this->never())
  1248. ->method('exists');
  1249. $this->assertSame($entity, $table->save($entity));
  1250. }
  1251. /**
  1252. * Tests that saving an entity will filter out properties that
  1253. * are not present in the table schema when saving
  1254. *
  1255. * @group save
  1256. * @return void
  1257. */
  1258. public function testSaveEntityOnlySchemaFields()
  1259. {
  1260. $entity = new \Cake\ORM\Entity([
  1261. 'username' => 'superuser',
  1262. 'password' => 'root',
  1263. 'crazyness' => 'super crazy value',
  1264. 'created' => new Time('2013-10-10 00:00'),
  1265. 'updated' => new Time('2013-10-10 00:00'),
  1266. ]);
  1267. $table = TableRegistry::get('users');
  1268. $this->assertSame($entity, $table->save($entity));
  1269. $this->assertEquals($entity->id, self::$nextUserId);
  1270. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1271. $entity->unsetProperty('crazyness');
  1272. $this->assertEquals($entity->toArray(), $row->toArray());
  1273. }
  1274. /**
  1275. * Tests that it is possible to modify data from the beforeSave callback
  1276. *
  1277. * @group save
  1278. * @return void
  1279. */
  1280. public function testBeforeSaveModifyData()
  1281. {
  1282. $table = TableRegistry::get('users');
  1283. $data = new \Cake\ORM\Entity([
  1284. 'username' => 'superuser',
  1285. 'created' => new Time('2013-10-10 00:00'),
  1286. 'updated' => new Time('2013-10-10 00:00')
  1287. ]);
  1288. $listener = function ($e, $entity, $options) use ($data) {
  1289. $this->assertSame($data, $entity);
  1290. $entity->set('password', 'foo');
  1291. };
  1292. $table->eventManager()->attach($listener, 'Model.beforeSave');
  1293. $this->assertSame($data, $table->save($data));
  1294. $this->assertEquals($data->id, self::$nextUserId);
  1295. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1296. $this->assertEquals('foo', $row->get('password'));
  1297. }
  1298. /**
  1299. * Tests that it is possible to modify the options array in beforeSave
  1300. *
  1301. * @group save
  1302. * @return void
  1303. */
  1304. public function testBeforeSaveModifyOptions()
  1305. {
  1306. $table = TableRegistry::get('users');
  1307. $data = new \Cake\ORM\Entity([
  1308. 'username' => 'superuser',
  1309. 'password' => 'foo',
  1310. 'created' => new Time('2013-10-10 00:00'),
  1311. 'updated' => new Time('2013-10-10 00:00')
  1312. ]);
  1313. $listener1 = function ($e, $entity, $options) {
  1314. $options['crazy'] = true;
  1315. };
  1316. $listener2 = function ($e, $entity, $options) {
  1317. $this->assertTrue($options['crazy']);
  1318. };
  1319. $table->eventManager()->attach($listener1, 'Model.beforeSave');
  1320. $table->eventManager()->attach($listener2, 'Model.beforeSave');
  1321. $this->assertSame($data, $table->save($data));
  1322. $this->assertEquals($data->id, self::$nextUserId);
  1323. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1324. $this->assertEquals($data->toArray(), $row->toArray());
  1325. }
  1326. /**
  1327. * Tests that it is possible to stop the saving altogether, without implying
  1328. * the save operation failed
  1329. *
  1330. * @group save
  1331. * @return void
  1332. */
  1333. public function testBeforeSaveStopEvent()
  1334. {
  1335. $table = TableRegistry::get('users');
  1336. $data = new \Cake\ORM\Entity([
  1337. 'username' => 'superuser',
  1338. 'created' => new Time('2013-10-10 00:00'),
  1339. 'updated' => new Time('2013-10-10 00:00')
  1340. ]);
  1341. $listener = function ($e, $entity) {
  1342. $e->stopPropagation();
  1343. return $entity;
  1344. };
  1345. $table->eventManager()->attach($listener, 'Model.beforeSave');
  1346. $this->assertSame($data, $table->save($data));
  1347. $this->assertNull($data->id);
  1348. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1349. $this->assertNull($row);
  1350. }
  1351. /**
  1352. * Asserts that afterSave callback is called on successful save
  1353. *
  1354. * @group save
  1355. * @return void
  1356. */
  1357. public function testAfterSave()
  1358. {
  1359. $table = TableRegistry::get('users');
  1360. $data = new \Cake\ORM\Entity([
  1361. 'username' => 'superuser',
  1362. 'created' => new Time('2013-10-10 00:00'),
  1363. 'updated' => new Time('2013-10-10 00:00')
  1364. ]);
  1365. $called = false;
  1366. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1367. $this->assertSame($data, $entity);
  1368. $called = true;
  1369. };
  1370. $table->eventManager()->attach($listener, 'Model.afterSave');
  1371. $this->assertSame($data, $table->save($data));
  1372. $this->assertEquals($data->id, self::$nextUserId);
  1373. $this->assertTrue($called);
  1374. }
  1375. /**
  1376. * Asserts that afterSave callback not is called on unsuccessful save
  1377. *
  1378. * @group save
  1379. * @return void
  1380. */
  1381. public function testAfterSaveNotCalled()
  1382. {
  1383. $table = $this->getMock(
  1384. '\Cake\ORM\Table',
  1385. ['query'],
  1386. [['table' => 'users', 'connection' => $this->connection]]
  1387. );
  1388. $query = $this->getMock(
  1389. '\Cake\ORM\Query',
  1390. ['execute', 'addDefaultTypes'],
  1391. [null, $table]
  1392. );
  1393. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1394. $data = new \Cake\ORM\Entity([
  1395. 'username' => 'superuser',
  1396. 'created' => new Time('2013-10-10 00:00'),
  1397. 'updated' => new Time('2013-10-10 00:00')
  1398. ]);
  1399. $table->expects($this->once())->method('query')
  1400. ->will($this->returnValue($query));
  1401. $query->expects($this->once())->method('execute')
  1402. ->will($this->returnValue($statement));
  1403. $statement->expects($this->once())->method('rowCount')
  1404. ->will($this->returnValue(0));
  1405. $called = false;
  1406. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1407. $called = true;
  1408. };
  1409. $table->eventManager()->attach($listener, 'Model.afterSave');
  1410. $this->assertFalse($table->save($data));
  1411. $this->assertFalse($called);
  1412. }
  1413. /**
  1414. * Test that you cannot save rows without a primary key.
  1415. *
  1416. * @group save
  1417. * @expectedException \RuntimeException
  1418. * @expectedExceptionMessage Cannot insert row in "users" table, it has no primary key
  1419. * @return void
  1420. */
  1421. public function testSaveNewErrorOnNoPrimaryKey()
  1422. {
  1423. $entity = new \Cake\ORM\Entity(['username' => 'superuser']);
  1424. $table = TableRegistry::get('users', [
  1425. 'schema' => [
  1426. 'id' => ['type' => 'integer'],
  1427. 'username' => ['type' => 'string'],
  1428. ]
  1429. ]);
  1430. $table->save($entity);
  1431. }
  1432. /**
  1433. * Tests that save is wrapped around a transaction
  1434. *
  1435. * @group save
  1436. * @return void
  1437. */
  1438. public function testAtomicSave()
  1439. {
  1440. $config = ConnectionManager::config('test');
  1441. $connection = $this->getMock(
  1442. '\Cake\Database\Connection',
  1443. ['begin', 'commit'],
  1444. [$config]
  1445. );
  1446. $connection->driver($this->connection->driver());
  1447. $table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
  1448. $table->expects($this->any())->method('connection')
  1449. ->will($this->returnValue($connection));
  1450. $connection->expects($this->once())->method('begin');
  1451. $connection->expects($this->once())->method('commit');
  1452. $data = new \Cake\ORM\Entity([
  1453. 'username' => 'superuser',
  1454. 'created' => new Time('2013-10-10 00:00'),
  1455. 'updated' => new Time('2013-10-10 00:00')
  1456. ]);
  1457. $this->assertSame($data, $table->save($data));
  1458. }
  1459. /**
  1460. * Tests that save will rollback the transaction in the case of an exception
  1461. *
  1462. * @group save
  1463. * @expectedException \PDOException
  1464. * @return void
  1465. */
  1466. public function testAtomicSaveRollback()
  1467. {
  1468. $connection = $this->getMock(
  1469. '\Cake\Database\Connection',
  1470. ['begin', 'rollback'],
  1471. [ConnectionManager::config('test')]
  1472. );
  1473. $connection->driver(ConnectionManager::get('test')->driver());
  1474. $table = $this->getMock(
  1475. '\Cake\ORM\Table',
  1476. ['query', 'connection'],
  1477. [['table' => 'users']]
  1478. );
  1479. $query = $this->getMock(
  1480. '\Cake\ORM\Query',
  1481. ['execute', 'addDefaultTypes'],
  1482. [null, $table]
  1483. );
  1484. $table->expects($this->any())->method('connection')
  1485. ->will($this->returnValue($connection));
  1486. $table->expects($this->once())->method('query')
  1487. ->will($this->returnValue($query));
  1488. $connection->expects($this->once())->method('begin');
  1489. $connection->expects($this->once())->method('rollback');
  1490. $query->expects($this->once())->method('execute')
  1491. ->will($this->throwException(new \PDOException));
  1492. $data = new \Cake\ORM\Entity([
  1493. 'username' => 'superuser',
  1494. 'created' => new Time('2013-10-10 00:00'),
  1495. 'updated' => new Time('2013-10-10 00:00')
  1496. ]);
  1497. $table->save($data);
  1498. }
  1499. /**
  1500. * Tests that save will rollback the transaction in the case of an exception
  1501. *
  1502. * @group save
  1503. * @return void
  1504. */
  1505. public function testAtomicSaveRollbackOnFailure()
  1506. {
  1507. $connection = $this->getMock(
  1508. '\Cake\Database\Connection',
  1509. ['begin', 'rollback'],
  1510. [ConnectionManager::config('test')]
  1511. );
  1512. $connection->driver(ConnectionManager::get('test')->driver());
  1513. $table = $this->getMock(
  1514. '\Cake\ORM\Table',
  1515. ['query', 'connection', 'exists'],
  1516. [['table' => 'users']]
  1517. );
  1518. $query = $this->getMock(
  1519. '\Cake\ORM\Query',
  1520. ['execute', 'addDefaultTypes'],
  1521. [null, $table]
  1522. );
  1523. $table->expects($this->any())->method('connection')
  1524. ->will($this->returnValue($connection));
  1525. $table->expects($this->once())->method('query')
  1526. ->will($this->returnValue($query));
  1527. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1528. $statement->expects($this->once())
  1529. ->method('rowCount')
  1530. ->will($this->returnValue(0));
  1531. $connection->expects($this->once())->method('begin');
  1532. $connection->expects($this->once())->method('rollback');
  1533. $query->expects($this->once())
  1534. ->method('execute')
  1535. ->will($this->returnValue($statement));
  1536. $data = new \Cake\ORM\Entity([
  1537. 'username' => 'superuser',
  1538. 'created' => new Time('2013-10-10 00:00'),
  1539. 'updated' => new Time('2013-10-10 00:00')
  1540. ]);
  1541. $table->save($data);
  1542. }
  1543. /**
  1544. * Tests that only the properties marked as dirty are actually saved
  1545. * to the database
  1546. *
  1547. * @group save
  1548. * @return void
  1549. */
  1550. public function testSaveOnlyDirtyProperties()
  1551. {
  1552. $entity = new \Cake\ORM\Entity([
  1553. 'username' => 'superuser',
  1554. 'password' => 'root',
  1555. 'created' => new Time('2013-10-10 00:00'),
  1556. 'updated' => new Time('2013-10-10 00:00')
  1557. ]);
  1558. $entity->clean();
  1559. $entity->dirty('username', true);
  1560. $entity->dirty('created', true);
  1561. $entity->dirty('updated', true);
  1562. $table = TableRegistry::get('users');
  1563. $this->assertSame($entity, $table->save($entity));
  1564. $this->assertEquals($entity->id, self::$nextUserId);
  1565. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1566. $entity->set('password', null);
  1567. $this->assertEquals($entity->toArray(), $row->toArray());
  1568. }
  1569. /**
  1570. * Tests that a recently saved entity is marked as clean
  1571. *
  1572. * @group save
  1573. * @return void
  1574. */
  1575. public function testASavedEntityIsClean()
  1576. {
  1577. $entity = new \Cake\ORM\Entity([
  1578. 'username' => 'superuser',
  1579. 'password' => 'root',
  1580. 'created' => new Time('2013-10-10 00:00'),
  1581. 'updated' => new Time('2013-10-10 00:00')
  1582. ]);
  1583. $table = TableRegistry::get('users');
  1584. $this->assertSame($entity, $table->save($entity));
  1585. $this->assertFalse($entity->dirty('usermane'));
  1586. $this->assertFalse($entity->dirty('password'));
  1587. $this->assertFalse($entity->dirty('created'));
  1588. $this->assertFalse($entity->dirty('updated'));
  1589. }
  1590. /**
  1591. * Tests that a recently saved entity is marked as not new
  1592. *
  1593. * @group save
  1594. * @return void
  1595. */
  1596. public function testASavedEntityIsNotNew()
  1597. {
  1598. $entity = new \Cake\ORM\Entity([
  1599. 'username' => 'superuser',
  1600. 'password' => 'root',
  1601. 'created' => new Time('2013-10-10 00:00'),
  1602. 'updated' => new Time('2013-10-10 00:00')
  1603. ]);
  1604. $table = TableRegistry::get('users');
  1605. $this->assertSame($entity, $table->save($entity));
  1606. $this->assertFalse($entity->isNew());
  1607. }
  1608. /**
  1609. * Tests that save can detect automatically if it needs to insert
  1610. * or update a row
  1611. *
  1612. * @group save
  1613. * @return void
  1614. */
  1615. public function testSaveUpdateAuto()
  1616. {
  1617. $entity = new \Cake\ORM\Entity([
  1618. 'id' => 2,
  1619. 'username' => 'baggins'
  1620. ]);
  1621. $table = TableRegistry::get('users');
  1622. $original = $table->find('all')->where(['id' => 2])->first();
  1623. $this->assertSame($entity, $table->save($entity));
  1624. $row = $table->find('all')->where(['id' => 2])->first();
  1625. $this->assertEquals('baggins', $row->username);
  1626. $this->assertEquals($original->password, $row->password);
  1627. $this->assertEquals($original->created, $row->created);
  1628. $this->assertEquals($original->updated, $row->updated);
  1629. $this->assertFalse($entity->isNew());
  1630. $this->assertFalse($entity->dirty('id'));
  1631. $this->assertFalse($entity->dirty('username'));
  1632. }
  1633. /**
  1634. * Tests that beforeFind gets the correct isNew() state for the entity
  1635. *
  1636. * @return void
  1637. */
  1638. public function testBeforeSaveGetsCorrectPersistance()
  1639. {
  1640. $entity = new \Cake\ORM\Entity([
  1641. 'id' => 2,
  1642. 'username' => 'baggins'
  1643. ]);
  1644. $table = TableRegistry::get('users');
  1645. $called = false;
  1646. $listener = function ($event, $entity) use (&$called) {
  1647. $this->assertFalse($entity->isNew());
  1648. $called = true;
  1649. };
  1650. $table->eventManager()->attach($listener, 'Model.beforeSave');
  1651. $this->assertSame($entity, $table->save($entity));
  1652. $this->assertTrue($called);
  1653. }
  1654. /**
  1655. * Tests that marking an entity as already persisted will prevent the save
  1656. * method from trying to infer the entity's actual status.
  1657. *
  1658. * @group save
  1659. * @return void
  1660. */
  1661. public function testSaveUpdateWithHint()
  1662. {
  1663. $table = $this->getMock(
  1664. '\Cake\ORM\Table',
  1665. ['exists'],
  1666. [['table' => 'users', 'connection' => ConnectionManager::get('test')]]
  1667. );
  1668. $entity = new \Cake\ORM\Entity([
  1669. 'id' => 2,
  1670. 'username' => 'baggins'
  1671. ], ['markNew' => false]);
  1672. $this->assertFalse($entity->isNew());
  1673. $table->expects($this->never())->method('exists');
  1674. $this->assertSame($entity, $table->save($entity));
  1675. }
  1676. /**
  1677. * Tests that when updating the primary key is not passed to the list of
  1678. * attributes to change
  1679. *
  1680. * @group save
  1681. * @return void
  1682. */
  1683. public function testSaveUpdatePrimaryKeyNotModified()
  1684. {
  1685. $table = $this->getMock(
  1686. '\Cake\ORM\Table',
  1687. ['query'],
  1688. [['table' => 'users', 'connection' => $this->connection]]
  1689. );
  1690. $query = $this->getMock(
  1691. '\Cake\ORM\Query',
  1692. ['execute', 'addDefaultTypes', 'set'],
  1693. [null, $table]
  1694. );
  1695. $table->expects($this->once())->method('query')
  1696. ->will($this->returnValue($query));
  1697. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1698. $statement->expects($this->once())
  1699. ->method('errorCode')
  1700. ->will($this->returnValue('00000'));
  1701. $query->expects($this->once())
  1702. ->method('execute')
  1703. ->will($this->returnValue($statement));
  1704. $query->expects($this->once())->method('set')
  1705. ->with(['username' => 'baggins'])
  1706. ->will($this->returnValue($query));
  1707. $entity = new \Cake\ORM\Entity([
  1708. 'id' => 2,
  1709. 'username' => 'baggins'
  1710. ], ['markNew' => false]);
  1711. $this->assertSame($entity, $table->save($entity));
  1712. }
  1713. /**
  1714. * Tests that passing only the primary key to save will not execute any queries
  1715. * but still return success
  1716. *
  1717. * @group save
  1718. * @return void
  1719. */
  1720. public function testUpdateNoChange()
  1721. {
  1722. $table = $this->getMock(
  1723. '\Cake\ORM\Table',
  1724. ['query'],
  1725. [['table' => 'users', 'connection' => $this->connection]]
  1726. );
  1727. $table->expects($this->never())->method('query');
  1728. $entity = new \Cake\ORM\Entity([
  1729. 'id' => 2,
  1730. ], ['markNew' => false]);
  1731. $this->assertSame($entity, $table->save($entity));
  1732. }
  1733. /**
  1734. * Tests that passing only the primary key to save will not execute any queries
  1735. * but still return success
  1736. *
  1737. * @group save
  1738. * @group integration
  1739. * @return void
  1740. */
  1741. public function testUpdateDirtyNoActualChanges()
  1742. {
  1743. $table = TableRegistry::get('Articles');
  1744. $entity = $table->get(1);
  1745. $entity->accessible('*', true);
  1746. $entity->set($entity->toArray());
  1747. $this->assertSame($entity, $table->save($entity));
  1748. }
  1749. /**
  1750. * Tests that failing to pass a primary key to save will result in exception
  1751. *
  1752. * @group save
  1753. * @expectedException \InvalidArgumentException
  1754. * @return void
  1755. */
  1756. public function testUpdateNoPrimaryButOtherKeys()
  1757. {
  1758. $table = $this->getMock(
  1759. '\Cake\ORM\Table',
  1760. ['query'],
  1761. [['table' => 'users', 'connection' => $this->connection]]
  1762. );
  1763. $table->expects($this->never())->method('query');
  1764. $entity = new \Cake\ORM\Entity([
  1765. 'username' => 'mariano',
  1766. ], ['markNew' => false]);
  1767. $this->assertSame($entity, $table->save($entity));
  1768. }
  1769. /**
  1770. * Test simple delete.
  1771. *
  1772. * @return void
  1773. */
  1774. public function testDelete()
  1775. {
  1776. $table = TableRegistry::get('users');
  1777. $conditions = [
  1778. 'limit' => 1,
  1779. 'conditions' => [
  1780. 'username' => 'nate'
  1781. ]
  1782. ];
  1783. $query = $table->find('all', $conditions);
  1784. $entity = $query->first();
  1785. $result = $table->delete($entity);
  1786. $this->assertTrue($result);
  1787. $query = $table->find('all', $conditions);
  1788. $results = $query->execute();
  1789. $this->assertCount(0, $results, 'Find should fail.');
  1790. }
  1791. /**
  1792. * Test delete with dependent records
  1793. *
  1794. * @return void
  1795. */
  1796. public function testDeleteDependent()
  1797. {
  1798. $table = TableRegistry::get('authors');
  1799. $table->hasOne('articles', [
  1800. 'foreignKey' => 'author_id',
  1801. 'dependent' => true,
  1802. ]);
  1803. $query = $table->find('all')->where(['id' => 1]);
  1804. $entity = $query->first();
  1805. $result = $table->delete($entity);
  1806. $articles = $table->association('articles')->target();
  1807. $query = $articles->find('all', [
  1808. 'conditions' => [
  1809. 'author_id' => $entity->id
  1810. ]
  1811. ]);
  1812. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  1813. }
  1814. /**
  1815. * Test delete with dependent = false does not cascade.
  1816. *
  1817. * @return void
  1818. */
  1819. public function testDeleteNoDependentNoCascade()
  1820. {
  1821. $table = TableRegistry::get('authors');
  1822. $table->hasMany('article', [
  1823. 'foreignKey' => 'author_id',
  1824. 'dependent' => false,
  1825. ]);
  1826. $query = $table->find('all')->where(['id' => 1]);
  1827. $entity = $query->first();
  1828. $result = $table->delete($entity);
  1829. $articles = $table->association('articles')->target();
  1830. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  1831. $this->assertCount(2, $query->execute(), 'Should find rows.');
  1832. }
  1833. /**
  1834. * Test delete with BelongsToMany
  1835. *
  1836. * @return void
  1837. */
  1838. public function testDeleteBelongsToMany()
  1839. {
  1840. $table = TableRegistry::get('articles');
  1841. $table->belongsToMany('tag', [
  1842. 'foreignKey' => 'article_id',
  1843. 'joinTable' => 'articles_tags'
  1844. ]);
  1845. $query = $table->find('all')->where(['id' => 1]);
  1846. $entity = $query->first();
  1847. $table->delete($entity);
  1848. $junction = $table->association('tags')->junction();
  1849. $query = $junction->find('all')->where(['article_id' => 1]);
  1850. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  1851. }
  1852. /**
  1853. * Test delete callbacks
  1854. *
  1855. * @return void
  1856. */
  1857. public function testDeleteCallbacks()
  1858. {
  1859. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1860. $options = new \ArrayObject(['atomic' => true, 'checkRules' => false]);
  1861. $mock = $this->getMock('Cake\Event\EventManager');
  1862. $mock->expects($this->at(0))
  1863. ->method('attach');
  1864. $mock->expects($this->at(1))
  1865. ->method('dispatch');
  1866. $mock->expects($this->at(2))
  1867. ->method('dispatch')
  1868. ->with($this->logicalAnd(
  1869. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  1870. $this->attributeEqualTo(
  1871. 'data',
  1872. ['entity' => $entity, 'options' => $options]
  1873. )
  1874. ));
  1875. $mock->expects($this->at(3))
  1876. ->method('dispatch')
  1877. ->with($this->logicalAnd(
  1878. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  1879. $this->attributeEqualTo(
  1880. 'data',
  1881. ['entity' => $entity, 'options' => $options]
  1882. )
  1883. ));
  1884. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1885. $entity->isNew(false);
  1886. $table->delete($entity, ['checkRules' => false]);
  1887. }
  1888. /**
  1889. * Test delete beforeDelete can abort the delete.
  1890. *
  1891. * @return void
  1892. */
  1893. public function testDeleteBeforeDeleteAbort()
  1894. {
  1895. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1896. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  1897. $mock = $this->getMock('Cake\Event\EventManager');
  1898. $mock->expects($this->at(2))
  1899. ->method('dispatch')
  1900. ->will($this->returnCallback(function ($event) {
  1901. $event->stopPropagation();
  1902. }));
  1903. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1904. $entity->isNew(false);
  1905. $result = $table->delete($entity, ['checkRules' => false]);
  1906. $this->assertNull($result);
  1907. }
  1908. /**
  1909. * Test delete beforeDelete return result
  1910. *
  1911. * @return void
  1912. */
  1913. public function testDeleteBeforeDeleteReturnResult()
  1914. {
  1915. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1916. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  1917. $mock = $this->getMock('Cake\Event\EventManager');
  1918. $mock->expects($this->at(2))
  1919. ->method('dispatch')
  1920. ->will($this->returnCallback(function ($event) {
  1921. $event->stopPropagation();
  1922. $event->result = 'got stopped';
  1923. }));
  1924. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  1925. $entity->isNew(false);
  1926. $result = $table->delete($entity, ['checkRules' => false]);
  1927. $this->assertEquals('got stopped', $result);
  1928. }
  1929. /**
  1930. * Test deleting new entities does nothing.
  1931. *
  1932. * @return void
  1933. */
  1934. public function testDeleteIsNew()
  1935. {
  1936. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  1937. $table = $this->getMock(
  1938. 'Cake\ORM\Table',
  1939. ['query'],
  1940. [['connection' => $this->connection]]
  1941. );
  1942. $table->expects($this->never())
  1943. ->method('query');
  1944. $entity->isNew(true);
  1945. $result = $table->delete($entity);
  1946. $this->assertFalse($result);
  1947. }
  1948. /**
  1949. * test hasField()
  1950. *
  1951. * @return void
  1952. */
  1953. public function testHasField()
  1954. {
  1955. $table = TableRegistry::get('articles');
  1956. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  1957. $this->assertTrue($table->hasField('title'), 'Should be there.');
  1958. $this->assertTrue($table->hasField('body'), 'Should be there.');
  1959. }
  1960. /**
  1961. * Tests that there exists a default validator
  1962. *
  1963. * @return void
  1964. */
  1965. public function testValidatorDefault()
  1966. {
  1967. $table = new Table();
  1968. $validator = $table->validator();
  1969. $this->assertSame($table, $validator->provider('table'));
  1970. $this->assertInstanceOf('Cake\Validation\Validator', $validator);
  1971. $default = $table->validator('default');
  1972. $this->assertSame($validator, $default);
  1973. }
  1974. /**
  1975. * Tests that it is possible to define custom validator methods
  1976. *
  1977. * @return void
  1978. */
  1979. public function functionTestValidationWithDefiner()
  1980. {
  1981. $table = $this->getMock('\Cake\ORM\Table', ['validationForOtherStuff']);
  1982. $table->expects($this->once())->method('validationForOtherStuff')
  1983. ->will($this->returnArgument(0));
  1984. $other = $table->validator('forOtherStuff');
  1985. $this->assertInstanceOf('Cake\Validation\Validator', $other);
  1986. $this->assertNotSame($other, $table->validator());
  1987. $this->assertSame($table, $other->provider('table'));
  1988. }
  1989. /**
  1990. * Tests that it is possible to set a custom validator under a name
  1991. *
  1992. * @return void
  1993. */
  1994. public function testValidatorSetter()
  1995. {
  1996. $table = new Table;
  1997. $validator = new \Cake\Validation\Validator;
  1998. $table->validator('other', $validator);
  1999. $this->assertSame($validator, $table->validator('other'));
  2000. $this->assertSame($table, $validator->provider('table'));
  2001. }
  2002. /**
  2003. * Tests that calling an entity with an empty array will run validation
  2004. * whereas calling it with no parameters will not run any validation.
  2005. *
  2006. * @return void
  2007. */
  2008. public function testNewEntityAndValidation()
  2009. {
  2010. $table = TableRegistry::get('Articles');
  2011. $validator = $table->validator()->requirePresence('title');
  2012. $entity = $table->newEntity([]);
  2013. $errors = $entity->errors();
  2014. $this->assertNotEmpty($errors['title']);
  2015. $entity = $table->newEntity();
  2016. $this->assertEmpty($entity->errors());
  2017. }
  2018. /**
  2019. * Test magic findByXX method.
  2020. *
  2021. * @return void
  2022. */
  2023. public function testMagicFindDefaultToAll()
  2024. {
  2025. $table = TableRegistry::get('Users');
  2026. $result = $table->findByUsername('garrett');
  2027. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2028. $expected = new QueryExpression(['username' => 'garrett'], $this->usersTypeMap);
  2029. $this->assertEquals($expected, $result->clause('where'));
  2030. }
  2031. /**
  2032. * Test magic findByXX errors on missing arguments.
  2033. *
  2034. * @expectedException \BadMethodCallException
  2035. * @expectedExceptionMessage Not enough arguments for magic finder. Got 0 required 1
  2036. * @return void
  2037. */
  2038. public function testMagicFindError()
  2039. {
  2040. $table = TableRegistry::get('Users');
  2041. $table->findByUsername();
  2042. }
  2043. /**
  2044. * Test magic findByXX errors on missing arguments.
  2045. *
  2046. * @expectedException \BadMethodCallException
  2047. * @expectedExceptionMessage Not enough arguments for magic finder. Got 1 required 2
  2048. * @return void
  2049. */
  2050. public function testMagicFindErrorMissingField()
  2051. {
  2052. $table = TableRegistry::get('Users');
  2053. $table->findByUsernameAndId('garrett');
  2054. }
  2055. /**
  2056. * Test magic findByXX errors when there is a mix of or & and.
  2057. *
  2058. * @expectedException \BadMethodCallException
  2059. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  2060. * @return void
  2061. */
  2062. public function testMagicFindErrorMixOfOperators()
  2063. {
  2064. $table = TableRegistry::get('Users');
  2065. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  2066. }
  2067. /**
  2068. * Test magic findByXX method.
  2069. *
  2070. * @return void
  2071. */
  2072. public function testMagicFindFirstAnd()
  2073. {
  2074. $table = TableRegistry::get('Users');
  2075. $result = $table->findByUsernameAndId('garrett', 4);
  2076. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2077. $expected = new QueryExpression(['username' => 'garrett', 'id' => 4], $this->usersTypeMap);
  2078. $this->assertEquals($expected, $result->clause('where'));
  2079. }
  2080. /**
  2081. * Test magic findByXX method.
  2082. *
  2083. * @return void
  2084. */
  2085. public function testMagicFindFirstOr()
  2086. {
  2087. $table = TableRegistry::get('Users');
  2088. $result = $table->findByUsernameOrId('garrett', 4);
  2089. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2090. $expected = new QueryExpression([], $this->usersTypeMap);
  2091. $expected->add(
  2092. [
  2093. 'OR' => [
  2094. 'username' => 'garrett',
  2095. 'id' => 4
  2096. ]]
  2097. );
  2098. $this->assertEquals($expected, $result->clause('where'));
  2099. }
  2100. /**
  2101. * Test magic findAllByXX method.
  2102. *
  2103. * @return void
  2104. */
  2105. public function testMagicFindAll()
  2106. {
  2107. $table = TableRegistry::get('Articles');
  2108. $result = $table->findAllByAuthorId(1);
  2109. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2110. $this->assertNull($result->clause('limit'));
  2111. $expected = new QueryExpression(['author_id' => 1], $this->articlesTypeMap);
  2112. $this->assertEquals($expected, $result->clause('where'));
  2113. }
  2114. /**
  2115. * Test magic findAllByXX method.
  2116. *
  2117. * @return void
  2118. */
  2119. public function testMagicFindAllAnd()
  2120. {
  2121. $table = TableRegistry::get('Users');
  2122. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  2123. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2124. $this->assertNull($result->clause('limit'));
  2125. $expected = new QueryExpression(
  2126. ['author_id' => 1, 'published' => 'Y'],
  2127. $this->usersTypeMap
  2128. );
  2129. $this->assertEquals($expected, $result->clause('where'));
  2130. }
  2131. /**
  2132. * Test magic findAllByXX method.
  2133. *
  2134. * @return void
  2135. */
  2136. public function testMagicFindAllOr()
  2137. {
  2138. $table = TableRegistry::get('Users');
  2139. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  2140. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2141. $this->assertNull($result->clause('limit'));
  2142. $expected = new QueryExpression();
  2143. $expected->typeMap()->defaults([
  2144. 'Users.id' => 'integer',
  2145. 'id' => 'integer',
  2146. 'Users.username' => 'string',
  2147. 'username' => 'string',
  2148. 'Users.password' => 'string',
  2149. 'password' => 'string',
  2150. 'Users.created' => 'timestamp',
  2151. 'created' => 'timestamp',
  2152. 'Users.updated' => 'timestamp',
  2153. 'updated' => 'timestamp',
  2154. ]);
  2155. $expected->add(
  2156. ['or' => ['author_id' => 1, 'published' => 'Y']]
  2157. );
  2158. $this->assertEquals($expected, $result->clause('where'));
  2159. $this->assertNull($result->clause('order'));
  2160. }
  2161. /**
  2162. * Test the behavior method.
  2163. *
  2164. * @return void
  2165. */
  2166. public function testBehaviorIntrospection()
  2167. {
  2168. $table = TableRegistry::get('users');
  2169. $table->addBehavior('Timestamp');
  2170. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  2171. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  2172. }
  2173. /**
  2174. * Tests saving belongsTo association
  2175. *
  2176. * @group save
  2177. * @return void
  2178. */
  2179. public function testSaveBelongsTo()
  2180. {
  2181. $entity = new \Cake\ORM\Entity([
  2182. 'title' => 'A Title',
  2183. 'body' => 'A body'
  2184. ]);
  2185. $entity->author = new \Cake\ORM\Entity([
  2186. 'name' => 'Jose'
  2187. ]);
  2188. $table = TableRegistry::get('articles');
  2189. $table->belongsTo('authors');
  2190. $this->assertSame($entity, $table->save($entity));
  2191. $this->assertFalse($entity->isNew());
  2192. $this->assertFalse($entity->author->isNew());
  2193. $this->assertEquals(5, $entity->author->id);
  2194. $this->assertEquals(5, $entity->get('author_id'));
  2195. }
  2196. /**
  2197. * Tests saving hasOne association
  2198. *
  2199. * @group save
  2200. * @return void
  2201. */
  2202. public function testSaveHasOne()
  2203. {
  2204. $entity = new \Cake\ORM\Entity([
  2205. 'name' => 'Jose'
  2206. ]);
  2207. $entity->article = new \Cake\ORM\Entity([
  2208. 'title' => 'A Title',
  2209. 'body' => 'A body'
  2210. ]);
  2211. $table = TableRegistry::get('authors');
  2212. $table->hasOne('articles');
  2213. $this->assertSame($entity, $table->save($entity));
  2214. $this->assertFalse($entity->isNew());
  2215. $this->assertFalse($entity->article->isNew());
  2216. $this->assertEquals(4, $entity->article->id);
  2217. $this->assertEquals(5, $entity->article->get('author_id'));
  2218. $this->assertFalse($entity->article->dirty('author_id'));
  2219. }
  2220. /**
  2221. * Tests saving associations only saves associations
  2222. * if they are entities.
  2223. *
  2224. * @group save
  2225. * @return void
  2226. */
  2227. public function testSaveOnlySaveAssociatedEntities()
  2228. {
  2229. $entity = new \Cake\ORM\Entity([
  2230. 'name' => 'Jose'
  2231. ]);
  2232. // Not an entity.
  2233. $entity->article = [
  2234. 'title' => 'A Title',
  2235. 'body' => 'A body'
  2236. ];
  2237. $table = TableRegistry::get('authors');
  2238. $table->hasOne('articles');
  2239. $table->save($entity);
  2240. $this->assertFalse($entity->isNew());
  2241. $this->assertInternalType('array', $entity->article);
  2242. }
  2243. /**
  2244. * Tests saving multiple entities in a hasMany association
  2245. *
  2246. * @return void
  2247. */
  2248. public function testSaveHasMany()
  2249. {
  2250. $entity = new \Cake\ORM\Entity([
  2251. 'name' => 'Jose'
  2252. ]);
  2253. $entity->articles = [
  2254. new \Cake\ORM\Entity([
  2255. 'title' => 'A Title',
  2256. 'body' => 'A body'
  2257. ]),
  2258. new \Cake\ORM\Entity([
  2259. 'title' => 'Another Title',
  2260. 'body' => 'Another body'
  2261. ])
  2262. ];
  2263. $table = TableRegistry::get('authors');
  2264. $table->hasMany('articles');
  2265. $this->assertSame($entity, $table->save($entity));
  2266. $this->assertFalse($entity->isNew());
  2267. $this->assertFalse($entity->articles[0]->isNew());
  2268. $this->assertFalse($entity->articles[1]->isNew());
  2269. $this->assertEquals(4, $entity->articles[0]->id);
  2270. $this->assertEquals(5, $entity->articles[1]->id);
  2271. $this->assertEquals(5, $entity->articles[0]->author_id);
  2272. $this->assertEquals(5, $entity->articles[1]->author_id);
  2273. }
  2274. /**
  2275. * Tests saving belongsToMany records
  2276. *
  2277. * @group save
  2278. * @return void
  2279. */
  2280. public function testSaveBelongsToMany()
  2281. {
  2282. $entity = new \Cake\ORM\Entity([
  2283. 'title' => 'A Title',
  2284. 'body' => 'A body'
  2285. ]);
  2286. $entity->tags = [
  2287. new \Cake\ORM\Entity([
  2288. 'name' => 'Something New'
  2289. ]),
  2290. new \Cake\ORM\Entity([
  2291. 'name' => 'Another Something'
  2292. ])
  2293. ];
  2294. $table = TableRegistry::get('articles');
  2295. $table->belongsToMany('tags');
  2296. $this->assertSame($entity, $table->save($entity));
  2297. $this->assertFalse($entity->isNew());
  2298. $this->assertFalse($entity->tags[0]->isNew());
  2299. $this->assertFalse($entity->tags[1]->isNew());
  2300. $this->assertEquals(4, $entity->tags[0]->id);
  2301. $this->assertEquals(5, $entity->tags[1]->id);
  2302. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  2303. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2304. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  2305. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2306. }
  2307. /**
  2308. * Tests saving belongsToMany records when record exists.
  2309. *
  2310. * @group save
  2311. * @return void
  2312. */
  2313. public function testSaveBelongsToManyJoinDataOnExistingRecord()
  2314. {
  2315. $tags = TableRegistry::get('Tags');
  2316. $table = TableRegistry::get('Articles');
  2317. $table->belongsToMany('Tags');
  2318. $entity = $table->find()->contain('Tags')->first();
  2319. // not associated to the article already.
  2320. $entity->tags[] = $tags->get(3);
  2321. $entity->dirty('tags', true);
  2322. $this->assertSame($entity, $table->save($entity));
  2323. $this->assertFalse($entity->isNew());
  2324. $this->assertFalse($entity->tags[0]->isNew());
  2325. $this->assertFalse($entity->tags[1]->isNew());
  2326. $this->assertFalse($entity->tags[2]->isNew());
  2327. $this->assertNotEmpty($entity->tags[0]->_joinData);
  2328. $this->assertNotEmpty($entity->tags[1]->_joinData);
  2329. $this->assertNotEmpty($entity->tags[2]->_joinData);
  2330. }
  2331. /**
  2332. * Test that belongsToMany can be saved with _joinData data.
  2333. *
  2334. * @return void
  2335. */
  2336. public function testSaveBelongsToManyJoinData()
  2337. {
  2338. $articles = TableRegistry::get('Articles');
  2339. $article = $articles->get(1, ['contain' => ['Tags']]);
  2340. $data = [
  2341. 'tags' => [
  2342. ['id' => 1, '_joinData' => ['highlighted' => 1]],
  2343. ['id' => 3]
  2344. ]
  2345. ];
  2346. $article = $articles->patchEntity($article, $data);
  2347. $result = $articles->save($article);
  2348. $this->assertSame($result, $article);
  2349. }
  2350. /**
  2351. * Tests saving belongsToMany records can delete all links.
  2352. *
  2353. * @group save
  2354. * @return void
  2355. */
  2356. public function testSaveBelongsToManyDeleteAllLinks()
  2357. {
  2358. $table = TableRegistry::get('articles');
  2359. $table->belongsToMany('tags', [
  2360. 'saveStrategy' => 'replace',
  2361. ]);
  2362. $entity = $table->get(1, ['contain' => 'Tags']);
  2363. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  2364. $entity->tags = [];
  2365. $result = $table->save($entity);
  2366. $this->assertSame($result, $entity);
  2367. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  2368. $entity = $table->get(1, ['contain' => 'Tags']);
  2369. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  2370. }
  2371. /**
  2372. * Tests saving belongsToMany records can delete some links.
  2373. *
  2374. * @group save
  2375. * @return void
  2376. */
  2377. public function testSaveBelongsToManyDeleteSomeLinks()
  2378. {
  2379. $table = TableRegistry::get('articles');
  2380. $table->belongsToMany('tags', [
  2381. 'saveStrategy' => 'replace',
  2382. ]);
  2383. $entity = $table->get(1, ['contain' => 'Tags']);
  2384. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  2385. $tag = new \Cake\ORM\Entity([
  2386. 'id' => 2,
  2387. ]);
  2388. $entity->tags = [$tag];
  2389. $result = $table->save($entity);
  2390. $this->assertSame($result, $entity);
  2391. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  2392. $this->assertEquals($tag, $entity->tags[0]);
  2393. $entity = $table->get(1, ['contain' => 'Tags']);
  2394. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  2395. $this->assertEquals($tag->id, $entity->tags[0]->id);
  2396. }
  2397. /**
  2398. * Tests that saving a persisted and clean entity will is a no-op
  2399. *
  2400. * @group save
  2401. * @return void
  2402. */
  2403. public function testSaveCleanEntity()
  2404. {
  2405. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  2406. $entity = new \Cake\ORM\Entity(
  2407. ['id' => 'foo'],
  2408. ['markNew' => false, 'markClean' => true]
  2409. );
  2410. $table->expects($this->never())->method('_processSave');
  2411. $this->assertSame($entity, $table->save($entity));
  2412. }
  2413. /**
  2414. * Integration test to show how to append a new tag to an article
  2415. *
  2416. * @group save
  2417. * @return void
  2418. */
  2419. public function testBelongsToManyIntegration()
  2420. {
  2421. $table = TableRegistry::get('articles');
  2422. $table->belongsToMany('tags');
  2423. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2424. $tags = $article->tags;
  2425. $this->assertNotEmpty($tags);
  2426. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  2427. $article->tags = $tags;
  2428. $this->assertSame($article, $table->save($article));
  2429. $tags = $article->tags;
  2430. $this->assertCount(3, $tags);
  2431. $this->assertFalse($tags[2]->isNew());
  2432. $this->assertEquals(4, $tags[2]->id);
  2433. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  2434. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  2435. }
  2436. /**
  2437. * Tests that it is possible to do a deep save and control what associations get saved,
  2438. * while having control of the options passed to each level of the save
  2439. *
  2440. * @group save
  2441. * @return void
  2442. */
  2443. public function testSaveDeepAssociationOptions()
  2444. {
  2445. $articles = $this->getMock(
  2446. '\Cake\ORM\Table',
  2447. ['_insert'],
  2448. [['table' => 'articles', 'connection' => $this->connection]]
  2449. );
  2450. $authors = $this->getMock(
  2451. '\Cake\ORM\Table',
  2452. ['_insert'],
  2453. [['table' => 'authors', 'connection' => $this->connection]]
  2454. );
  2455. $supervisors = $this->getMock(
  2456. '\Cake\ORM\Table',
  2457. ['_insert', 'validate'],
  2458. [[
  2459. 'table' => 'authors',
  2460. 'alias' => 'supervisors',
  2461. 'connection' => $this->connection
  2462. ]]
  2463. );
  2464. $tags = $this->getMock(
  2465. '\Cake\ORM\Table',
  2466. ['_insert'],
  2467. [['table' => 'tags', 'connection' => $this->connection]]
  2468. );
  2469. $articles->belongsTo('authors', ['targetTable' => $authors]);
  2470. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  2471. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  2472. $entity = new \Cake\ORM\Entity([
  2473. 'title' => 'bar',
  2474. 'author' => new \Cake\ORM\Entity([
  2475. 'name' => 'Juan',
  2476. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  2477. 'tags' => [
  2478. new \Cake\ORM\Entity(['name' => 'foo'])
  2479. ]
  2480. ]),
  2481. ]);
  2482. $entity->isNew(true);
  2483. $entity->author->isNew(true);
  2484. $entity->author->supervisor->isNew(true);
  2485. $entity->author->tags[0]->isNew(true);
  2486. $articles->expects($this->once())
  2487. ->method('_insert')
  2488. ->with($entity, ['title' => 'bar'])
  2489. ->will($this->returnValue($entity));
  2490. $authors->expects($this->once())
  2491. ->method('_insert')
  2492. ->with($entity->author, ['name' => 'Juan'])
  2493. ->will($this->returnValue($entity->author));
  2494. $supervisors->expects($this->once())
  2495. ->method('_insert')
  2496. ->with($entity->author->supervisor, ['name' => 'Marc'])
  2497. ->will($this->returnValue($entity->author->supervisor));
  2498. $tags->expects($this->never())->method('_insert');
  2499. $this->assertSame($entity, $articles->save($entity, [
  2500. 'associated' => [
  2501. 'authors' => [],
  2502. 'authors.supervisors' => [
  2503. 'atomic' => false,
  2504. 'associated' => false
  2505. ]
  2506. ]
  2507. ]));
  2508. }
  2509. /**
  2510. * Integration test for linking entities with belongsToMany
  2511. *
  2512. * @return void
  2513. */
  2514. public function testLinkBelongsToMany()
  2515. {
  2516. $table = TableRegistry::get('articles');
  2517. $table->belongsToMany('tags');
  2518. $tagsTable = TableRegistry::get('tags');
  2519. $source = ['source' => 'tags'];
  2520. $options = ['markNew' => false];
  2521. $article = new \Cake\ORM\Entity([
  2522. 'id' => 1,
  2523. ], $options);
  2524. $newTag = new \TestApp\Model\Entity\Tag([
  2525. 'name' => 'Foo'
  2526. ], $source);
  2527. $tags[] = new \TestApp\Model\Entity\Tag([
  2528. 'id' => 3
  2529. ], $options + $source);
  2530. $tags[] = $newTag;
  2531. $tagsTable->save($newTag);
  2532. $table->association('tags')->link($article, $tags);
  2533. $this->assertEquals($article->tags, $tags);
  2534. foreach ($tags as $tag) {
  2535. $this->assertFalse($tag->isNew());
  2536. }
  2537. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2538. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  2539. $this->assertEquals($article->tags[3], $tags[1]);
  2540. }
  2541. /**
  2542. * Integration test to show how to unlink a single record from a belongsToMany
  2543. *
  2544. * @return void
  2545. */
  2546. public function testUnlinkBelongsToMany()
  2547. {
  2548. $table = TableRegistry::get('articles');
  2549. $table->belongsToMany('tags');
  2550. $tagsTable = TableRegistry::get('tags');
  2551. $options = ['markNew' => false];
  2552. $article = $table->find('all')
  2553. ->where(['id' => 1])
  2554. ->contain(['tags'])->first();
  2555. $table->association('tags')->unlink($article, [$article->tags[0]]);
  2556. $this->assertCount(1, $article->tags);
  2557. $this->assertEquals(2, $article->tags[0]->get('id'));
  2558. $this->assertFalse($article->dirty('tags'));
  2559. }
  2560. /**
  2561. * Integration test to show how to unlink multiple records from a belongsToMany
  2562. *
  2563. * @return void
  2564. */
  2565. public function testUnlinkBelongsToManyMultiple()
  2566. {
  2567. $table = TableRegistry::get('articles');
  2568. $table->belongsToMany('tags');
  2569. $tagsTable = TableRegistry::get('tags');
  2570. $options = ['markNew' => false];
  2571. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2572. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2573. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2574. $table->association('tags')->unlink($article, $tags);
  2575. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2576. $this->assertEmpty($left->tags);
  2577. }
  2578. /**
  2579. * Integration test to show how to unlink multiple records from a belongsToMany
  2580. * providing some of the joint
  2581. *
  2582. * @return void
  2583. */
  2584. public function testUnlinkBelongsToManyPassingJoint()
  2585. {
  2586. $table = TableRegistry::get('articles');
  2587. $table->belongsToMany('tags');
  2588. $tagsTable = TableRegistry::get('tags');
  2589. $options = ['markNew' => false];
  2590. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2591. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2592. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2593. $tags[1]->_joinData = new \Cake\ORM\Entity([
  2594. 'article_id' => 1,
  2595. 'tag_id' => 2
  2596. ], $options);
  2597. $table->association('tags')->unlink($article, $tags);
  2598. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2599. $this->assertEmpty($left->tags);
  2600. }
  2601. /**
  2602. * Integration test to show how to replace records from a belongsToMany
  2603. *
  2604. * @return void
  2605. */
  2606. public function testReplacelinksBelongsToMany()
  2607. {
  2608. $table = TableRegistry::get('articles');
  2609. $table->belongsToMany('tags');
  2610. $tagsTable = TableRegistry::get('tags');
  2611. $options = ['markNew' => false];
  2612. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2613. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2614. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2615. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  2616. $table->association('tags')->replaceLinks($article, $tags);
  2617. $this->assertEquals(2, $article->tags[0]->id);
  2618. $this->assertEquals(3, $article->tags[1]->id);
  2619. $this->assertEquals(4, $article->tags[2]->id);
  2620. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2621. $this->assertCount(3, $article->tags);
  2622. $this->assertEquals(2, $article->tags[0]->id);
  2623. $this->assertEquals(3, $article->tags[1]->id);
  2624. $this->assertEquals(4, $article->tags[2]->id);
  2625. $this->assertEquals('foo', $article->tags[2]->name);
  2626. }
  2627. /**
  2628. * Integration test to show how remove all links from a belongsToMany
  2629. *
  2630. * @return void
  2631. */
  2632. public function testReplacelinksBelongsToManyWithEmpty()
  2633. {
  2634. $table = TableRegistry::get('articles');
  2635. $table->belongsToMany('tags');
  2636. $tagsTable = TableRegistry::get('tags');
  2637. $options = ['markNew' => false];
  2638. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2639. $tags = [];
  2640. $table->association('tags')->replaceLinks($article, $tags);
  2641. $this->assertSame($tags, $article->tags);
  2642. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2643. $this->assertEmpty($article->tags);
  2644. }
  2645. /**
  2646. * Integration test to show how to replace records from a belongsToMany
  2647. * passing the joint property along in the target entity
  2648. *
  2649. * @return void
  2650. */
  2651. public function testReplacelinksBelongsToManyWithJoint()
  2652. {
  2653. $table = TableRegistry::get('articles');
  2654. $table->belongsToMany('tags');
  2655. $tagsTable = TableRegistry::get('tags');
  2656. $options = ['markNew' => false];
  2657. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2658. $tags[] = new \TestApp\Model\Entity\Tag([
  2659. 'id' => 2,
  2660. '_joinData' => new \Cake\ORM\Entity([
  2661. 'article_id' => 1,
  2662. 'tag_id' => 2,
  2663. ])
  2664. ], $options);
  2665. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2666. $table->association('tags')->replaceLinks($article, $tags);
  2667. $this->assertSame($tags, $article->tags);
  2668. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2669. $this->assertCount(2, $article->tags);
  2670. $this->assertEquals(2, $article->tags[0]->id);
  2671. $this->assertEquals(3, $article->tags[1]->id);
  2672. }
  2673. /**
  2674. * Tests that it is possible to call find with no arguments
  2675. *
  2676. * @return void
  2677. */
  2678. public function testSimplifiedFind()
  2679. {
  2680. $table = $this->getMock(
  2681. '\Cake\ORM\Table',
  2682. ['callFinder'],
  2683. [[
  2684. 'connection' => $this->connection,
  2685. 'schema' => ['id' => ['type' => 'integer']]
  2686. ]]
  2687. );
  2688. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  2689. $table->expects($this->once())->method('callFinder')
  2690. ->with('all', $query, []);
  2691. $table->find();
  2692. }
  2693. public function providerForTestGet()
  2694. {
  2695. return [
  2696. [ ['fields' => ['id']] ],
  2697. [ ['fields' => ['id'], 'cache' => false] ]
  2698. ];
  2699. }
  2700. /**
  2701. * Test that get() will use the primary key for searching and return the first
  2702. * entity found
  2703. *
  2704. * @dataProvider providerForTestGet
  2705. * @param array $options
  2706. * @return void
  2707. */
  2708. public function testGet($options)
  2709. {
  2710. $table = $this->getMock(
  2711. '\Cake\ORM\Table',
  2712. ['callFinder', 'query'],
  2713. [[
  2714. 'connection' => $this->connection,
  2715. 'schema' => [
  2716. 'id' => ['type' => 'integer'],
  2717. 'bar' => ['type' => 'integer'],
  2718. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2719. ]
  2720. ]]
  2721. );
  2722. $query = $this->getMock(
  2723. '\Cake\ORM\Query',
  2724. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  2725. [$this->connection, $table]
  2726. );
  2727. $entity = new \Cake\ORM\Entity;
  2728. $table->expects($this->once())->method('query')
  2729. ->will($this->returnValue($query));
  2730. $table->expects($this->once())->method('callFinder')
  2731. ->with('all', $query, ['fields' => ['id']])
  2732. ->will($this->returnValue($query));
  2733. $query->expects($this->once())->method('where')
  2734. ->with([$table->alias() . '.bar' => 10])
  2735. ->will($this->returnSelf());
  2736. $query->expects($this->never())->method('cache');
  2737. $query->expects($this->once())->method('firstOrFail')
  2738. ->will($this->returnValue($entity));
  2739. $result = $table->get(10, $options);
  2740. $this->assertSame($entity, $result);
  2741. }
  2742. public function providerForTestGetWithCache()
  2743. {
  2744. return [
  2745. [
  2746. ['fields' => ['id'], 'cache' => 'default'],
  2747. 'get:test.table_name[10]', 'default'
  2748. ],
  2749. [
  2750. ['fields' => ['id'], 'cache' => 'default', 'key' => 'custom_key'],
  2751. 'custom_key', 'default'
  2752. ]
  2753. ];
  2754. }
  2755. /**
  2756. * Test that get() will use the cache.
  2757. *
  2758. * @dataProvider providerForTestGetWithCache
  2759. * @param array $options
  2760. * @param string $cacheKey
  2761. * @param string $cacheConfig
  2762. * @return void
  2763. */
  2764. public function testGetWithCache($options, $cacheKey, $cacheConfig)
  2765. {
  2766. $table = $this->getMock(
  2767. '\Cake\ORM\Table',
  2768. ['callFinder', 'query'],
  2769. [[
  2770. 'connection' => $this->connection,
  2771. 'schema' => [
  2772. 'id' => ['type' => 'integer'],
  2773. 'bar' => ['type' => 'integer'],
  2774. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2775. ]
  2776. ]]
  2777. );
  2778. $table->table('table_name');
  2779. $query = $this->getMock(
  2780. '\Cake\ORM\Query',
  2781. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  2782. [$this->connection, $table]
  2783. );
  2784. $entity = new \Cake\ORM\Entity;
  2785. $table->expects($this->once())->method('query')
  2786. ->will($this->returnValue($query));
  2787. $table->expects($this->once())->method('callFinder')
  2788. ->with('all', $query, ['fields' => ['id']])
  2789. ->will($this->returnValue($query));
  2790. $query->expects($this->once())->method('where')
  2791. ->with([$table->alias() . '.bar' => 10])
  2792. ->will($this->returnSelf());
  2793. $query->expects($this->once())->method('cache')
  2794. ->with($cacheKey, $cacheConfig)
  2795. ->will($this->returnSelf());
  2796. $query->expects($this->once())->method('firstOrFail')
  2797. ->will($this->returnValue($entity));
  2798. $result = $table->get(10, $options);
  2799. $this->assertSame($entity, $result);
  2800. }
  2801. /**
  2802. * Tests that get() will throw an exception if the record was not found
  2803. *
  2804. * @expectedException Cake\Datasource\Exception\RecordNotFoundException
  2805. * @expectedExceptionMessage Record not found in table "articles"
  2806. * @return void
  2807. */
  2808. public function testGetNotFoundException()
  2809. {
  2810. $table = new Table([
  2811. 'name' => 'Articles',
  2812. 'connection' => $this->connection,
  2813. 'table' => 'articles',
  2814. ]);
  2815. $table->get(10);
  2816. }
  2817. /**
  2818. * Test that an exception is raised when there are not enough keys.
  2819. *
  2820. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  2821. * @expectedExceptionMessage Record not found in table "articles" with primary key [NULL]
  2822. * @return void
  2823. */
  2824. public function testGetExceptionOnNoData()
  2825. {
  2826. $table = new Table([
  2827. 'name' => 'Articles',
  2828. 'connection' => $this->connection,
  2829. 'table' => 'articles',
  2830. ]);
  2831. $table->get(null);
  2832. }
  2833. /**
  2834. * Test that an exception is raised when there are too many keys.
  2835. *
  2836. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  2837. * @expectedExceptionMessage Record not found in table "articles" with primary key [1, 'two']
  2838. * @return void
  2839. */
  2840. public function testGetExceptionOnTooMuchData()
  2841. {
  2842. $table = new Table([
  2843. 'name' => 'Articles',
  2844. 'connection' => $this->connection,
  2845. 'table' => 'articles',
  2846. ]);
  2847. $table->get([1, 'two']);
  2848. }
  2849. /**
  2850. * Tests that patchEntity delegates the task to the marshaller and passed
  2851. * all associations
  2852. *
  2853. * @return void
  2854. */
  2855. public function testPatchEntity()
  2856. {
  2857. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  2858. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  2859. $table->belongsTo('users');
  2860. $table->hasMany('articles');
  2861. $table->expects($this->once())->method('marshaller')
  2862. ->will($this->returnValue($marshaller));
  2863. $entity = new \Cake\ORM\Entity;
  2864. $data = ['foo' => 'bar'];
  2865. $marshaller->expects($this->once())
  2866. ->method('merge')
  2867. ->with($entity, $data, ['associated' => ['users', 'articles']])
  2868. ->will($this->returnValue($entity));
  2869. $table->patchEntity($entity, $data);
  2870. }
  2871. /**
  2872. * Tests that patchEntities delegates the task to the marshaller and passed
  2873. * all associations
  2874. *
  2875. * @return void
  2876. */
  2877. public function testPatchEntities()
  2878. {
  2879. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  2880. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  2881. $table->belongsTo('users');
  2882. $table->hasMany('articles');
  2883. $table->expects($this->once())->method('marshaller')
  2884. ->will($this->returnValue($marshaller));
  2885. $entities = [new \Cake\ORM\Entity];
  2886. $data = [['foo' => 'bar']];
  2887. $marshaller->expects($this->once())
  2888. ->method('mergeMany')
  2889. ->with($entities, $data, ['associated' => ['users', 'articles']])
  2890. ->will($this->returnValue($entities));
  2891. $table->patchEntities($entities, $data);
  2892. }
  2893. /**
  2894. * Tests __debugInfo
  2895. *
  2896. * @return void
  2897. */
  2898. public function testDebugInfo()
  2899. {
  2900. $articles = TableRegistry::get('articles');
  2901. $articles->addBehavior('Timestamp');
  2902. $result = $articles->__debugInfo();
  2903. $expected = [
  2904. 'table' => 'articles',
  2905. 'alias' => 'articles',
  2906. 'entityClass' => 'TestApp\Model\Entity\Article',
  2907. 'associations' => ['authors', 'tags', 'articlestags'],
  2908. 'behaviors' => ['Timestamp'],
  2909. 'defaultConnection' => 'default',
  2910. 'connectionName' => 'test'
  2911. ];
  2912. $this->assertEquals($expected, $result);
  2913. }
  2914. /**
  2915. * Test the findOrCreate method.
  2916. *
  2917. * @return void
  2918. */
  2919. public function testFindOrCreate()
  2920. {
  2921. $articles = TableRegistry::get('Articles');
  2922. $article = $articles->findOrCreate(['title' => 'Not there'], function ($article) {
  2923. $article->body = 'New body';
  2924. });
  2925. $this->assertFalse($article->isNew());
  2926. $this->assertNotNull($article->id);
  2927. $this->assertEquals('Not there', $article->title);
  2928. $this->assertEquals('New body', $article->body);
  2929. $article = $articles->findOrCreate(['title' => 'Not there']);
  2930. $this->assertFalse($article->isNew());
  2931. $this->assertNotNull($article->id);
  2932. $this->assertEquals('Not there', $article->title);
  2933. $article = $articles->findOrCreate(['title' => 'First Article'], function ($article) {
  2934. $this->fail('Should not be called for existing entities.');
  2935. });
  2936. $this->assertFalse($article->isNew());
  2937. $this->assertNotNull($article->id);
  2938. $this->assertEquals('First Article', $article->title);
  2939. $article = $articles->findOrCreate(
  2940. ['author_id' => 2, 'title' => 'First Article'],
  2941. function ($article) {
  2942. $article->set(['published' => 'N', 'body' => 'New body']);
  2943. }
  2944. );
  2945. $this->assertFalse($article->isNew());
  2946. $this->assertNotNull($article->id);
  2947. $this->assertEquals('First Article', $article->title);
  2948. $this->assertEquals('New body', $article->body);
  2949. $this->assertEquals('N', $article->published);
  2950. $this->assertEquals(2, $article->author_id);
  2951. }
  2952. /**
  2953. * Test that creating a table fires the initialize event.
  2954. *
  2955. * @return void
  2956. */
  2957. public function testInitializeEvent()
  2958. {
  2959. $count = 0;
  2960. $cb = function ($event) use (&$count) {
  2961. $count++;
  2962. };
  2963. EventManager::instance()->attach($cb, 'Model.initialize');
  2964. $articles = TableRegistry::get('Articles');
  2965. $this->assertEquals(1, $count, 'Callback should be called');
  2966. EventManager::instance()->detach($cb, 'Model.initialize');
  2967. }
  2968. /**
  2969. * Tests the hasFinder method
  2970. *
  2971. * @return void
  2972. */
  2973. public function testHasFinder()
  2974. {
  2975. $table = TableRegistry::get('articles');
  2976. $table->addBehavior('Sluggable');
  2977. $this->assertTrue($table->hasFinder('list'));
  2978. $this->assertTrue($table->hasFinder('noSlug'));
  2979. $this->assertFalse($table->hasFinder('noFind'));
  2980. }
  2981. /**
  2982. * Tests that calling validator() trigger the buildValidator event
  2983. *
  2984. * @return void
  2985. */
  2986. public function testBuildValidatorEvent()
  2987. {
  2988. $count = 0;
  2989. $cb = function ($event) use (&$count) {
  2990. $count++;
  2991. };
  2992. EventManager::instance()->attach($cb, 'Model.buildValidator');
  2993. $articles = TableRegistry::get('Articles');
  2994. $articles->validator();
  2995. $this->assertEquals(1, $count, 'Callback should be called');
  2996. $articles->validator();
  2997. $this->assertEquals(1, $count, 'Callback should be called only once');
  2998. }
  2999. /**
  3000. * Tests the validateUnique method with different combinations
  3001. *
  3002. * @return void
  3003. */
  3004. public function testValidateUnique()
  3005. {
  3006. $table = TableRegistry::get('Users');
  3007. $validator = new Validator;
  3008. $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
  3009. $validator->provider('table', $table);
  3010. $data = ['username' => 'larry'];
  3011. $this->assertNotEmpty($validator->errors($data));
  3012. $data = ['username' => 'jose'];
  3013. $this->assertEmpty($validator->errors($data));
  3014. $data = ['username' => 'larry', 'id' => 3];
  3015. $this->assertEmpty($validator->errors($data, false));
  3016. $data = ['username' => 'larry', 'id' => 3];
  3017. $this->assertNotEmpty($validator->errors($data));
  3018. $data = ['username' => 'larry'];
  3019. $this->assertNotEmpty($validator->errors($data, false));
  3020. $validator->add('username', 'unique', [
  3021. 'rule' => 'validateUnique', 'provider' => 'table'
  3022. ]);
  3023. $data = ['username' => 'larry'];
  3024. $this->assertNotEmpty($validator->errors($data, false));
  3025. }
  3026. }