TableTest.php 129 KB

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