TableTest.php 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361
  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\Collection\Collection;
  18. use Cake\Core\Configure;
  19. use Cake\Core\Plugin;
  20. use Cake\Database\Exception;
  21. use Cake\Database\Expression\QueryExpression;
  22. use Cake\Database\TypeMap;
  23. use Cake\Datasource\ConnectionManager;
  24. use Cake\Event\Event;
  25. use Cake\Event\EventManager;
  26. use Cake\I18n\Time;
  27. use Cake\ORM\AssociationCollection;
  28. use Cake\ORM\Association\HasMany;
  29. use Cake\ORM\Entity;
  30. use Cake\ORM\Query;
  31. use Cake\ORM\RulesChecker;
  32. use Cake\ORM\Table;
  33. use Cake\ORM\TableRegistry;
  34. use Cake\TestSuite\TestCase;
  35. use Cake\Validation\Validator;
  36. /**
  37. * Used to test correct class is instantiated when using TableRegistry::get();
  38. */
  39. class UsersTable extends Table
  40. {
  41. }
  42. /**
  43. * Tests Table class
  44. *
  45. */
  46. class TableTest extends TestCase
  47. {
  48. public $fixtures = [
  49. 'core.articles',
  50. 'core.articles_tags',
  51. 'core.authors',
  52. 'core.categories',
  53. 'core.comments',
  54. 'core.groups',
  55. 'core.groups_members',
  56. 'core.members',
  57. 'core.polymorphic_tagged',
  58. 'core.site_articles',
  59. 'core.tags',
  60. 'core.users'
  61. ];
  62. /**
  63. * Handy variable containing the next primary key that will be inserted in the
  64. * users table
  65. *
  66. * @var int
  67. */
  68. public static $nextUserId = 5;
  69. public function setUp()
  70. {
  71. parent::setUp();
  72. $this->connection = ConnectionManager::get('test');
  73. Configure::write('App.namespace', 'TestApp');
  74. $this->usersTypeMap = new TypeMap([
  75. 'Users.id' => 'integer',
  76. 'id' => 'integer',
  77. 'Users__id' => 'integer',
  78. 'Users.username' => 'string',
  79. 'Users__username' => 'string',
  80. 'username' => 'string',
  81. 'Users.password' => 'string',
  82. 'Users__password' => 'string',
  83. 'password' => 'string',
  84. 'Users.created' => 'timestamp',
  85. 'Users__created' => 'timestamp',
  86. 'created' => 'timestamp',
  87. 'Users.updated' => 'timestamp',
  88. 'Users__updated' => 'timestamp',
  89. 'updated' => 'timestamp',
  90. ]);
  91. $this->articlesTypeMap = new TypeMap([
  92. 'Articles.id' => 'integer',
  93. 'Articles__id' => 'integer',
  94. 'id' => 'integer',
  95. 'Articles.title' => 'string',
  96. 'Articles__title' => 'string',
  97. 'title' => 'string',
  98. 'Articles.author_id' => 'integer',
  99. 'Articles__author_id' => 'integer',
  100. 'author_id' => 'integer',
  101. 'Articles.body' => 'text',
  102. 'Articles__body' => 'text',
  103. 'body' => 'text',
  104. 'Articles.published' => 'string',
  105. 'Articles__published' => 'string',
  106. 'published' => 'string',
  107. ]);
  108. }
  109. /**
  110. * teardown method
  111. *
  112. * @return void
  113. */
  114. public function tearDown()
  115. {
  116. parent::tearDown();
  117. TableRegistry::clear();
  118. }
  119. /**
  120. * Tests the table method
  121. *
  122. * @return void
  123. */
  124. public function testTableMethod()
  125. {
  126. $table = new Table(['table' => 'users']);
  127. $this->assertEquals('users', $table->table());
  128. $table = new UsersTable;
  129. $this->assertEquals('users', $table->table());
  130. $table = $this->getMockBuilder('\Cake\ORM\Table')
  131. ->setMethods(['find'])
  132. ->setMockClassName('SpecialThingsTable')
  133. ->getMock();
  134. $this->assertEquals('special_things', $table->table());
  135. $table = new Table(['alias' => 'LoveBoats']);
  136. $this->assertEquals('love_boats', $table->table());
  137. $table->table('other');
  138. $this->assertEquals('other', $table->table());
  139. $table->table('database.other');
  140. $this->assertEquals('database.other', $table->table());
  141. }
  142. /**
  143. * Tests the alias method
  144. *
  145. * @return void
  146. */
  147. public function testAliasMethod()
  148. {
  149. $table = new Table(['alias' => 'users']);
  150. $this->assertEquals('users', $table->alias());
  151. $table = new Table(['table' => 'stuffs']);
  152. $this->assertEquals('stuffs', $table->alias());
  153. $table = new UsersTable;
  154. $this->assertEquals('Users', $table->alias());
  155. $table = $this->getMockBuilder('\Cake\ORM\Table')
  156. ->setMethods(['find'])
  157. ->setMockClassName('SpecialThingTable')
  158. ->getMock();
  159. $this->assertEquals('SpecialThing', $table->alias());
  160. $table->alias('AnotherOne');
  161. $this->assertEquals('AnotherOne', $table->alias());
  162. }
  163. /**
  164. * Test that aliasField() works.
  165. *
  166. * @return void
  167. */
  168. public function testAliasField()
  169. {
  170. $table = new Table(['alias' => 'Users']);
  171. $this->assertEquals('Users.id', $table->aliasField('id'));
  172. }
  173. /**
  174. * Tests connection method
  175. *
  176. * @return void
  177. */
  178. public function testConnection()
  179. {
  180. $table = new Table(['table' => 'users']);
  181. $this->assertNull($table->connection());
  182. $table->connection($this->connection);
  183. $this->assertSame($this->connection, $table->connection());
  184. }
  185. /**
  186. * Tests primaryKey method
  187. *
  188. * @return void
  189. */
  190. public function testPrimaryKey()
  191. {
  192. $table = new Table([
  193. 'table' => 'users',
  194. 'schema' => [
  195. 'id' => ['type' => 'integer'],
  196. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  197. ]
  198. ]);
  199. $this->assertEquals('id', $table->primaryKey());
  200. $table->primaryKey('thingID');
  201. $this->assertEquals('thingID', $table->primaryKey());
  202. $table->primaryKey(['thingID', 'user_id']);
  203. $this->assertEquals(['thingID', 'user_id'], $table->primaryKey());
  204. }
  205. /**
  206. * Tests that name will be selected as a displayField
  207. *
  208. * @return void
  209. */
  210. public function testDisplayFieldName()
  211. {
  212. $table = new Table([
  213. 'table' => 'users',
  214. 'schema' => [
  215. 'foo' => ['type' => 'string'],
  216. 'name' => ['type' => 'string']
  217. ]
  218. ]);
  219. $this->assertEquals('name', $table->displayField());
  220. }
  221. /**
  222. * Tests that title will be selected as a displayField
  223. *
  224. * @return void
  225. */
  226. public function testDisplayFieldTitle()
  227. {
  228. $table = new Table([
  229. 'table' => 'users',
  230. 'schema' => [
  231. 'foo' => ['type' => 'string'],
  232. 'title' => ['type' => 'string']
  233. ]
  234. ]);
  235. $this->assertEquals('title', $table->displayField());
  236. }
  237. /**
  238. * Tests that no displayField will fallback to primary key
  239. *
  240. * @return void
  241. */
  242. public function testDisplayFallback()
  243. {
  244. $table = new Table([
  245. 'table' => 'users',
  246. 'schema' => [
  247. 'id' => ['type' => 'string'],
  248. 'foo' => ['type' => 'string'],
  249. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  250. ]
  251. ]);
  252. $this->assertEquals('id', $table->displayField());
  253. }
  254. /**
  255. * Tests that displayField can be changed
  256. *
  257. * @return void
  258. */
  259. public function testDisplaySet()
  260. {
  261. $table = new Table([
  262. 'table' => 'users',
  263. 'schema' => [
  264. 'id' => ['type' => 'string'],
  265. 'foo' => ['type' => 'string'],
  266. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  267. ]
  268. ]);
  269. $this->assertEquals('id', $table->displayField());
  270. $table->displayField('foo');
  271. $this->assertEquals('foo', $table->displayField());
  272. }
  273. /**
  274. * Tests schema method
  275. *
  276. * @return void
  277. */
  278. public function testSchema()
  279. {
  280. $schema = $this->connection->schemaCollection()->describe('users');
  281. $table = new Table([
  282. 'table' => 'users',
  283. 'connection' => $this->connection,
  284. ]);
  285. $this->assertEquals($schema, $table->schema());
  286. $table = new Table(['table' => 'stuff']);
  287. $table->schema($schema);
  288. $this->assertSame($schema, $table->schema());
  289. $table = new Table(['table' => 'another']);
  290. $schema = ['id' => ['type' => 'integer']];
  291. $table->schema($schema);
  292. $this->assertEquals(
  293. new \Cake\Database\Schema\Table('another', $schema),
  294. $table->schema()
  295. );
  296. }
  297. /**
  298. * Tests that _initializeSchema can be used to alter the database schema
  299. *
  300. * @return void
  301. */
  302. public function testSchemaInitialize()
  303. {
  304. $schema = $this->connection->schemaCollection()->describe('users');
  305. $table = $this->getMock('Cake\ORM\Table', ['_initializeSchema'], [
  306. ['table' => 'users', 'connection' => $this->connection]
  307. ]);
  308. $table->expects($this->once())
  309. ->method('_initializeSchema')
  310. ->with($schema)
  311. ->will($this->returnCallback(function ($schema) {
  312. $schema->columnType('username', 'integer');
  313. return $schema;
  314. }));
  315. $result = $table->schema();
  316. $schema->columnType('username', 'integer');
  317. $this->assertEquals($schema, $result);
  318. $this->assertEquals($schema, $table->schema(), '_initializeSchema should be called once');
  319. }
  320. /**
  321. * Tests that all fields for a table are added by default in a find when no
  322. * other fields are specified
  323. *
  324. * @return void
  325. */
  326. public function testFindAllNoFieldsAndNoHydration()
  327. {
  328. $table = new Table([
  329. 'table' => 'users',
  330. 'connection' => $this->connection,
  331. ]);
  332. $results = $table
  333. ->find('all')
  334. ->where(['id IN' => [1, 2]])
  335. ->order('id')
  336. ->hydrate(false)
  337. ->toArray();
  338. $expected = [
  339. [
  340. 'id' => 1,
  341. 'username' => 'mariano',
  342. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  343. 'created' => new Time('2007-03-17 01:16:23'),
  344. 'updated' => new Time('2007-03-17 01:18:31'),
  345. ],
  346. [
  347. 'id' => 2,
  348. 'username' => 'nate',
  349. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  350. 'created' => new Time('2008-03-17 01:18:23'),
  351. 'updated' => new Time('2008-03-17 01:20:31'),
  352. ],
  353. ];
  354. $this->assertEquals($expected, $results);
  355. }
  356. /**
  357. * Tests that it is possible to select only a few fields when finding over a table
  358. *
  359. * @return void
  360. */
  361. public function testFindAllSomeFieldsNoHydration()
  362. {
  363. $table = new Table([
  364. 'table' => 'users',
  365. 'connection' => $this->connection,
  366. ]);
  367. $results = $table->find('all')
  368. ->select(['username', 'password'])
  369. ->hydrate(false)
  370. ->order('username')->toArray();
  371. $expected = [
  372. ['username' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  373. ['username' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  374. ['username' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  375. ['username' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  376. ];
  377. $this->assertSame($expected, $results);
  378. $results = $table->find('all')
  379. ->select(['foo' => 'username', 'password'])
  380. ->order('username')
  381. ->hydrate(false)
  382. ->toArray();
  383. $expected = [
  384. ['foo' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  385. ['foo' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  386. ['foo' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  387. ['foo' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  388. ];
  389. $this->assertSame($expected, $results);
  390. }
  391. /**
  392. * Tests that the query will automatically casts complex conditions to the correct
  393. * types when the columns belong to the default table
  394. *
  395. * @return void
  396. */
  397. public function testFindAllConditionAutoTypes()
  398. {
  399. $table = new Table([
  400. 'table' => 'users',
  401. 'connection' => $this->connection,
  402. ]);
  403. $query = $table->find('all')
  404. ->select(['id', 'username'])
  405. ->where(['created >=' => new Time('2010-01-22 00:00')])
  406. ->hydrate(false)
  407. ->order('id');
  408. $expected = [
  409. ['id' => 3, 'username' => 'larry'],
  410. ['id' => 4, 'username' => 'garrett']
  411. ];
  412. $this->assertSame($expected, $query->toArray());
  413. $query->orWhere(['users.created' => new Time('2008-03-17 01:18:23')]);
  414. $expected = [
  415. ['id' => 2, 'username' => 'nate'],
  416. ['id' => 3, 'username' => 'larry'],
  417. ['id' => 4, 'username' => 'garrett']
  418. ];
  419. $this->assertSame($expected, $query->toArray());
  420. }
  421. /**
  422. * Test that beforeFind events can mutate the query.
  423. *
  424. * @return void
  425. */
  426. public function testFindBeforeFindEventMutateQuery()
  427. {
  428. $table = new Table([
  429. 'table' => 'users',
  430. 'connection' => $this->connection,
  431. ]);
  432. $table->eventManager()->on(
  433. 'Model.beforeFind',
  434. function ($event, $query, $options) {
  435. $query->limit(1);
  436. }
  437. );
  438. $result = $table->find('all')->all();
  439. $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
  440. }
  441. /**
  442. * Test that beforeFind events are fired and can stop the find and
  443. * return custom results.
  444. *
  445. * @return void
  446. */
  447. public function testFindBeforeFindEventOverrideReturn()
  448. {
  449. $table = new Table([
  450. 'table' => 'users',
  451. 'connection' => $this->connection,
  452. ]);
  453. $expected = ['One', 'Two', 'Three'];
  454. $table->eventManager()->on(
  455. 'Model.beforeFind',
  456. function ($event, $query, $options) use ($expected) {
  457. $query->setResult($expected);
  458. $event->stopPropagation();
  459. }
  460. );
  461. $query = $table->find('all');
  462. $query->limit(1);
  463. $this->assertEquals($expected, $query->all()->toArray());
  464. }
  465. /**
  466. * Tests that belongsTo() creates and configures correctly the association
  467. *
  468. * @return void
  469. */
  470. public function testBelongsTo()
  471. {
  472. $options = ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']];
  473. $table = new Table(['table' => 'dates']);
  474. $belongsTo = $table->belongsTo('user', $options);
  475. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  476. $this->assertSame($belongsTo, $table->association('user'));
  477. $this->assertEquals('user', $belongsTo->name());
  478. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  479. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  480. $this->assertSame($table, $belongsTo->source());
  481. }
  482. /**
  483. * Tests that hasOne() creates and configures correctly the association
  484. *
  485. * @return void
  486. */
  487. public function testHasOne()
  488. {
  489. $options = ['foreignKey' => 'user_id', 'conditions' => ['b' => 'c']];
  490. $table = new Table(['table' => 'users']);
  491. $hasOne = $table->hasOne('profile', $options);
  492. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  493. $this->assertSame($hasOne, $table->association('profile'));
  494. $this->assertEquals('profile', $hasOne->name());
  495. $this->assertEquals('user_id', $hasOne->foreignKey());
  496. $this->assertEquals(['b' => 'c'], $hasOne->conditions());
  497. $this->assertSame($table, $hasOne->source());
  498. }
  499. /**
  500. * Test has one with a plugin model
  501. *
  502. * @return void
  503. */
  504. public function testHasOnePlugin()
  505. {
  506. $options = ['className' => 'TestPlugin.Comments'];
  507. $table = new Table(['table' => 'users']);
  508. $hasOne = $table->hasOne('Comments', $options);
  509. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  510. $this->assertSame('Comments', $hasOne->name());
  511. $hasOneTable = $hasOne->target();
  512. $this->assertSame('Comments', $hasOne->alias());
  513. $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias());
  514. $options = ['className' => 'TestPlugin.Comments'];
  515. $table = new Table(['table' => 'users']);
  516. $hasOne = $table->hasOne('TestPlugin.Comments', $options);
  517. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  518. $this->assertSame('Comments', $hasOne->name());
  519. $hasOneTable = $hasOne->target();
  520. $this->assertSame('Comments', $hasOne->alias());
  521. $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias());
  522. }
  523. /**
  524. * testNoneUniqueAssociationsSameClass
  525. *
  526. * @return void
  527. */
  528. public function testNoneUniqueAssociationsSameClass()
  529. {
  530. $Users = new Table(['table' => 'users']);
  531. $options = ['className' => 'Comments'];
  532. $Users->hasMany('Comments', $options);
  533. $Articles = new Table(['table' => 'articles']);
  534. $options = ['className' => 'Comments'];
  535. $Articles->hasMany('Comments', $options);
  536. $Categories = new Table(['table' => 'categories']);
  537. $options = ['className' => 'TestPlugin.Comments'];
  538. $Categories->hasMany('Comments', $options);
  539. $this->assertInstanceOf('Cake\ORM\Table', $Users->Comments->target());
  540. $this->assertInstanceOf('Cake\ORM\Table', $Articles->Comments->target());
  541. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $Categories->Comments->target());
  542. }
  543. /**
  544. * Test associations which refer to the same table multiple times
  545. *
  546. * @return void
  547. */
  548. public function testSelfJoinAssociations()
  549. {
  550. $Categories = TableRegistry::get('Categories');
  551. $options = ['className' => 'Categories'];
  552. $Categories->hasMany('Children', ['foreignKey' => 'parent_id'] + $options);
  553. $Categories->belongsTo('Parent', $options);
  554. $this->assertSame('categories', $Categories->Children->target()->table());
  555. $this->assertSame('categories', $Categories->Parent->target()->table());
  556. $this->assertSame('Children', $Categories->Children->alias());
  557. $this->assertSame('Children', $Categories->Children->target()->alias());
  558. $this->assertSame('Parent', $Categories->Parent->alias());
  559. $this->assertSame('Parent', $Categories->Parent->target()->alias());
  560. $expected = [
  561. 'id' => 2,
  562. 'parent_id' => 1,
  563. 'name' => 'Category 1.1',
  564. 'parent' => [
  565. 'id' => 1,
  566. 'parent_id' => 0,
  567. 'name' => 'Category 1',
  568. ],
  569. 'children' => [
  570. [
  571. 'id' => 7,
  572. 'parent_id' => 2,
  573. 'name' => 'Category 1.1.1',
  574. ],
  575. [
  576. 'id' => 8,
  577. 'parent_id' => 2,
  578. 'name' => 'Category 1.1.2',
  579. ]
  580. ]
  581. ];
  582. $fields = ['id', 'parent_id', 'name'];
  583. $result = $Categories->find('all')
  584. ->select(['Categories.id', 'Categories.parent_id', 'Categories.name'])
  585. ->contain(['Children' => ['fields' => $fields], 'Parent' => ['fields' => $fields]])
  586. ->where(['Categories.id' => 2])
  587. ->first()
  588. ->toArray();
  589. $this->assertSame($expected, $result);
  590. }
  591. /**
  592. * Tests that hasMany() creates and configures correctly the association
  593. *
  594. * @return void
  595. */
  596. public function testHasMany()
  597. {
  598. $options = [
  599. 'foreignKey' => 'author_id',
  600. 'conditions' => ['b' => 'c'],
  601. 'sort' => ['foo' => 'asc']
  602. ];
  603. $table = new Table(['table' => 'authors']);
  604. $hasMany = $table->hasMany('article', $options);
  605. $this->assertInstanceOf('Cake\ORM\Association\HasMany', $hasMany);
  606. $this->assertSame($hasMany, $table->association('article'));
  607. $this->assertEquals('article', $hasMany->name());
  608. $this->assertEquals('author_id', $hasMany->foreignKey());
  609. $this->assertEquals(['b' => 'c'], $hasMany->conditions());
  610. $this->assertEquals(['foo' => 'asc'], $hasMany->sort());
  611. $this->assertSame($table, $hasMany->source());
  612. }
  613. /**
  614. * testHasManyWithClassName
  615. *
  616. * @return void
  617. */
  618. public function testHasManyWithClassName()
  619. {
  620. $table = TableRegistry::get('Articles');
  621. $table->hasMany('Comments', [
  622. 'className' => 'Comments',
  623. 'conditions' => ['published' => 'Y'],
  624. ]);
  625. $table->hasMany('UnapprovedComments', [
  626. 'className' => 'Comments',
  627. 'conditions' => ['published' => 'N'],
  628. 'propertyName' => 'unaproved_comments'
  629. ]);
  630. $expected = [
  631. 'id' => 1,
  632. 'title' => 'First Article',
  633. 'unaproved_comments' => [
  634. [
  635. 'id' => 4,
  636. 'article_id' => 1,
  637. 'comment' => 'Fourth Comment for First Article'
  638. ]
  639. ],
  640. 'comments' => [
  641. [
  642. 'id' => 1,
  643. 'article_id' => 1,
  644. 'comment' => 'First Comment for First Article'
  645. ],
  646. [
  647. 'id' => 2,
  648. 'article_id' => 1,
  649. 'comment' => 'Second Comment for First Article'
  650. ],
  651. [
  652. 'id' => 3,
  653. 'article_id' => 1,
  654. 'comment' => 'Third Comment for First Article'
  655. ]
  656. ]
  657. ];
  658. $result = $table->find()
  659. ->select(['id', 'title'])
  660. ->contain([
  661. 'Comments' => ['fields' => ['id', 'article_id', 'comment']],
  662. 'UnapprovedComments' => ['fields' => ['id', 'article_id', 'comment']]
  663. ])
  664. ->where(['id' => 1])
  665. ->first();
  666. $this->assertSame($expected, $result->toArray());
  667. }
  668. /**
  669. * Ensure associations use the plugin-prefixed model
  670. *
  671. * @return void
  672. */
  673. public function testHasManyPluginOverlap()
  674. {
  675. TableRegistry::get('Comments');
  676. Plugin::load('TestPlugin');
  677. $table = new Table(['table' => 'authors']);
  678. $table->hasMany('TestPlugin.Comments');
  679. $comments = $table->Comments->target();
  680. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  681. }
  682. /**
  683. * Ensure associations use the plugin-prefixed model
  684. * even if specified with config
  685. *
  686. * @return void
  687. */
  688. public function testHasManyPluginOverlapConfig()
  689. {
  690. TableRegistry::get('Comments');
  691. Plugin::load('TestPlugin');
  692. $table = new Table(['table' => 'authors']);
  693. $table->hasMany('Comments', ['className' => 'TestPlugin.Comments']);
  694. $comments = $table->Comments->target();
  695. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  696. }
  697. /**
  698. * Tests that BelongsToMany() creates and configures correctly the association
  699. *
  700. * @return void
  701. */
  702. public function testBelongsToMany()
  703. {
  704. $options = [
  705. 'foreignKey' => 'thing_id',
  706. 'joinTable' => 'things_tags',
  707. 'conditions' => ['b' => 'c'],
  708. 'sort' => ['foo' => 'asc']
  709. ];
  710. $table = new Table(['table' => 'authors', 'connection' => $this->connection]);
  711. $belongsToMany = $table->belongsToMany('tag', $options);
  712. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  713. $this->assertSame($belongsToMany, $table->association('tag'));
  714. $this->assertEquals('tag', $belongsToMany->name());
  715. $this->assertEquals('thing_id', $belongsToMany->foreignKey());
  716. $this->assertEquals(['b' => 'c'], $belongsToMany->conditions());
  717. $this->assertEquals(['foo' => 'asc'], $belongsToMany->sort());
  718. $this->assertSame($table, $belongsToMany->source());
  719. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  720. }
  721. /**
  722. * Test addAssociations()
  723. *
  724. * @return void
  725. */
  726. public function testAddAssociations()
  727. {
  728. $params = [
  729. 'belongsTo' => [
  730. 'users' => ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']]
  731. ],
  732. 'hasOne' => ['profiles'],
  733. 'hasMany' => ['authors'],
  734. 'belongsToMany' => [
  735. 'tags' => ['joinTable' => 'things_tags']
  736. ]
  737. ];
  738. $table = new Table(['table' => 'dates']);
  739. $table->addAssociations($params);
  740. $associations = $table->associations();
  741. $belongsTo = $associations->get('users');
  742. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  743. $this->assertEquals('users', $belongsTo->name());
  744. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  745. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  746. $this->assertSame($table, $belongsTo->source());
  747. $hasOne = $associations->get('profiles');
  748. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  749. $this->assertEquals('profiles', $hasOne->name());
  750. $hasMany = $associations->get('authors');
  751. $this->assertInstanceOf('Cake\ORM\Association\hasMany', $hasMany);
  752. $this->assertEquals('authors', $hasMany->name());
  753. $belongsToMany = $associations->get('tags');
  754. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  755. $this->assertEquals('tags', $belongsToMany->name());
  756. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  757. }
  758. /**
  759. * Test basic multi row updates.
  760. *
  761. * @return void
  762. */
  763. public function testUpdateAll()
  764. {
  765. $table = new Table([
  766. 'table' => 'users',
  767. 'connection' => $this->connection,
  768. ]);
  769. $fields = ['username' => 'mark'];
  770. $result = $table->updateAll($fields, ['id <' => 4]);
  771. $this->assertSame(3, $result);
  772. $result = $table->find('all')
  773. ->select(['username'])
  774. ->order(['id' => 'asc'])
  775. ->hydrate(false)
  776. ->toArray();
  777. $expected = array_fill(0, 3, $fields);
  778. $expected[] = ['username' => 'garrett'];
  779. $this->assertEquals($expected, $result);
  780. }
  781. /**
  782. * Test that exceptions from the Query bubble up.
  783. *
  784. * @expectedException \Cake\Database\Exception
  785. */
  786. public function testUpdateAllFailure()
  787. {
  788. $table = $this->getMock(
  789. 'Cake\ORM\Table',
  790. ['query'],
  791. [['table' => 'users', 'connection' => $this->connection]]
  792. );
  793. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  794. $table->expects($this->once())
  795. ->method('query')
  796. ->will($this->returnValue($query));
  797. $query->expects($this->once())
  798. ->method('execute')
  799. ->will($this->throwException(new Exception('Not good')));
  800. $table->updateAll(['username' => 'mark'], []);
  801. }
  802. /**
  803. * Test deleting many records.
  804. *
  805. * @return void
  806. */
  807. public function testDeleteAll()
  808. {
  809. $table = new Table([
  810. 'table' => 'users',
  811. 'connection' => $this->connection,
  812. ]);
  813. $result = $table->deleteAll(['id <' => 4]);
  814. $this->assertSame(3, $result);
  815. $result = $table->find('all')->toArray();
  816. $this->assertCount(1, $result, 'Only one record should remain');
  817. $this->assertEquals(4, $result[0]['id']);
  818. }
  819. /**
  820. * Test deleting many records with conditions using the alias
  821. *
  822. * @return void
  823. */
  824. public function testDeleteAllAliasedConditions()
  825. {
  826. $table = new Table([
  827. 'table' => 'users',
  828. 'alias' => 'Managers',
  829. 'connection' => $this->connection,
  830. ]);
  831. $result = $table->deleteAll(['Managers.id <' => 4]);
  832. $this->assertSame(3, $result);
  833. $result = $table->find('all')->toArray();
  834. $this->assertCount(1, $result, 'Only one record should remain');
  835. $this->assertEquals(4, $result[0]['id']);
  836. }
  837. /**
  838. * Test that exceptions from the Query bubble up.
  839. *
  840. * @expectedException \Cake\Database\Exception
  841. */
  842. public function testDeleteAllFailure()
  843. {
  844. $table = $this->getMock(
  845. 'Cake\ORM\Table',
  846. ['query'],
  847. [['table' => 'users', 'connection' => $this->connection]]
  848. );
  849. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  850. $table->expects($this->once())
  851. ->method('query')
  852. ->will($this->returnValue($query));
  853. $query->expects($this->once())
  854. ->method('execute')
  855. ->will($this->throwException(new Exception('Not good')));
  856. $table->deleteAll(['id >' => 4]);
  857. }
  858. /**
  859. * Tests that array options are passed to the query object using applyOptions
  860. *
  861. * @return void
  862. */
  863. public function testFindApplyOptions()
  864. {
  865. $table = $this->getMock(
  866. 'Cake\ORM\Table',
  867. ['query', 'findAll'],
  868. [['table' => 'users', 'connection' => $this->connection]]
  869. );
  870. $query = $this->getMock('Cake\ORM\Query', [], [$this->connection, $table]);
  871. $table->expects($this->once())
  872. ->method('query')
  873. ->will($this->returnValue($query));
  874. $options = ['fields' => ['a', 'b'], 'connections' => ['a >' => 1]];
  875. $query->expects($this->any())
  876. ->method('select')
  877. ->will($this->returnSelf());
  878. $query->expects($this->once())->method('getOptions')
  879. ->will($this->returnValue(['connections' => ['a >' => 1]]));
  880. $query->expects($this->once())
  881. ->method('applyOptions')
  882. ->with($options);
  883. $table->expects($this->once())->method('findAll')
  884. ->with($query, ['connections' => ['a >' => 1]]);
  885. $table->find('all', $options);
  886. }
  887. /**
  888. * Tests find('list')
  889. *
  890. * @return void
  891. */
  892. public function testFindListNoHydration()
  893. {
  894. $table = new Table([
  895. 'table' => 'users',
  896. 'connection' => $this->connection,
  897. ]);
  898. $table->displayField('username');
  899. $query = $table->find('list')
  900. ->hydrate(false)
  901. ->order('id');
  902. $expected = [
  903. 1 => 'mariano',
  904. 2 => 'nate',
  905. 3 => 'larry',
  906. 4 => 'garrett'
  907. ];
  908. $this->assertSame($expected, $query->toArray());
  909. $query = $table->find('list', ['fields' => ['id', 'username']])
  910. ->hydrate(false)
  911. ->order('id');
  912. $expected = [
  913. 1 => 'mariano',
  914. 2 => 'nate',
  915. 3 => 'larry',
  916. 4 => 'garrett'
  917. ];
  918. $this->assertSame($expected, $query->toArray());
  919. $query = $table->find('list', ['groupField' => 'odd'])
  920. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  921. ->hydrate(false)
  922. ->order('id');
  923. $expected = [
  924. 1 => [
  925. 1 => 'mariano',
  926. 3 => 'larry'
  927. ],
  928. 0 => [
  929. 2 => 'nate',
  930. 4 => 'garrett'
  931. ]
  932. ];
  933. $this->assertSame($expected, $query->toArray());
  934. }
  935. /**
  936. * Tests find('threaded')
  937. *
  938. * @return void
  939. */
  940. public function testFindThreadedNoHydration()
  941. {
  942. $table = new Table([
  943. 'table' => 'categories',
  944. 'connection' => $this->connection,
  945. ]);
  946. $expected = [
  947. [
  948. 'id' => 1,
  949. 'parent_id' => 0,
  950. 'name' => 'Category 1',
  951. 'children' => [
  952. [
  953. 'id' => 2,
  954. 'parent_id' => 1,
  955. 'name' => 'Category 1.1',
  956. 'children' => [
  957. [
  958. 'id' => 7,
  959. 'parent_id' => 2,
  960. 'name' => 'Category 1.1.1',
  961. 'children' => []
  962. ],
  963. [
  964. 'id' => 8,
  965. 'parent_id' => '2',
  966. 'name' => 'Category 1.1.2',
  967. 'children' => []
  968. ]
  969. ],
  970. ],
  971. [
  972. 'id' => 3,
  973. 'parent_id' => '1',
  974. 'name' => 'Category 1.2',
  975. 'children' => []
  976. ],
  977. ]
  978. ],
  979. [
  980. 'id' => 4,
  981. 'parent_id' => 0,
  982. 'name' => 'Category 2',
  983. 'children' => []
  984. ],
  985. [
  986. 'id' => 5,
  987. 'parent_id' => 0,
  988. 'name' => 'Category 3',
  989. 'children' => [
  990. [
  991. 'id' => '6',
  992. 'parent_id' => '5',
  993. 'name' => 'Category 3.1',
  994. 'children' => []
  995. ]
  996. ]
  997. ]
  998. ];
  999. $results = $table->find('all')
  1000. ->select(['id', 'parent_id', 'name'])
  1001. ->hydrate(false)
  1002. ->find('threaded')
  1003. ->toArray();
  1004. $this->assertEquals($expected, $results);
  1005. }
  1006. /**
  1007. * Tests that finders can be stacked
  1008. *
  1009. * @return void
  1010. */
  1011. public function testStackingFinders()
  1012. {
  1013. $table = $this->getMock('\Cake\ORM\Table', ['find', 'findList'], [], '', false);
  1014. $params = [$this->connection, $table];
  1015. $query = $this->getMock('\Cake\ORM\Query', ['addDefaultTypes'], $params);
  1016. $table->expects($this->once())
  1017. ->method('find')
  1018. ->with('threaded', ['order' => ['name' => 'ASC']])
  1019. ->will($this->returnValue($query));
  1020. $table->expects($this->once())
  1021. ->method('findList')
  1022. ->with($query, ['keyPath' => 'id'])
  1023. ->will($this->returnValue($query));
  1024. $result = $table
  1025. ->find('threaded', ['order' => ['name' => 'ASC']])
  1026. ->find('list', ['keyPath' => 'id']);
  1027. $this->assertSame($query, $result);
  1028. }
  1029. /**
  1030. * Tests find('threaded') with hydrated results
  1031. *
  1032. * @return void
  1033. */
  1034. public function testFindThreadedHydrated()
  1035. {
  1036. $table = new Table([
  1037. 'table' => 'categories',
  1038. 'connection' => $this->connection,
  1039. ]);
  1040. $results = $table->find('all')
  1041. ->find('threaded')
  1042. ->select(['id', 'parent_id', 'name'])
  1043. ->toArray();
  1044. $this->assertEquals(1, $results[0]->id);
  1045. $expected = [
  1046. 'id' => 8,
  1047. 'parent_id' => 2,
  1048. 'name' => 'Category 1.1.2',
  1049. 'children' => []
  1050. ];
  1051. $this->assertEquals($expected, $results[0]->children[0]->children[1]->toArray());
  1052. }
  1053. /**
  1054. * Tests find('list') with hydrated records
  1055. *
  1056. * @return void
  1057. */
  1058. public function testFindListHydrated()
  1059. {
  1060. $table = new Table([
  1061. 'table' => 'users',
  1062. 'connection' => $this->connection,
  1063. ]);
  1064. $table->displayField('username');
  1065. $query = $table
  1066. ->find('list', ['fields' => ['id', 'username']])
  1067. ->order('id');
  1068. $expected = [
  1069. 1 => 'mariano',
  1070. 2 => 'nate',
  1071. 3 => 'larry',
  1072. 4 => 'garrett'
  1073. ];
  1074. $this->assertSame($expected, $query->toArray());
  1075. $query = $table->find('list', ['groupField' => 'odd'])
  1076. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  1077. ->hydrate(true)
  1078. ->order('id');
  1079. $expected = [
  1080. 1 => [
  1081. 1 => 'mariano',
  1082. 3 => 'larry'
  1083. ],
  1084. 0 => [
  1085. 2 => 'nate',
  1086. 4 => 'garrett'
  1087. ]
  1088. ];
  1089. $this->assertSame($expected, $query->toArray());
  1090. }
  1091. /**
  1092. * Test that find('list') only selects required fields.
  1093. *
  1094. * @return void
  1095. */
  1096. public function testFindListSelectedFields()
  1097. {
  1098. $table = new Table([
  1099. 'table' => 'users',
  1100. 'connection' => $this->connection,
  1101. ]);
  1102. $table->displayField('username');
  1103. $query = $table->find('list');
  1104. $expected = ['id', 'username'];
  1105. $this->assertSame($expected, $query->clause('select'));
  1106. $query = $table->find('list', ['valueField' => function ($row) {
  1107. return $row->username;
  1108. }]);
  1109. $this->assertEmpty($query->clause('select'));
  1110. $expected = ['odd' => new QueryExpression('id % 2'), 'id', 'username'];
  1111. $query = $table->find('list', [
  1112. 'fields' => $expected,
  1113. 'groupField' => 'odd',
  1114. ]);
  1115. $this->assertSame($expected, $query->clause('select'));
  1116. $articles = new Table([
  1117. 'table' => 'articles',
  1118. 'connection' => $this->connection,
  1119. ]);
  1120. $query = $articles->find('list', ['groupField' => 'author_id']);
  1121. $expected = ['id', 'title', 'author_id'];
  1122. $this->assertSame($expected, $query->clause('select'));
  1123. $query = $articles->find('list', ['valueField' => ['author_id', 'title']])
  1124. ->order('id');
  1125. $expected = ['id', 'author_id', 'title'];
  1126. $this->assertSame($expected, $query->clause('select'));
  1127. $expected = [
  1128. 1 => '1;First Article',
  1129. 2 => '3;Second Article',
  1130. 3 => '1;Third Article',
  1131. ];
  1132. $this->assertSame($expected, $query->toArray());
  1133. }
  1134. /**
  1135. * test that find('list') does not auto add fields to select if using virtual properties
  1136. *
  1137. * @return void
  1138. */
  1139. public function testFindListWithVirtualField()
  1140. {
  1141. $table = new Table([
  1142. 'table' => 'users',
  1143. 'connection' => $this->connection,
  1144. 'entityClass' => '\TestApp\Model\Entity\VirtualUser'
  1145. ]);
  1146. $table->displayField('bonus');
  1147. $query = $table
  1148. ->find('list')
  1149. ->order('id');
  1150. $this->assertEmpty($query->clause('select'));
  1151. $expected = [
  1152. 1 => 'bonus',
  1153. 2 => 'bonus',
  1154. 3 => 'bonus',
  1155. 4 => 'bonus'
  1156. ];
  1157. $this->assertSame($expected, $query->toArray());
  1158. $query = $table->find('list', ['groupField' => 'odd']);
  1159. $this->assertEmpty($query->clause('select'));
  1160. }
  1161. /**
  1162. * Test find('list') with value field from associated table
  1163. *
  1164. * @return void
  1165. */
  1166. public function testFindListWithAssociatedTable()
  1167. {
  1168. $articles = new Table([
  1169. 'table' => 'articles',
  1170. 'connection' => $this->connection,
  1171. ]);
  1172. $articles->belongsTo('Authors');
  1173. $query = $articles->find('list', ['valueField' => 'author.name'])
  1174. ->contain(['Authors'])
  1175. ->order('articles.id');
  1176. $this->assertEmpty($query->clause('select'));
  1177. $expected = [
  1178. 1 => 'mariano',
  1179. 2 => 'larry',
  1180. 3 => 'mariano',
  1181. ];
  1182. $this->assertSame($expected, $query->toArray());
  1183. }
  1184. /**
  1185. * Test the default entityClass.
  1186. *
  1187. * @return void
  1188. */
  1189. public function testEntityClassDefault()
  1190. {
  1191. $table = new Table();
  1192. $this->assertEquals('\Cake\ORM\Entity', $table->entityClass());
  1193. }
  1194. /**
  1195. * Tests that using a simple string for entityClass will try to
  1196. * load the class from the App namespace
  1197. *
  1198. * @return void
  1199. */
  1200. public function testTableClassInApp()
  1201. {
  1202. $class = $this->getMockClass('\Cake\ORM\Entity');
  1203. if (!class_exists('TestApp\Model\Entity\TestUser')) {
  1204. class_alias($class, 'TestApp\Model\Entity\TestUser');
  1205. }
  1206. $table = new Table();
  1207. $this->assertEquals('TestApp\Model\Entity\TestUser', $table->entityClass('TestUser'));
  1208. }
  1209. /**
  1210. * Tests that using a simple string for entityClass will try to
  1211. * load the class from the Plugin namespace when using plugin notation
  1212. *
  1213. * @return void
  1214. */
  1215. public function testTableClassInPlugin()
  1216. {
  1217. $class = $this->getMockClass('\Cake\ORM\Entity');
  1218. if (!class_exists('MyPlugin\Model\Entity\SuperUser')) {
  1219. class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
  1220. }
  1221. $table = new Table();
  1222. $this->assertEquals(
  1223. 'MyPlugin\Model\Entity\SuperUser',
  1224. $table->entityClass('MyPlugin.SuperUser')
  1225. );
  1226. }
  1227. /**
  1228. * Tests that using a simple string for entityClass will throw an exception
  1229. * when the class does not exist in the namespace
  1230. *
  1231. * @expectedException \Cake\ORM\Exception\MissingEntityException
  1232. * @expectedExceptionMessage Entity class FooUser could not be found.
  1233. * @return void
  1234. */
  1235. public function testTableClassNonExisting()
  1236. {
  1237. $table = new Table;
  1238. $this->assertFalse($table->entityClass('FooUser'));
  1239. }
  1240. /**
  1241. * Tests getting the entityClass based on conventions for the entity
  1242. * namespace
  1243. *
  1244. * @return void
  1245. */
  1246. public function testTableClassConventionForAPP()
  1247. {
  1248. $table = new \TestApp\Model\Table\ArticlesTable;
  1249. $this->assertEquals('TestApp\Model\Entity\Article', $table->entityClass());
  1250. }
  1251. /**
  1252. * Tests setting a entity class object using the setter method
  1253. *
  1254. * @return void
  1255. */
  1256. public function testSetEntityClass()
  1257. {
  1258. $table = new Table;
  1259. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  1260. $table->entityClass($class);
  1261. $this->assertEquals($class, $table->entityClass());
  1262. }
  1263. /**
  1264. * Proves that associations, even though they are lazy loaded, will fetch
  1265. * records using the correct table class and hydrate with the correct entity
  1266. *
  1267. * @return void
  1268. */
  1269. public function testReciprocalBelongsToLoading()
  1270. {
  1271. $table = new \TestApp\Model\Table\ArticlesTable([
  1272. 'connection' => $this->connection,
  1273. ]);
  1274. $result = $table->find('all')->contain(['authors'])->first();
  1275. $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author);
  1276. }
  1277. /**
  1278. * Proves that associations, even though they are lazy loaded, will fetch
  1279. * records using the correct table class and hydrate with the correct entity
  1280. *
  1281. * @return void
  1282. */
  1283. public function testReciprocalHasManyLoading()
  1284. {
  1285. $table = new \TestApp\Model\Table\ArticlesTable([
  1286. 'connection' => $this->connection,
  1287. ]);
  1288. $result = $table->find('all')->contain(['authors' => ['articles']])->first();
  1289. $this->assertCount(2, $result->author->articles);
  1290. foreach ($result->author->articles as $article) {
  1291. $this->assertInstanceOf('TestApp\Model\Entity\Article', $article);
  1292. }
  1293. }
  1294. /**
  1295. * Tests that the correct table and entity are loaded for the join association in
  1296. * a belongsToMany setup
  1297. *
  1298. * @return void
  1299. */
  1300. public function testReciprocalBelongsToMany()
  1301. {
  1302. $table = new \TestApp\Model\Table\ArticlesTable([
  1303. 'connection' => $this->connection,
  1304. ]);
  1305. $result = $table->find('all')->contain(['tags'])->first();
  1306. $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]);
  1307. $this->assertInstanceOf(
  1308. 'TestApp\Model\Entity\ArticlesTag',
  1309. $result->tags[0]->_joinData
  1310. );
  1311. }
  1312. /**
  1313. * Tests that recently fetched entities are always clean
  1314. *
  1315. * @return void
  1316. */
  1317. public function testFindCleanEntities()
  1318. {
  1319. $table = new \TestApp\Model\Table\ArticlesTable([
  1320. 'connection' => $this->connection,
  1321. ]);
  1322. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1323. $this->assertCount(3, $results);
  1324. foreach ($results as $article) {
  1325. $this->assertFalse($article->dirty('id'));
  1326. $this->assertFalse($article->dirty('title'));
  1327. $this->assertFalse($article->dirty('author_id'));
  1328. $this->assertFalse($article->dirty('body'));
  1329. $this->assertFalse($article->dirty('published'));
  1330. $this->assertFalse($article->dirty('author'));
  1331. $this->assertFalse($article->author->dirty('id'));
  1332. $this->assertFalse($article->author->dirty('name'));
  1333. $this->assertFalse($article->dirty('tag'));
  1334. if ($article->tag) {
  1335. $this->assertFalse($article->tag[0]->_joinData->dirty('tag_id'));
  1336. }
  1337. }
  1338. }
  1339. /**
  1340. * Tests that recently fetched entities are marked as not new
  1341. *
  1342. * @return void
  1343. */
  1344. public function testFindPersistedEntities()
  1345. {
  1346. $table = new \TestApp\Model\Table\ArticlesTable([
  1347. 'connection' => $this->connection,
  1348. ]);
  1349. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1350. $this->assertCount(3, $results);
  1351. foreach ($results as $article) {
  1352. $this->assertFalse($article->isNew());
  1353. foreach ((array)$article->tag as $tag) {
  1354. $this->assertFalse($tag->isNew());
  1355. $this->assertFalse($tag->_joinData->isNew());
  1356. }
  1357. }
  1358. }
  1359. /**
  1360. * Tests the exists function
  1361. *
  1362. * @return void
  1363. */
  1364. public function testExists()
  1365. {
  1366. $table = TableRegistry::get('users');
  1367. $this->assertTrue($table->exists(['id' => 1]));
  1368. $this->assertFalse($table->exists(['id' => 501]));
  1369. $this->assertTrue($table->exists(['id' => 3, 'username' => 'larry']));
  1370. }
  1371. /**
  1372. * Test adding a behavior to a table.
  1373. *
  1374. * @return void
  1375. */
  1376. public function testAddBehavior()
  1377. {
  1378. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1379. $mock->expects($this->once())
  1380. ->method('load')
  1381. ->with('Sluggable');
  1382. $table = new Table([
  1383. 'table' => 'articles',
  1384. 'behaviors' => $mock
  1385. ]);
  1386. $table->addBehavior('Sluggable');
  1387. }
  1388. /**
  1389. * Test adding a behavior that is a duplicate.
  1390. *
  1391. * @return void
  1392. */
  1393. public function testAddBehaviorDuplicate()
  1394. {
  1395. $table = new Table(['table' => 'articles']);
  1396. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1397. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1398. try {
  1399. $table->addBehavior('Sluggable', ['thing' => 'thing']);
  1400. $this->fail('No exception raised');
  1401. } catch (\RuntimeException $e) {
  1402. $this->assertContains('The "Sluggable" alias has already been loaded', $e->getMessage());
  1403. }
  1404. }
  1405. /**
  1406. * Test removing a behavior from a table.
  1407. *
  1408. * @return void
  1409. */
  1410. public function testRemoveBehavior()
  1411. {
  1412. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1413. $mock->expects($this->once())
  1414. ->method('unload')
  1415. ->with('Sluggable');
  1416. $table = new Table([
  1417. 'table' => 'articles',
  1418. 'behaviors' => $mock
  1419. ]);
  1420. $table->removeBehavior('Sluggable');
  1421. }
  1422. /**
  1423. * Test getting a behavior instance from a table.
  1424. *
  1425. * @return void
  1426. */
  1427. public function testBehaviors()
  1428. {
  1429. $table = TableRegistry::get('article');
  1430. $result = $table->behaviors();
  1431. $this->assertInstanceOf('Cake\ORM\BehaviorRegistry', $result);
  1432. }
  1433. /**
  1434. * Ensure exceptions are raised on missing behaviors.
  1435. *
  1436. * @expectedException \Cake\ORM\Exception\MissingBehaviorException
  1437. */
  1438. public function testAddBehaviorMissing()
  1439. {
  1440. $table = TableRegistry::get('article');
  1441. $this->assertNull($table->addBehavior('NopeNotThere'));
  1442. }
  1443. /**
  1444. * Test mixin methods from behaviors.
  1445. *
  1446. * @return void
  1447. */
  1448. public function testCallBehaviorMethod()
  1449. {
  1450. $table = TableRegistry::get('article');
  1451. $table->addBehavior('Sluggable');
  1452. $this->assertEquals('some-value', $table->slugify('some value'));
  1453. }
  1454. /**
  1455. * Test you can alias a behavior method
  1456. *
  1457. * @return void
  1458. */
  1459. public function testCallBehaviorAliasedMethod()
  1460. {
  1461. $table = TableRegistry::get('article');
  1462. $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
  1463. $this->assertEquals('some-value', $table->wednesday('some value'));
  1464. }
  1465. /**
  1466. * Test finder methods from behaviors.
  1467. *
  1468. * @return void
  1469. */
  1470. public function testCallBehaviorFinder()
  1471. {
  1472. $table = TableRegistry::get('articles');
  1473. $table->addBehavior('Sluggable');
  1474. $query = $table->find('noSlug');
  1475. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1476. $this->assertNotEmpty($query->clause('where'));
  1477. }
  1478. /**
  1479. * testCallBehaviorAliasedFinder
  1480. *
  1481. * @return void
  1482. */
  1483. public function testCallBehaviorAliasedFinder()
  1484. {
  1485. $table = TableRegistry::get('articles');
  1486. $table->addBehavior('Sluggable', ['implementedFinders' => ['special' => 'findNoSlug']]);
  1487. $query = $table->find('special');
  1488. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1489. $this->assertNotEmpty($query->clause('where'));
  1490. }
  1491. /**
  1492. * Test implementedEvents
  1493. *
  1494. * @return void
  1495. */
  1496. public function testImplementedEvents()
  1497. {
  1498. $table = $this->getMock(
  1499. 'Cake\ORM\Table',
  1500. ['beforeFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete']
  1501. );
  1502. $result = $table->implementedEvents();
  1503. $expected = [
  1504. 'Model.beforeFind' => 'beforeFind',
  1505. 'Model.beforeSave' => 'beforeSave',
  1506. 'Model.afterSave' => 'afterSave',
  1507. 'Model.beforeDelete' => 'beforeDelete',
  1508. 'Model.afterDelete' => 'afterDelete',
  1509. ];
  1510. $this->assertEquals($expected, $result, 'Events do not match.');
  1511. }
  1512. /**
  1513. * Tests that it is possible to insert a new row using the save method
  1514. *
  1515. * @group save
  1516. * @return void
  1517. */
  1518. public function testSaveNewEntity()
  1519. {
  1520. $entity = new \Cake\ORM\Entity([
  1521. 'username' => 'superuser',
  1522. 'password' => 'root',
  1523. 'created' => new Time('2013-10-10 00:00'),
  1524. 'updated' => new Time('2013-10-10 00:00')
  1525. ]);
  1526. $table = TableRegistry::get('users');
  1527. $this->assertSame($entity, $table->save($entity));
  1528. $this->assertEquals($entity->id, self::$nextUserId);
  1529. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1530. $this->assertEquals($entity->toArray(), $row->toArray());
  1531. }
  1532. /**
  1533. * Test that saving a new empty entity does nothing.
  1534. *
  1535. * @group save
  1536. * @return void
  1537. */
  1538. public function testSaveNewEmptyEntity()
  1539. {
  1540. $entity = new \Cake\ORM\Entity();
  1541. $table = TableRegistry::get('users');
  1542. $this->assertFalse($table->save($entity));
  1543. }
  1544. /**
  1545. * Test that saving a new empty entity does not call exists.
  1546. *
  1547. * @group save
  1548. * @return void
  1549. */
  1550. public function testSaveNewEntityNoExists()
  1551. {
  1552. $table = $this->getMock(
  1553. 'Cake\ORM\Table',
  1554. ['exists'],
  1555. [[
  1556. 'connection' => $this->connection,
  1557. 'alias' => 'Users',
  1558. 'table' => 'users',
  1559. ]]
  1560. );
  1561. $entity = $table->newEntity(['username' => 'mark']);
  1562. $this->assertTrue($entity->isNew());
  1563. $table->expects($this->never())
  1564. ->method('exists');
  1565. $this->assertSame($entity, $table->save($entity));
  1566. }
  1567. /**
  1568. * Test that saving a new entity with a Primary Key set does call exists.
  1569. *
  1570. * @group save
  1571. * @return void
  1572. */
  1573. public function testSavePrimaryKeyEntityExists()
  1574. {
  1575. $this->skipIfSqlServer();
  1576. $table = $this->getMock(
  1577. 'Cake\ORM\Table',
  1578. ['exists'],
  1579. [
  1580. [
  1581. 'connection' => $this->connection,
  1582. 'alias' => 'Users',
  1583. 'table' => 'users',
  1584. ]
  1585. ]
  1586. );
  1587. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1588. $this->assertTrue($entity->isNew());
  1589. $table->expects($this->once())->method('exists');
  1590. $this->assertSame($entity, $table->save($entity));
  1591. }
  1592. /**
  1593. * Test that save works with replace saveStrategy and are not deleted once they are not null
  1594. *
  1595. * @return void
  1596. */
  1597. public function testSaveReplaceSaveStrategy()
  1598. {
  1599. $authors = new Table(
  1600. [
  1601. 'table' => 'authors',
  1602. 'alias' => 'Authors',
  1603. 'connection' => $this->connection,
  1604. 'entityClass' => 'Cake\ORM\Entity',
  1605. ]
  1606. );
  1607. $authors->hasMany('Articles', ['saveStrategy' => 'replace']);
  1608. $entity = $authors->newEntity([
  1609. 'name' => 'mylux',
  1610. 'articles' => [
  1611. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1612. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1613. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1614. ]
  1615. ], ['associated' => ['Articles']]);
  1616. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1617. $sizeArticles = count($entity->articles);
  1618. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1619. $articleId = $entity->articles[0]->id;
  1620. unset($entity->articles[0]);
  1621. $entity->dirty('articles', true);
  1622. $authors->save($entity, ['associated' => ['Articles']]);
  1623. $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1624. $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
  1625. }
  1626. /**
  1627. * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed
  1628. *
  1629. * @return void
  1630. */
  1631. public function testSaveReplaceSaveStrategyNotAdding()
  1632. {
  1633. $authors = new Table(
  1634. [
  1635. 'table' => 'authors',
  1636. 'alias' => 'Authors',
  1637. 'connection' => $this->connection,
  1638. 'entityClass' => 'Cake\ORM\Entity',
  1639. ]
  1640. );
  1641. $authors->hasMany('Articles', ['saveStrategy' => 'replace']);
  1642. $entity = $authors->newEntity([
  1643. 'name' => 'mylux',
  1644. 'articles' => [
  1645. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1646. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1647. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1648. ]
  1649. ], ['associated' => ['Articles']]);
  1650. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1651. $sizeArticles = count($entity->articles);
  1652. $this->assertCount($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
  1653. $entity->set('articles', []);
  1654. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1655. $this->assertCount(0, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
  1656. }
  1657. /**
  1658. * Test that save works with append saveStrategy not deleting or setting null anything
  1659. *
  1660. * @return void
  1661. */
  1662. public function testSaveAppendSaveStrategy()
  1663. {
  1664. $authors = new Table(
  1665. [
  1666. 'table' => 'authors',
  1667. 'alias' => 'Authors',
  1668. 'connection' => $this->connection,
  1669. 'entityClass' => 'Cake\ORM\Entity',
  1670. ]
  1671. );
  1672. $authors->hasMany('Articles', ['saveStrategy' => 'append']);
  1673. $entity = $authors->newEntity([
  1674. 'name' => 'mylux',
  1675. 'articles' => [
  1676. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1677. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1678. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1679. ]
  1680. ], ['associated' => ['Articles']]);
  1681. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1682. $sizeArticles = count($entity->articles);
  1683. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1684. $articleId = $entity->articles[0]->id;
  1685. unset($entity->articles[0]);
  1686. $entity->dirty('articles', true);
  1687. $authors->save($entity, ['associated' => ['Articles']]);
  1688. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1689. $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
  1690. }
  1691. /**
  1692. * Test that save has append as the default save strategy
  1693. *
  1694. * @return void
  1695. */
  1696. public function testSaveDefaultSaveStrategy()
  1697. {
  1698. $authors = new Table(
  1699. [
  1700. 'table' => 'authors',
  1701. 'alias' => 'Authors',
  1702. 'connection' => $this->connection,
  1703. 'entityClass' => 'Cake\ORM\Entity',
  1704. ]
  1705. );
  1706. $authors->hasMany('Articles', ['saveStrategy' => 'append']);
  1707. $this->assertEquals('append', $authors->association('articles')->saveStrategy());
  1708. }
  1709. /**
  1710. * Test that the associated entities are unlinked and deleted when they are dependent
  1711. *
  1712. * @return void
  1713. */
  1714. public function testSaveReplaceSaveStrategyDependent()
  1715. {
  1716. $authors = new Table(
  1717. [
  1718. 'table' => 'authors',
  1719. 'alias' => 'Authors',
  1720. 'connection' => $this->connection,
  1721. 'entityClass' => 'Cake\ORM\Entity',
  1722. ]
  1723. );
  1724. $authors->hasMany('Articles', ['saveStrategy' => 'replace', 'dependent' => true]);
  1725. $entity = $authors->newEntity([
  1726. 'name' => 'mylux',
  1727. 'articles' => [
  1728. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1729. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1730. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1731. ]
  1732. ], ['associated' => ['Articles']]);
  1733. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1734. $sizeArticles = count($entity->articles);
  1735. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1736. $articleId = $entity->articles[0]->id;
  1737. unset($entity->articles[0]);
  1738. $entity->dirty('articles', true);
  1739. $authors->save($entity, ['associated' => ['Articles']]);
  1740. $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1741. $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
  1742. }
  1743. /**
  1744. * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  1745. *
  1746. * @return void
  1747. */
  1748. public function testSaveReplaceSaveStrategyNotNullable()
  1749. {
  1750. $articles = new Table(
  1751. [
  1752. 'table' => 'articles',
  1753. 'alias' => 'Articles',
  1754. 'connection' => $this->connection,
  1755. 'entityClass' => 'Cake\ORM\Entity',
  1756. ]
  1757. );
  1758. $articles->hasMany('Comments', ['saveStrategy' => 'replace']);
  1759. $article = $articles->newEntity([
  1760. 'title' => 'Bakeries are sky rocketing',
  1761. 'body' => 'All because of cake',
  1762. 'comments' => [
  1763. [
  1764. 'user_id' => 1,
  1765. 'comment' => 'That is true!'
  1766. ],
  1767. [
  1768. 'user_id' => 2,
  1769. 'comment' => 'Of course'
  1770. ]
  1771. ]
  1772. ], ['associated' => ['Comments']]);
  1773. $article = $articles->save($article, ['associated' => ['Comments']]);
  1774. $commentId = $article->comments[0]->id;
  1775. $sizeComments = count($article->comments);
  1776. $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1777. $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
  1778. unset($article->comments[0]);
  1779. $article->dirty('comments', true);
  1780. $article = $articles->save($article, ['associated' => ['Comments']]);
  1781. $this->assertEquals($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1782. $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
  1783. }
  1784. /**
  1785. * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  1786. *
  1787. * @return void
  1788. */
  1789. public function testSaveReplaceSaveStrategyAdding()
  1790. {
  1791. $articles = new Table(
  1792. [
  1793. 'table' => 'articles',
  1794. 'alias' => 'Articles',
  1795. 'connection' => $this->connection,
  1796. 'entityClass' => 'Cake\ORM\Entity',
  1797. ]
  1798. );
  1799. $articles->hasMany('Comments', ['saveStrategy' => 'replace']);
  1800. $article = $articles->newEntity([
  1801. 'title' => 'Bakeries are sky rocketing',
  1802. 'body' => 'All because of cake',
  1803. 'comments' => [
  1804. [
  1805. 'user_id' => 1,
  1806. 'comment' => 'That is true!'
  1807. ],
  1808. [
  1809. 'user_id' => 2,
  1810. 'comment' => 'Of course'
  1811. ]
  1812. ]
  1813. ], ['associated' => ['Comments']]);
  1814. $article = $articles->save($article, ['associated' => ['Comments']]);
  1815. $commentId = $article->comments[0]->id;
  1816. $sizeComments = count($article->comments);
  1817. $articleId = $article->id;
  1818. $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1819. $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
  1820. unset($article->comments[0]);
  1821. $article->comments[] = $articles->Comments->newEntity([
  1822. 'user_id' => 1,
  1823. 'comment' => 'new comment'
  1824. ]);
  1825. $article->dirty('comments', true);
  1826. $article = $articles->save($article, ['associated' => ['Comments']]);
  1827. $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1828. $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
  1829. $this->assertTrue($articles->Comments->exists(['comment' => 'new comment', 'article_id' => $articleId]));
  1830. }
  1831. /**
  1832. * Test that saving a new entity with a Primary Key set does not call exists when checkExisting is false.
  1833. *
  1834. * @group save
  1835. * @return void
  1836. */
  1837. public function testSavePrimaryKeyEntityNoExists()
  1838. {
  1839. $this->skipIfSqlServer();
  1840. $table = $this->getMock(
  1841. 'Cake\ORM\Table',
  1842. ['exists'],
  1843. [
  1844. [
  1845. 'connection' => $this->connection,
  1846. 'alias' => 'Users',
  1847. 'table' => 'users',
  1848. ]
  1849. ]
  1850. );
  1851. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1852. $this->assertTrue($entity->isNew());
  1853. $table->expects($this->never())->method('exists');
  1854. $this->assertSame($entity, $table->save($entity, ['checkExisting' => false]));
  1855. }
  1856. /**
  1857. * Tests that saving an entity will filter out properties that
  1858. * are not present in the table schema when saving
  1859. *
  1860. * @group save
  1861. * @return void
  1862. */
  1863. public function testSaveEntityOnlySchemaFields()
  1864. {
  1865. $entity = new \Cake\ORM\Entity([
  1866. 'username' => 'superuser',
  1867. 'password' => 'root',
  1868. 'crazyness' => 'super crazy value',
  1869. 'created' => new Time('2013-10-10 00:00'),
  1870. 'updated' => new Time('2013-10-10 00:00'),
  1871. ]);
  1872. $table = TableRegistry::get('users');
  1873. $this->assertSame($entity, $table->save($entity));
  1874. $this->assertEquals($entity->id, self::$nextUserId);
  1875. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1876. $entity->unsetProperty('crazyness');
  1877. $this->assertEquals($entity->toArray(), $row->toArray());
  1878. }
  1879. /**
  1880. * Tests that it is possible to modify data from the beforeSave callback
  1881. *
  1882. * @group save
  1883. * @return void
  1884. */
  1885. public function testBeforeSaveModifyData()
  1886. {
  1887. $table = TableRegistry::get('users');
  1888. $data = new \Cake\ORM\Entity([
  1889. 'username' => 'superuser',
  1890. 'created' => new Time('2013-10-10 00:00'),
  1891. 'updated' => new Time('2013-10-10 00:00')
  1892. ]);
  1893. $listener = function ($e, $entity, $options) use ($data) {
  1894. $this->assertSame($data, $entity);
  1895. $entity->set('password', 'foo');
  1896. };
  1897. $table->eventManager()->on('Model.beforeSave', $listener);
  1898. $this->assertSame($data, $table->save($data));
  1899. $this->assertEquals($data->id, self::$nextUserId);
  1900. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1901. $this->assertEquals('foo', $row->get('password'));
  1902. }
  1903. /**
  1904. * Tests that it is possible to modify the options array in beforeSave
  1905. *
  1906. * @group save
  1907. * @return void
  1908. */
  1909. public function testBeforeSaveModifyOptions()
  1910. {
  1911. $table = TableRegistry::get('users');
  1912. $data = new \Cake\ORM\Entity([
  1913. 'username' => 'superuser',
  1914. 'password' => 'foo',
  1915. 'created' => new Time('2013-10-10 00:00'),
  1916. 'updated' => new Time('2013-10-10 00:00')
  1917. ]);
  1918. $listener1 = function ($e, $entity, $options) {
  1919. $options['crazy'] = true;
  1920. };
  1921. $listener2 = function ($e, $entity, $options) {
  1922. $this->assertTrue($options['crazy']);
  1923. };
  1924. $table->eventManager()->on('Model.beforeSave', $listener1);
  1925. $table->eventManager()->on('Model.beforeSave', $listener2);
  1926. $this->assertSame($data, $table->save($data));
  1927. $this->assertEquals($data->id, self::$nextUserId);
  1928. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1929. $this->assertEquals($data->toArray(), $row->toArray());
  1930. }
  1931. /**
  1932. * Tests that it is possible to stop the saving altogether, without implying
  1933. * the save operation failed
  1934. *
  1935. * @group save
  1936. * @return void
  1937. */
  1938. public function testBeforeSaveStopEvent()
  1939. {
  1940. $table = TableRegistry::get('users');
  1941. $data = new \Cake\ORM\Entity([
  1942. 'username' => 'superuser',
  1943. 'created' => new Time('2013-10-10 00:00'),
  1944. 'updated' => new Time('2013-10-10 00:00')
  1945. ]);
  1946. $listener = function ($e, $entity) {
  1947. $e->stopPropagation();
  1948. return $entity;
  1949. };
  1950. $table->eventManager()->on('Model.beforeSave', $listener);
  1951. $this->assertSame($data, $table->save($data));
  1952. $this->assertNull($data->id);
  1953. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1954. $this->assertNull($row);
  1955. }
  1956. /**
  1957. * Asserts that afterSave callback is called on successful save
  1958. *
  1959. * @group save
  1960. * @return void
  1961. */
  1962. public function testAfterSave()
  1963. {
  1964. $table = TableRegistry::get('users');
  1965. $data = new \Cake\ORM\Entity([
  1966. 'username' => 'superuser',
  1967. 'created' => new Time('2013-10-10 00:00'),
  1968. 'updated' => new Time('2013-10-10 00:00')
  1969. ]);
  1970. $called = false;
  1971. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1972. $this->assertSame($data, $entity);
  1973. $this->assertTrue($entity->dirty());
  1974. $called = true;
  1975. };
  1976. $table->eventManager()->on('Model.afterSave', $listener);
  1977. $calledAfterCommit = false;
  1978. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1979. $this->assertSame($data, $entity);
  1980. $this->assertFalse($entity->dirty());
  1981. $calledAfterCommit = true;
  1982. };
  1983. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1984. $this->assertSame($data, $table->save($data));
  1985. $this->assertEquals($data->id, self::$nextUserId);
  1986. $this->assertTrue($called);
  1987. $this->assertTrue($calledAfterCommit);
  1988. }
  1989. /**
  1990. * Asserts that afterSaveCommit is also triggered for non-atomic saves
  1991. *
  1992. * @return void
  1993. */
  1994. public function testAfterSaveCommitForNonAtomic()
  1995. {
  1996. $table = TableRegistry::get('users');
  1997. $data = new \Cake\ORM\Entity([
  1998. 'username' => 'superuser',
  1999. 'created' => new Time('2013-10-10 00:00'),
  2000. 'updated' => new Time('2013-10-10 00:00')
  2001. ]);
  2002. $called = false;
  2003. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2004. $this->assertSame($data, $entity);
  2005. $called = true;
  2006. };
  2007. $table->eventManager()->on('Model.afterSave', $listener);
  2008. $calledAfterCommit = false;
  2009. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2010. $calledAfterCommit = true;
  2011. };
  2012. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2013. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  2014. $this->assertEquals($data->id, self::$nextUserId);
  2015. $this->assertTrue($called);
  2016. $this->assertTrue($calledAfterCommit);
  2017. }
  2018. /**
  2019. * Asserts the afterSaveCommit is not triggered if transaction is running.
  2020. *
  2021. * @return void
  2022. */
  2023. public function testAfterSaveCommitWithTransactionRunning()
  2024. {
  2025. $table = TableRegistry::get('users');
  2026. $data = new \Cake\ORM\Entity([
  2027. 'username' => 'superuser',
  2028. 'created' => new Time('2013-10-10 00:00'),
  2029. 'updated' => new Time('2013-10-10 00:00')
  2030. ]);
  2031. $called = false;
  2032. $listener = function ($e, $entity, $options) use (&$called) {
  2033. $called = true;
  2034. };
  2035. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  2036. $this->connection->begin();
  2037. $this->assertSame($data, $table->save($data));
  2038. $this->assertFalse($called);
  2039. $this->connection->commit();
  2040. }
  2041. /**
  2042. * Asserts the afterSaveCommit is not triggered if transaction is running.
  2043. *
  2044. * @return void
  2045. */
  2046. public function testAfterSaveCommitWithNonAtomicAndTransactionRunning()
  2047. {
  2048. $table = TableRegistry::get('users');
  2049. $data = new \Cake\ORM\Entity([
  2050. 'username' => 'superuser',
  2051. 'created' => new Time('2013-10-10 00:00'),
  2052. 'updated' => new Time('2013-10-10 00:00')
  2053. ]);
  2054. $called = false;
  2055. $listener = function ($e, $entity, $options) use (&$called) {
  2056. $called = true;
  2057. };
  2058. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  2059. $this->connection->begin();
  2060. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  2061. $this->assertFalse($called);
  2062. $this->connection->commit();
  2063. }
  2064. /**
  2065. * Asserts that afterSave callback not is called on unsuccessful save
  2066. *
  2067. * @group save
  2068. * @return void
  2069. */
  2070. public function testAfterSaveNotCalled()
  2071. {
  2072. $table = $this->getMock(
  2073. '\Cake\ORM\Table',
  2074. ['query'],
  2075. [['table' => 'users', 'connection' => $this->connection]]
  2076. );
  2077. $query = $this->getMock(
  2078. '\Cake\ORM\Query',
  2079. ['execute', 'addDefaultTypes'],
  2080. [null, $table]
  2081. );
  2082. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2083. $data = new \Cake\ORM\Entity([
  2084. 'username' => 'superuser',
  2085. 'created' => new Time('2013-10-10 00:00'),
  2086. 'updated' => new Time('2013-10-10 00:00')
  2087. ]);
  2088. $table->expects($this->once())->method('query')
  2089. ->will($this->returnValue($query));
  2090. $query->expects($this->once())->method('execute')
  2091. ->will($this->returnValue($statement));
  2092. $statement->expects($this->once())->method('rowCount')
  2093. ->will($this->returnValue(0));
  2094. $called = false;
  2095. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2096. $called = true;
  2097. };
  2098. $table->eventManager()->on('Model.afterSave', $listener);
  2099. $calledAfterCommit = false;
  2100. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2101. $calledAfterCommit = true;
  2102. };
  2103. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2104. $this->assertFalse($table->save($data));
  2105. $this->assertFalse($called);
  2106. $this->assertFalse($calledAfterCommit);
  2107. }
  2108. /**
  2109. * Asserts that afterSaveCommit callback is triggered only for primary table
  2110. *
  2111. * @group save
  2112. * @return void
  2113. */
  2114. public function testAfterSaveCommitTriggeredOnlyForPrimaryTable()
  2115. {
  2116. $entity = new \Cake\ORM\Entity([
  2117. 'title' => 'A Title',
  2118. 'body' => 'A body'
  2119. ]);
  2120. $entity->author = new \Cake\ORM\Entity([
  2121. 'name' => 'Jose'
  2122. ]);
  2123. $table = TableRegistry::get('articles');
  2124. $table->belongsTo('authors');
  2125. $calledForArticle = false;
  2126. $listenerForArticle = function ($e, $entity, $options) use (&$calledForArticle) {
  2127. $calledForArticle = true;
  2128. };
  2129. $table->eventManager()->on('Model.afterSaveCommit', $listenerForArticle);
  2130. $calledForAuthor = false;
  2131. $listenerForAuthor = function ($e, $entity, $options) use (&$calledForAuthor) {
  2132. $calledForAuthor = true;
  2133. };
  2134. $table->authors->eventManager()->on('Model.afterSaveCommit', $listenerForAuthor);
  2135. $this->assertSame($entity, $table->save($entity));
  2136. $this->assertFalse($entity->isNew());
  2137. $this->assertFalse($entity->author->isNew());
  2138. $this->assertTrue($calledForArticle);
  2139. $this->assertFalse($calledForAuthor);
  2140. }
  2141. /**
  2142. * Test that you cannot save rows without a primary key.
  2143. *
  2144. * @group save
  2145. * @expectedException \RuntimeException
  2146. * @expectedExceptionMessage Cannot insert row in "users" table, it has no primary key
  2147. * @return void
  2148. */
  2149. public function testSaveNewErrorOnNoPrimaryKey()
  2150. {
  2151. $entity = new \Cake\ORM\Entity(['username' => 'superuser']);
  2152. $table = TableRegistry::get('users', [
  2153. 'schema' => [
  2154. 'id' => ['type' => 'integer'],
  2155. 'username' => ['type' => 'string'],
  2156. ]
  2157. ]);
  2158. $table->save($entity);
  2159. }
  2160. /**
  2161. * Tests that save is wrapped around a transaction
  2162. *
  2163. * @group save
  2164. * @return void
  2165. */
  2166. public function testAtomicSave()
  2167. {
  2168. $config = ConnectionManager::config('test');
  2169. $connection = $this->getMock(
  2170. '\Cake\Database\Connection',
  2171. ['begin', 'commit'],
  2172. [$config]
  2173. );
  2174. $connection->driver($this->connection->driver());
  2175. $table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
  2176. $table->expects($this->any())->method('connection')
  2177. ->will($this->returnValue($connection));
  2178. $connection->expects($this->once())->method('begin');
  2179. $connection->expects($this->once())->method('commit');
  2180. $data = new \Cake\ORM\Entity([
  2181. 'username' => 'superuser',
  2182. 'created' => new Time('2013-10-10 00:00'),
  2183. 'updated' => new Time('2013-10-10 00:00')
  2184. ]);
  2185. $this->assertSame($data, $table->save($data));
  2186. }
  2187. /**
  2188. * Tests that save will rollback the transaction in the case of an exception
  2189. *
  2190. * @group save
  2191. * @expectedException \PDOException
  2192. * @return void
  2193. */
  2194. public function testAtomicSaveRollback()
  2195. {
  2196. $connection = $this->getMock(
  2197. '\Cake\Database\Connection',
  2198. ['begin', 'rollback'],
  2199. [ConnectionManager::config('test')]
  2200. );
  2201. $connection->driver(ConnectionManager::get('test')->driver());
  2202. $table = $this->getMock(
  2203. '\Cake\ORM\Table',
  2204. ['query', 'connection'],
  2205. [['table' => 'users']]
  2206. );
  2207. $query = $this->getMock(
  2208. '\Cake\ORM\Query',
  2209. ['execute', 'addDefaultTypes'],
  2210. [null, $table]
  2211. );
  2212. $table->expects($this->any())->method('connection')
  2213. ->will($this->returnValue($connection));
  2214. $table->expects($this->once())->method('query')
  2215. ->will($this->returnValue($query));
  2216. $connection->expects($this->once())->method('begin');
  2217. $connection->expects($this->once())->method('rollback');
  2218. $query->expects($this->once())->method('execute')
  2219. ->will($this->throwException(new \PDOException));
  2220. $data = new \Cake\ORM\Entity([
  2221. 'username' => 'superuser',
  2222. 'created' => new Time('2013-10-10 00:00'),
  2223. 'updated' => new Time('2013-10-10 00:00')
  2224. ]);
  2225. $table->save($data);
  2226. }
  2227. /**
  2228. * Tests that save will rollback the transaction in the case of an exception
  2229. *
  2230. * @group save
  2231. * @return void
  2232. */
  2233. public function testAtomicSaveRollbackOnFailure()
  2234. {
  2235. $connection = $this->getMock(
  2236. '\Cake\Database\Connection',
  2237. ['begin', 'rollback'],
  2238. [ConnectionManager::config('test')]
  2239. );
  2240. $connection->driver(ConnectionManager::get('test')->driver());
  2241. $table = $this->getMock(
  2242. '\Cake\ORM\Table',
  2243. ['query', 'connection', 'exists'],
  2244. [['table' => 'users']]
  2245. );
  2246. $query = $this->getMock(
  2247. '\Cake\ORM\Query',
  2248. ['execute', 'addDefaultTypes'],
  2249. [null, $table]
  2250. );
  2251. $table->expects($this->any())->method('connection')
  2252. ->will($this->returnValue($connection));
  2253. $table->expects($this->once())->method('query')
  2254. ->will($this->returnValue($query));
  2255. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2256. $statement->expects($this->once())
  2257. ->method('rowCount')
  2258. ->will($this->returnValue(0));
  2259. $connection->expects($this->once())->method('begin');
  2260. $connection->expects($this->once())->method('rollback');
  2261. $query->expects($this->once())
  2262. ->method('execute')
  2263. ->will($this->returnValue($statement));
  2264. $data = new \Cake\ORM\Entity([
  2265. 'username' => 'superuser',
  2266. 'created' => new Time('2013-10-10 00:00'),
  2267. 'updated' => new Time('2013-10-10 00:00')
  2268. ]);
  2269. $table->save($data);
  2270. }
  2271. /**
  2272. * Tests that only the properties marked as dirty are actually saved
  2273. * to the database
  2274. *
  2275. * @group save
  2276. * @return void
  2277. */
  2278. public function testSaveOnlyDirtyProperties()
  2279. {
  2280. $entity = new \Cake\ORM\Entity([
  2281. 'username' => 'superuser',
  2282. 'password' => 'root',
  2283. 'created' => new Time('2013-10-10 00:00'),
  2284. 'updated' => new Time('2013-10-10 00:00')
  2285. ]);
  2286. $entity->clean();
  2287. $entity->dirty('username', true);
  2288. $entity->dirty('created', true);
  2289. $entity->dirty('updated', true);
  2290. $table = TableRegistry::get('users');
  2291. $this->assertSame($entity, $table->save($entity));
  2292. $this->assertEquals($entity->id, self::$nextUserId);
  2293. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  2294. $entity->set('password', null);
  2295. $this->assertEquals($entity->toArray(), $row->toArray());
  2296. }
  2297. /**
  2298. * Tests that a recently saved entity is marked as clean
  2299. *
  2300. * @group save
  2301. * @return void
  2302. */
  2303. public function testASavedEntityIsClean()
  2304. {
  2305. $entity = new \Cake\ORM\Entity([
  2306. 'username' => 'superuser',
  2307. 'password' => 'root',
  2308. 'created' => new Time('2013-10-10 00:00'),
  2309. 'updated' => new Time('2013-10-10 00:00')
  2310. ]);
  2311. $table = TableRegistry::get('users');
  2312. $this->assertSame($entity, $table->save($entity));
  2313. $this->assertFalse($entity->dirty('usermane'));
  2314. $this->assertFalse($entity->dirty('password'));
  2315. $this->assertFalse($entity->dirty('created'));
  2316. $this->assertFalse($entity->dirty('updated'));
  2317. }
  2318. /**
  2319. * Tests that a recently saved entity is marked as not new
  2320. *
  2321. * @group save
  2322. * @return void
  2323. */
  2324. public function testASavedEntityIsNotNew()
  2325. {
  2326. $entity = new \Cake\ORM\Entity([
  2327. 'username' => 'superuser',
  2328. 'password' => 'root',
  2329. 'created' => new Time('2013-10-10 00:00'),
  2330. 'updated' => new Time('2013-10-10 00:00')
  2331. ]);
  2332. $table = TableRegistry::get('users');
  2333. $this->assertSame($entity, $table->save($entity));
  2334. $this->assertFalse($entity->isNew());
  2335. }
  2336. /**
  2337. * Tests that save can detect automatically if it needs to insert
  2338. * or update a row
  2339. *
  2340. * @group save
  2341. * @return void
  2342. */
  2343. public function testSaveUpdateAuto()
  2344. {
  2345. $entity = new \Cake\ORM\Entity([
  2346. 'id' => 2,
  2347. 'username' => 'baggins'
  2348. ]);
  2349. $table = TableRegistry::get('users');
  2350. $original = $table->find('all')->where(['id' => 2])->first();
  2351. $this->assertSame($entity, $table->save($entity));
  2352. $row = $table->find('all')->where(['id' => 2])->first();
  2353. $this->assertEquals('baggins', $row->username);
  2354. $this->assertEquals($original->password, $row->password);
  2355. $this->assertEquals($original->created, $row->created);
  2356. $this->assertEquals($original->updated, $row->updated);
  2357. $this->assertFalse($entity->isNew());
  2358. $this->assertFalse($entity->dirty('id'));
  2359. $this->assertFalse($entity->dirty('username'));
  2360. }
  2361. /**
  2362. * Tests that beforeFind gets the correct isNew() state for the entity
  2363. *
  2364. * @return void
  2365. */
  2366. public function testBeforeSaveGetsCorrectPersistance()
  2367. {
  2368. $entity = new \Cake\ORM\Entity([
  2369. 'id' => 2,
  2370. 'username' => 'baggins'
  2371. ]);
  2372. $table = TableRegistry::get('users');
  2373. $called = false;
  2374. $listener = function ($event, $entity) use (&$called) {
  2375. $this->assertFalse($entity->isNew());
  2376. $called = true;
  2377. };
  2378. $table->eventManager()->on('Model.beforeSave', $listener);
  2379. $this->assertSame($entity, $table->save($entity));
  2380. $this->assertTrue($called);
  2381. }
  2382. /**
  2383. * Tests that marking an entity as already persisted will prevent the save
  2384. * method from trying to infer the entity's actual status.
  2385. *
  2386. * @group save
  2387. * @return void
  2388. */
  2389. public function testSaveUpdateWithHint()
  2390. {
  2391. $table = $this->getMock(
  2392. '\Cake\ORM\Table',
  2393. ['exists'],
  2394. [['table' => 'users', 'connection' => ConnectionManager::get('test')]]
  2395. );
  2396. $entity = new \Cake\ORM\Entity([
  2397. 'id' => 2,
  2398. 'username' => 'baggins'
  2399. ], ['markNew' => false]);
  2400. $this->assertFalse($entity->isNew());
  2401. $table->expects($this->never())->method('exists');
  2402. $this->assertSame($entity, $table->save($entity));
  2403. }
  2404. /**
  2405. * Tests that when updating the primary key is not passed to the list of
  2406. * attributes to change
  2407. *
  2408. * @group save
  2409. * @return void
  2410. */
  2411. public function testSaveUpdatePrimaryKeyNotModified()
  2412. {
  2413. $table = $this->getMock(
  2414. '\Cake\ORM\Table',
  2415. ['query'],
  2416. [['table' => 'users', 'connection' => $this->connection]]
  2417. );
  2418. $query = $this->getMock(
  2419. '\Cake\ORM\Query',
  2420. ['execute', 'addDefaultTypes', 'set'],
  2421. [null, $table]
  2422. );
  2423. $table->expects($this->once())->method('query')
  2424. ->will($this->returnValue($query));
  2425. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2426. $statement->expects($this->once())
  2427. ->method('errorCode')
  2428. ->will($this->returnValue('00000'));
  2429. $query->expects($this->once())
  2430. ->method('execute')
  2431. ->will($this->returnValue($statement));
  2432. $query->expects($this->once())->method('set')
  2433. ->with(['username' => 'baggins'])
  2434. ->will($this->returnValue($query));
  2435. $entity = new \Cake\ORM\Entity([
  2436. 'id' => 2,
  2437. 'username' => 'baggins'
  2438. ], ['markNew' => false]);
  2439. $this->assertSame($entity, $table->save($entity));
  2440. }
  2441. /**
  2442. * Tests that passing only the primary key to save will not execute any queries
  2443. * but still return success
  2444. *
  2445. * @group save
  2446. * @return void
  2447. */
  2448. public function testUpdateNoChange()
  2449. {
  2450. $table = $this->getMock(
  2451. '\Cake\ORM\Table',
  2452. ['query'],
  2453. [['table' => 'users', 'connection' => $this->connection]]
  2454. );
  2455. $table->expects($this->never())->method('query');
  2456. $entity = new \Cake\ORM\Entity([
  2457. 'id' => 2,
  2458. ], ['markNew' => false]);
  2459. $this->assertSame($entity, $table->save($entity));
  2460. }
  2461. /**
  2462. * Tests that passing only the primary key to save will not execute any queries
  2463. * but still return success
  2464. *
  2465. * @group save
  2466. * @group integration
  2467. * @return void
  2468. */
  2469. public function testUpdateDirtyNoActualChanges()
  2470. {
  2471. $table = TableRegistry::get('Articles');
  2472. $entity = $table->get(1);
  2473. $entity->accessible('*', true);
  2474. $entity->set($entity->toArray());
  2475. $this->assertSame($entity, $table->save($entity));
  2476. }
  2477. /**
  2478. * Tests that failing to pass a primary key to save will result in exception
  2479. *
  2480. * @group save
  2481. * @expectedException \InvalidArgumentException
  2482. * @return void
  2483. */
  2484. public function testUpdateNoPrimaryButOtherKeys()
  2485. {
  2486. $table = $this->getMock(
  2487. '\Cake\ORM\Table',
  2488. ['query'],
  2489. [['table' => 'users', 'connection' => $this->connection]]
  2490. );
  2491. $table->expects($this->never())->method('query');
  2492. $entity = new \Cake\ORM\Entity([
  2493. 'username' => 'mariano',
  2494. ], ['markNew' => false]);
  2495. $this->assertSame($entity, $table->save($entity));
  2496. }
  2497. /**
  2498. * Test simple delete.
  2499. *
  2500. * @return void
  2501. */
  2502. public function testDelete()
  2503. {
  2504. $table = TableRegistry::get('users');
  2505. $conditions = [
  2506. 'limit' => 1,
  2507. 'conditions' => [
  2508. 'username' => 'nate'
  2509. ]
  2510. ];
  2511. $query = $table->find('all', $conditions);
  2512. $entity = $query->first();
  2513. $result = $table->delete($entity);
  2514. $this->assertTrue($result);
  2515. $query = $table->find('all', $conditions);
  2516. $results = $query->execute();
  2517. $this->assertCount(0, $results, 'Find should fail.');
  2518. }
  2519. /**
  2520. * Test delete with dependent records
  2521. *
  2522. * @return void
  2523. */
  2524. public function testDeleteDependent()
  2525. {
  2526. $table = TableRegistry::get('authors');
  2527. $table->hasOne('articles', [
  2528. 'foreignKey' => 'author_id',
  2529. 'dependent' => true,
  2530. ]);
  2531. $entity = $table->get(1);
  2532. $result = $table->delete($entity);
  2533. $articles = $table->association('articles')->target();
  2534. $query = $articles->find('all', [
  2535. 'conditions' => [
  2536. 'author_id' => $entity->id
  2537. ]
  2538. ]);
  2539. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2540. }
  2541. /**
  2542. * Test delete with dependent records
  2543. *
  2544. * @return void
  2545. */
  2546. public function testDeleteDependentHasMany()
  2547. {
  2548. $table = TableRegistry::get('authors');
  2549. $table->hasMany('articles', [
  2550. 'foreignKey' => 'author_id',
  2551. 'dependent' => true,
  2552. 'cascadeCallbacks' => true,
  2553. ]);
  2554. $entity = $table->get(1);
  2555. $result = $table->delete($entity);
  2556. $this->assertTrue($result);
  2557. }
  2558. /**
  2559. * Test delete with dependent = false does not cascade.
  2560. *
  2561. * @return void
  2562. */
  2563. public function testDeleteNoDependentNoCascade()
  2564. {
  2565. $table = TableRegistry::get('authors');
  2566. $table->hasMany('article', [
  2567. 'foreignKey' => 'author_id',
  2568. 'dependent' => false,
  2569. ]);
  2570. $query = $table->find('all')->where(['id' => 1]);
  2571. $entity = $query->first();
  2572. $result = $table->delete($entity);
  2573. $articles = $table->association('articles')->target();
  2574. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  2575. $this->assertCount(2, $query->execute(), 'Should find rows.');
  2576. }
  2577. /**
  2578. * Test delete with BelongsToMany
  2579. *
  2580. * @return void
  2581. */
  2582. public function testDeleteBelongsToMany()
  2583. {
  2584. $table = TableRegistry::get('articles');
  2585. $table->belongsToMany('tag', [
  2586. 'foreignKey' => 'article_id',
  2587. 'joinTable' => 'articles_tags'
  2588. ]);
  2589. $query = $table->find('all')->where(['id' => 1]);
  2590. $entity = $query->first();
  2591. $table->delete($entity);
  2592. $junction = $table->association('tags')->junction();
  2593. $query = $junction->find('all')->where(['article_id' => 1]);
  2594. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2595. }
  2596. /**
  2597. * Test delete with dependent records belonging to an aliased
  2598. * belongsToMany association.
  2599. *
  2600. * @return void
  2601. */
  2602. public function testDeleteDependentAliased()
  2603. {
  2604. $Authors = TableRegistry::get('authors');
  2605. $Authors->associations()->removeAll();
  2606. $Articles = TableRegistry::get('articles');
  2607. $Articles->associations()->removeAll();
  2608. $Authors->hasMany('AliasedArticles', [
  2609. 'className' => 'articles',
  2610. 'dependent' => true,
  2611. 'cascadeCallbacks' => true
  2612. ]);
  2613. $Articles->belongsToMany('Tags');
  2614. $author = $Authors->get(1);
  2615. $result = $Authors->delete($author);
  2616. $this->assertTrue($result);
  2617. }
  2618. /**
  2619. * Test that cascading associations are deleted first.
  2620. *
  2621. * @return void
  2622. */
  2623. public function testDeleteAssociationsCascadingCallbacksOrder()
  2624. {
  2625. $groups = TableRegistry::get('Groups');
  2626. $members = TableRegistry::get('Members');
  2627. $groupsMembers = TableRegistry::get('GroupsMembers');
  2628. $groups->belongsToMany('Members');
  2629. $groups->hasMany('GroupsMembers', [
  2630. 'dependent' => true,
  2631. 'cascadeCallbacks' => true,
  2632. ]);
  2633. $groupsMembers->belongsTo('Members');
  2634. $groupsMembers->addBehavior('CounterCache', [
  2635. 'Members' => ['group_count']
  2636. ]);
  2637. $member = $members->get(1);
  2638. $this->assertEquals(2, $member->group_count);
  2639. $group = $groups->get(1);
  2640. $groups->delete($group);
  2641. $member = $members->get(1);
  2642. $this->assertEquals(1, $member->group_count);
  2643. }
  2644. /**
  2645. * Test delete callbacks
  2646. *
  2647. * @return void
  2648. */
  2649. public function testDeleteCallbacks()
  2650. {
  2651. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2652. $options = new \ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]);
  2653. $mock = $this->getMock('Cake\Event\EventManager');
  2654. $mock->expects($this->at(0))
  2655. ->method('on');
  2656. $mock->expects($this->at(1))
  2657. ->method('dispatch');
  2658. $mock->expects($this->at(2))
  2659. ->method('dispatch')
  2660. ->with($this->logicalAnd(
  2661. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  2662. $this->attributeEqualTo(
  2663. 'data',
  2664. ['entity' => $entity, 'options' => $options]
  2665. )
  2666. ));
  2667. $mock->expects($this->at(3))
  2668. ->method('dispatch')
  2669. ->with($this->logicalAnd(
  2670. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  2671. $this->attributeEqualTo(
  2672. 'data',
  2673. ['entity' => $entity, 'options' => $options]
  2674. )
  2675. ));
  2676. $mock->expects($this->at(4))
  2677. ->method('dispatch')
  2678. ->with($this->logicalAnd(
  2679. $this->attributeEqualTo('_name', 'Model.afterDeleteCommit'),
  2680. $this->attributeEqualTo(
  2681. 'data',
  2682. ['entity' => $entity, 'options' => $options]
  2683. )
  2684. ));
  2685. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2686. $entity->isNew(false);
  2687. $table->delete($entity, ['checkRules' => false]);
  2688. }
  2689. /**
  2690. * Test afterDeleteCommit is also called for non-atomic delete
  2691. *
  2692. * @return void
  2693. */
  2694. public function testDeleteCallbacksNonAtomic()
  2695. {
  2696. $table = TableRegistry::get('users');
  2697. $data = $table->get(1);
  2698. $options = new \ArrayObject(['atomic' => false, 'checkRules' => false]);
  2699. $called = false;
  2700. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2701. $this->assertSame($data, $entity);
  2702. $called = true;
  2703. };
  2704. $table->eventManager()->on('Model.afterDelete', $listener);
  2705. $calledAfterCommit = false;
  2706. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2707. $calledAfterCommit = true;
  2708. };
  2709. $table->eventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit);
  2710. $table->delete($data, ['atomic' => false]);
  2711. $this->assertTrue($called);
  2712. $this->assertTrue($calledAfterCommit);
  2713. }
  2714. /**
  2715. * Test that afterDeleteCommit is only triggered for primary table
  2716. *
  2717. * @return void
  2718. */
  2719. public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable()
  2720. {
  2721. $table = TableRegistry::get('authors');
  2722. $table->hasOne('articles', [
  2723. 'foreignKey' => 'author_id',
  2724. 'dependent' => true,
  2725. ]);
  2726. $called = false;
  2727. $listener = function ($e, $entity, $options) use (&$called) {
  2728. $called = true;
  2729. };
  2730. $table->eventManager()->on('Model.afterDeleteCommit', $listener);
  2731. $called2 = false;
  2732. $listener = function ($e, $entity, $options) use (&$called2) {
  2733. $called2 = true;
  2734. };
  2735. $table->articles->eventManager()->on('Model.afterDeleteCommit', $listener);
  2736. $entity = $table->get(1);
  2737. $this->assertTrue($table->delete($entity));
  2738. $this->assertTrue($called);
  2739. $this->assertFalse($called2);
  2740. }
  2741. /**
  2742. * Test delete beforeDelete can abort the delete.
  2743. *
  2744. * @return void
  2745. */
  2746. public function testDeleteBeforeDeleteAbort()
  2747. {
  2748. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2749. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2750. $mock = $this->getMock('Cake\Event\EventManager');
  2751. $mock->expects($this->at(2))
  2752. ->method('dispatch')
  2753. ->will($this->returnCallback(function ($event) {
  2754. $event->stopPropagation();
  2755. }));
  2756. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2757. $entity->isNew(false);
  2758. $result = $table->delete($entity, ['checkRules' => false]);
  2759. $this->assertNull($result);
  2760. }
  2761. /**
  2762. * Test delete beforeDelete return result
  2763. *
  2764. * @return void
  2765. */
  2766. public function testDeleteBeforeDeleteReturnResult()
  2767. {
  2768. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2769. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2770. $mock = $this->getMock('Cake\Event\EventManager');
  2771. $mock->expects($this->at(2))
  2772. ->method('dispatch')
  2773. ->will($this->returnCallback(function ($event) {
  2774. $event->stopPropagation();
  2775. $event->result = 'got stopped';
  2776. }));
  2777. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2778. $entity->isNew(false);
  2779. $result = $table->delete($entity, ['checkRules' => false]);
  2780. $this->assertEquals('got stopped', $result);
  2781. }
  2782. /**
  2783. * Test deleting new entities does nothing.
  2784. *
  2785. * @return void
  2786. */
  2787. public function testDeleteIsNew()
  2788. {
  2789. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2790. $table = $this->getMock(
  2791. 'Cake\ORM\Table',
  2792. ['query'],
  2793. [['connection' => $this->connection]]
  2794. );
  2795. $table->expects($this->never())
  2796. ->method('query');
  2797. $entity->isNew(true);
  2798. $result = $table->delete($entity);
  2799. $this->assertFalse($result);
  2800. }
  2801. /**
  2802. * test hasField()
  2803. *
  2804. * @return void
  2805. */
  2806. public function testHasField()
  2807. {
  2808. $table = TableRegistry::get('articles');
  2809. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  2810. $this->assertTrue($table->hasField('title'), 'Should be there.');
  2811. $this->assertTrue($table->hasField('body'), 'Should be there.');
  2812. }
  2813. /**
  2814. * Tests that there exists a default validator
  2815. *
  2816. * @return void
  2817. */
  2818. public function testValidatorDefault()
  2819. {
  2820. $table = new Table();
  2821. $validator = $table->validator();
  2822. $this->assertSame($table, $validator->provider('table'));
  2823. $this->assertInstanceOf('Cake\Validation\Validator', $validator);
  2824. $default = $table->validator('default');
  2825. $this->assertSame($validator, $default);
  2826. }
  2827. /**
  2828. * Tests that it is possible to define custom validator methods
  2829. *
  2830. * @return void
  2831. */
  2832. public function functionTestValidationWithDefiner()
  2833. {
  2834. $table = $this->getMock('\Cake\ORM\Table', ['validationForOtherStuff']);
  2835. $table->expects($this->once())->method('validationForOtherStuff')
  2836. ->will($this->returnArgument(0));
  2837. $other = $table->validator('forOtherStuff');
  2838. $this->assertInstanceOf('Cake\Validation\Validator', $other);
  2839. $this->assertNotSame($other, $table->validator());
  2840. $this->assertSame($table, $other->provider('table'));
  2841. }
  2842. /**
  2843. * Tests that it is possible to set a custom validator under a name
  2844. *
  2845. * @return void
  2846. */
  2847. public function testValidatorSetter()
  2848. {
  2849. $table = new Table;
  2850. $validator = new \Cake\Validation\Validator;
  2851. $table->validator('other', $validator);
  2852. $this->assertSame($validator, $table->validator('other'));
  2853. $this->assertSame($table, $validator->provider('table'));
  2854. }
  2855. /**
  2856. * Tests that the source of an existing Entity is the same as a new one
  2857. *
  2858. * @return void
  2859. */
  2860. public function testEntitySourceExistingAndNew()
  2861. {
  2862. Plugin::load('TestPlugin');
  2863. $table = TableRegistry::get('TestPlugin.Authors');
  2864. $existingAuthor = $table->find()->first();
  2865. $newAuthor = $table->newEntity();
  2866. $this->assertEquals('TestPlugin.Authors', $existingAuthor->source());
  2867. $this->assertEquals('TestPlugin.Authors', $newAuthor->source());
  2868. }
  2869. /**
  2870. * Tests that calling an entity with an empty array will run validation
  2871. * whereas calling it with no parameters will not run any validation.
  2872. *
  2873. * @return void
  2874. */
  2875. public function testNewEntityAndValidation()
  2876. {
  2877. $table = TableRegistry::get('Articles');
  2878. $validator = $table->validator()->requirePresence('title');
  2879. $entity = $table->newEntity([]);
  2880. $errors = $entity->errors();
  2881. $this->assertNotEmpty($errors['title']);
  2882. $entity = $table->newEntity();
  2883. $this->assertEmpty($entity->errors());
  2884. }
  2885. /**
  2886. * Test magic findByXX method.
  2887. *
  2888. * @return void
  2889. */
  2890. public function testMagicFindDefaultToAll()
  2891. {
  2892. $table = TableRegistry::get('Users');
  2893. $result = $table->findByUsername('garrett');
  2894. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2895. $expected = new QueryExpression(['Users.username' => 'garrett'], $this->usersTypeMap);
  2896. $this->assertEquals($expected, $result->clause('where'));
  2897. }
  2898. /**
  2899. * Test magic findByXX errors on missing arguments.
  2900. *
  2901. * @expectedException \BadMethodCallException
  2902. * @expectedExceptionMessage Not enough arguments for magic finder. Got 0 required 1
  2903. * @return void
  2904. */
  2905. public function testMagicFindError()
  2906. {
  2907. $table = TableRegistry::get('Users');
  2908. $table->findByUsername();
  2909. }
  2910. /**
  2911. * Test magic findByXX errors on missing arguments.
  2912. *
  2913. * @expectedException \BadMethodCallException
  2914. * @expectedExceptionMessage Not enough arguments for magic finder. Got 1 required 2
  2915. * @return void
  2916. */
  2917. public function testMagicFindErrorMissingField()
  2918. {
  2919. $table = TableRegistry::get('Users');
  2920. $table->findByUsernameAndId('garrett');
  2921. }
  2922. /**
  2923. * Test magic findByXX errors when there is a mix of or & and.
  2924. *
  2925. * @expectedException \BadMethodCallException
  2926. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  2927. * @return void
  2928. */
  2929. public function testMagicFindErrorMixOfOperators()
  2930. {
  2931. $table = TableRegistry::get('Users');
  2932. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  2933. }
  2934. /**
  2935. * Test magic findByXX method.
  2936. *
  2937. * @return void
  2938. */
  2939. public function testMagicFindFirstAnd()
  2940. {
  2941. $table = TableRegistry::get('Users');
  2942. $result = $table->findByUsernameAndId('garrett', 4);
  2943. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2944. $expected = new QueryExpression(['Users.username' => 'garrett', 'Users.id' => 4], $this->usersTypeMap);
  2945. $this->assertEquals($expected, $result->clause('where'));
  2946. }
  2947. /**
  2948. * Test magic findByXX method.
  2949. *
  2950. * @return void
  2951. */
  2952. public function testMagicFindFirstOr()
  2953. {
  2954. $table = TableRegistry::get('Users');
  2955. $result = $table->findByUsernameOrId('garrett', 4);
  2956. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2957. $expected = new QueryExpression([], $this->usersTypeMap);
  2958. $expected->add(
  2959. [
  2960. 'OR' => [
  2961. 'Users.username' => 'garrett',
  2962. 'Users.id' => 4
  2963. ]]
  2964. );
  2965. $this->assertEquals($expected, $result->clause('where'));
  2966. }
  2967. /**
  2968. * Test magic findAllByXX method.
  2969. *
  2970. * @return void
  2971. */
  2972. public function testMagicFindAll()
  2973. {
  2974. $table = TableRegistry::get('Articles');
  2975. $result = $table->findAllByAuthorId(1);
  2976. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2977. $this->assertNull($result->clause('limit'));
  2978. $expected = new QueryExpression(['Articles.author_id' => 1], $this->articlesTypeMap);
  2979. $this->assertEquals($expected, $result->clause('where'));
  2980. }
  2981. /**
  2982. * Test magic findAllByXX method.
  2983. *
  2984. * @return void
  2985. */
  2986. public function testMagicFindAllAnd()
  2987. {
  2988. $table = TableRegistry::get('Users');
  2989. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  2990. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2991. $this->assertNull($result->clause('limit'));
  2992. $expected = new QueryExpression(
  2993. ['Users.author_id' => 1, 'Users.published' => 'Y'],
  2994. $this->usersTypeMap
  2995. );
  2996. $this->assertEquals($expected, $result->clause('where'));
  2997. }
  2998. /**
  2999. * Test magic findAllByXX method.
  3000. *
  3001. * @return void
  3002. */
  3003. public function testMagicFindAllOr()
  3004. {
  3005. $table = TableRegistry::get('Users');
  3006. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  3007. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3008. $this->assertNull($result->clause('limit'));
  3009. $expected = new QueryExpression();
  3010. $expected->typeMap()->defaults($this->usersTypeMap->toArray());
  3011. $expected->add(
  3012. ['or' => ['Users.author_id' => 1, 'Users.published' => 'Y']]
  3013. );
  3014. $this->assertEquals($expected, $result->clause('where'));
  3015. $this->assertNull($result->clause('order'));
  3016. }
  3017. /**
  3018. * Test the behavior method.
  3019. *
  3020. * @return void
  3021. */
  3022. public function testBehaviorIntrospection()
  3023. {
  3024. $table = TableRegistry::get('users');
  3025. $table->addBehavior('Timestamp');
  3026. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  3027. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  3028. }
  3029. /**
  3030. * Tests saving belongsTo association
  3031. *
  3032. * @group save
  3033. * @return void
  3034. */
  3035. public function testSaveBelongsTo()
  3036. {
  3037. $entity = new \Cake\ORM\Entity([
  3038. 'title' => 'A Title',
  3039. 'body' => 'A body'
  3040. ]);
  3041. $entity->author = new \Cake\ORM\Entity([
  3042. 'name' => 'Jose'
  3043. ]);
  3044. $table = TableRegistry::get('articles');
  3045. $table->belongsTo('authors');
  3046. $this->assertSame($entity, $table->save($entity));
  3047. $this->assertFalse($entity->isNew());
  3048. $this->assertFalse($entity->author->isNew());
  3049. $this->assertEquals(5, $entity->author->id);
  3050. $this->assertEquals(5, $entity->get('author_id'));
  3051. }
  3052. /**
  3053. * Tests saving hasOne association
  3054. *
  3055. * @group save
  3056. * @return void
  3057. */
  3058. public function testSaveHasOne()
  3059. {
  3060. $entity = new \Cake\ORM\Entity([
  3061. 'name' => 'Jose'
  3062. ]);
  3063. $entity->article = new \Cake\ORM\Entity([
  3064. 'title' => 'A Title',
  3065. 'body' => 'A body'
  3066. ]);
  3067. $table = TableRegistry::get('authors');
  3068. $table->hasOne('articles');
  3069. $this->assertSame($entity, $table->save($entity));
  3070. $this->assertFalse($entity->isNew());
  3071. $this->assertFalse($entity->article->isNew());
  3072. $this->assertEquals(4, $entity->article->id);
  3073. $this->assertEquals(5, $entity->article->get('author_id'));
  3074. $this->assertFalse($entity->article->dirty('author_id'));
  3075. }
  3076. /**
  3077. * Tests saving associations only saves associations
  3078. * if they are entities.
  3079. *
  3080. * @group save
  3081. * @return void
  3082. */
  3083. public function testSaveOnlySaveAssociatedEntities()
  3084. {
  3085. $entity = new \Cake\ORM\Entity([
  3086. 'name' => 'Jose'
  3087. ]);
  3088. // Not an entity.
  3089. $entity->article = [
  3090. 'title' => 'A Title',
  3091. 'body' => 'A body'
  3092. ];
  3093. $table = TableRegistry::get('authors');
  3094. $table->hasOne('articles');
  3095. $table->save($entity);
  3096. $this->assertFalse($entity->isNew());
  3097. $this->assertInternalType('array', $entity->article);
  3098. }
  3099. /**
  3100. * Tests saving multiple entities in a hasMany association
  3101. *
  3102. * @return void
  3103. */
  3104. public function testSaveHasMany()
  3105. {
  3106. $entity = new \Cake\ORM\Entity([
  3107. 'name' => 'Jose'
  3108. ]);
  3109. $entity->articles = [
  3110. new \Cake\ORM\Entity([
  3111. 'title' => 'A Title',
  3112. 'body' => 'A body'
  3113. ]),
  3114. new \Cake\ORM\Entity([
  3115. 'title' => 'Another Title',
  3116. 'body' => 'Another body'
  3117. ])
  3118. ];
  3119. $table = TableRegistry::get('authors');
  3120. $table->hasMany('articles');
  3121. $this->assertSame($entity, $table->save($entity));
  3122. $this->assertFalse($entity->isNew());
  3123. $this->assertFalse($entity->articles[0]->isNew());
  3124. $this->assertFalse($entity->articles[1]->isNew());
  3125. $this->assertEquals(4, $entity->articles[0]->id);
  3126. $this->assertEquals(5, $entity->articles[1]->id);
  3127. $this->assertEquals(5, $entity->articles[0]->author_id);
  3128. $this->assertEquals(5, $entity->articles[1]->author_id);
  3129. }
  3130. /**
  3131. * Tests saving belongsToMany records
  3132. *
  3133. * @group save
  3134. * @return void
  3135. */
  3136. public function testSaveBelongsToMany()
  3137. {
  3138. $entity = new \Cake\ORM\Entity([
  3139. 'title' => 'A Title',
  3140. 'body' => 'A body'
  3141. ]);
  3142. $entity->tags = [
  3143. new \Cake\ORM\Entity([
  3144. 'name' => 'Something New'
  3145. ]),
  3146. new \Cake\ORM\Entity([
  3147. 'name' => 'Another Something'
  3148. ])
  3149. ];
  3150. $table = TableRegistry::get('articles');
  3151. $table->belongsToMany('tags');
  3152. $this->assertSame($entity, $table->save($entity));
  3153. $this->assertFalse($entity->isNew());
  3154. $this->assertFalse($entity->tags[0]->isNew());
  3155. $this->assertFalse($entity->tags[1]->isNew());
  3156. $this->assertEquals(4, $entity->tags[0]->id);
  3157. $this->assertEquals(5, $entity->tags[1]->id);
  3158. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  3159. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  3160. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  3161. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  3162. }
  3163. /**
  3164. * Tests saving belongsToMany records when record exists.
  3165. *
  3166. * @group save
  3167. * @return void
  3168. */
  3169. public function testSaveBelongsToManyJoinDataOnExistingRecord()
  3170. {
  3171. $tags = TableRegistry::get('Tags');
  3172. $table = TableRegistry::get('Articles');
  3173. $table->belongsToMany('Tags');
  3174. $entity = $table->find()->contain('Tags')->first();
  3175. // not associated to the article already.
  3176. $entity->tags[] = $tags->get(3);
  3177. $entity->dirty('tags', true);
  3178. $this->assertSame($entity, $table->save($entity));
  3179. $this->assertFalse($entity->isNew());
  3180. $this->assertFalse($entity->tags[0]->isNew());
  3181. $this->assertFalse($entity->tags[1]->isNew());
  3182. $this->assertFalse($entity->tags[2]->isNew());
  3183. $this->assertNotEmpty($entity->tags[0]->_joinData);
  3184. $this->assertNotEmpty($entity->tags[1]->_joinData);
  3185. $this->assertNotEmpty($entity->tags[2]->_joinData);
  3186. }
  3187. /**
  3188. * Test that belongsToMany can be saved with _joinData data.
  3189. *
  3190. * @return void
  3191. */
  3192. public function testSaveBelongsToManyJoinData()
  3193. {
  3194. $articles = TableRegistry::get('Articles');
  3195. $article = $articles->get(1, ['contain' => ['tags']]);
  3196. $data = [
  3197. 'tags' => [
  3198. ['id' => 1, '_joinData' => ['highlighted' => 1]],
  3199. ['id' => 3]
  3200. ]
  3201. ];
  3202. $article = $articles->patchEntity($article, $data);
  3203. $result = $articles->save($article);
  3204. $this->assertSame($result, $article);
  3205. }
  3206. /**
  3207. * Test to check that association condition are used when fetching existing
  3208. * records to decide which records to unlink.
  3209. *
  3210. * @return void
  3211. */
  3212. public function testPolymorphicBelongsToManySave()
  3213. {
  3214. $articles = TableRegistry::get('Articles');
  3215. $articles->belongsToMany('Tags', [
  3216. 'through' => 'PolymorphicTagged',
  3217. 'foreignKey' => 'foreign_key',
  3218. 'conditions' => [
  3219. 'PolymorphicTagged.foreign_model' => 'Articles'
  3220. ],
  3221. 'sort' => ['PolymorphicTagged.position' => 'ASC']
  3222. ]);
  3223. $articles->Tags->junction()->belongsTo('Tags');
  3224. $entity = $articles->get(1, ['contain' => ['Tags']]);
  3225. $data = [
  3226. 'id' => 1,
  3227. 'tags' => [
  3228. [
  3229. 'id' => 1,
  3230. '_joinData' => [
  3231. 'id' => 2,
  3232. 'foreign_model' => 'Articles',
  3233. 'position' => 2
  3234. ]
  3235. ],
  3236. [
  3237. 'id' => 2,
  3238. '_joinData' => [
  3239. 'foreign_model' => 'Articles',
  3240. 'position' => 1
  3241. ]
  3242. ]
  3243. ]
  3244. ];
  3245. $entity = $articles->patchEntity($entity, $data, ['associated' => ['Tags._joinData']]);
  3246. $entity = $articles->save($entity);
  3247. $expected = [
  3248. [
  3249. 'id' => 1,
  3250. 'tag_id' => 1,
  3251. 'foreign_key' => 1,
  3252. 'foreign_model' => 'Posts',
  3253. 'position' => 1
  3254. ],
  3255. [
  3256. 'id' => 2,
  3257. 'tag_id' => 1,
  3258. 'foreign_key' => 1,
  3259. 'foreign_model' => 'Articles',
  3260. 'position' => 2
  3261. ],
  3262. [
  3263. 'id' => 3,
  3264. 'tag_id' => 2,
  3265. 'foreign_key' => 1,
  3266. 'foreign_model' => 'Articles',
  3267. 'position' => 1
  3268. ]
  3269. ];
  3270. $result = TableRegistry::get('PolymorphicTagged')
  3271. ->find('all', ['sort' => ['id' => 'DESC']])
  3272. ->hydrate(false)
  3273. ->toArray();
  3274. $this->assertEquals($expected, $result);
  3275. }
  3276. /**
  3277. * Tests saving belongsToMany records can delete all links.
  3278. *
  3279. * @group save
  3280. * @return void
  3281. */
  3282. public function testSaveBelongsToManyDeleteAllLinks()
  3283. {
  3284. $table = TableRegistry::get('articles');
  3285. $table->belongsToMany('tags', [
  3286. 'saveStrategy' => 'replace',
  3287. ]);
  3288. $entity = $table->get(1, ['contain' => 'tags']);
  3289. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3290. $entity->tags = [];
  3291. $result = $table->save($entity);
  3292. $this->assertSame($result, $entity);
  3293. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  3294. $entity = $table->get(1, ['contain' => 'tags']);
  3295. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  3296. }
  3297. /**
  3298. * Tests saving belongsToMany records can delete some links.
  3299. *
  3300. * @group save
  3301. * @return void
  3302. */
  3303. public function testSaveBelongsToManyDeleteSomeLinks()
  3304. {
  3305. $table = TableRegistry::get('articles');
  3306. $table->belongsToMany('tags', [
  3307. 'saveStrategy' => 'replace',
  3308. ]);
  3309. $entity = $table->get(1, ['contain' => 'tags']);
  3310. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3311. $tag = new \Cake\ORM\Entity([
  3312. 'id' => 2,
  3313. ]);
  3314. $entity->tags = [$tag];
  3315. $result = $table->save($entity);
  3316. $this->assertSame($result, $entity);
  3317. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  3318. $this->assertEquals($tag, $entity->tags[0]);
  3319. $entity = $table->get(1, ['contain' => 'tags']);
  3320. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  3321. $this->assertEquals($tag->id, $entity->tags[0]->id);
  3322. }
  3323. /**
  3324. * Test that belongsToMany ignores non-entity data.
  3325. *
  3326. * @return void
  3327. */
  3328. public function testSaveBelongsToManyIgnoreNonEntityData()
  3329. {
  3330. $articles = TableRegistry::get('articles');
  3331. $article = $articles->get(1, ['contain' => ['tags']]);
  3332. $article->tags = [
  3333. '_ids' => [2, 1]
  3334. ];
  3335. $result = $articles->save($article);
  3336. $this->assertSame($result, $article);
  3337. }
  3338. /**
  3339. * Tests that saving a persisted and clean entity will is a no-op
  3340. *
  3341. * @group save
  3342. * @return void
  3343. */
  3344. public function testSaveCleanEntity()
  3345. {
  3346. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  3347. $entity = new \Cake\ORM\Entity(
  3348. ['id' => 'foo'],
  3349. ['markNew' => false, 'markClean' => true]
  3350. );
  3351. $table->expects($this->never())->method('_processSave');
  3352. $this->assertSame($entity, $table->save($entity));
  3353. }
  3354. /**
  3355. * Integration test to show how to append a new tag to an article
  3356. *
  3357. * @group save
  3358. * @return void
  3359. */
  3360. public function testBelongsToManyIntegration()
  3361. {
  3362. $table = TableRegistry::get('articles');
  3363. $table->belongsToMany('tags');
  3364. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3365. $tags = $article->tags;
  3366. $this->assertNotEmpty($tags);
  3367. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  3368. $article->tags = $tags;
  3369. $this->assertSame($article, $table->save($article));
  3370. $tags = $article->tags;
  3371. $this->assertCount(3, $tags);
  3372. $this->assertFalse($tags[2]->isNew());
  3373. $this->assertEquals(4, $tags[2]->id);
  3374. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  3375. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  3376. }
  3377. /**
  3378. * Tests that it is possible to do a deep save and control what associations get saved,
  3379. * while having control of the options passed to each level of the save
  3380. *
  3381. * @group save
  3382. * @return void
  3383. */
  3384. public function testSaveDeepAssociationOptions()
  3385. {
  3386. $articles = $this->getMock(
  3387. '\Cake\ORM\Table',
  3388. ['_insert'],
  3389. [['table' => 'articles', 'connection' => $this->connection]]
  3390. );
  3391. $authors = $this->getMock(
  3392. '\Cake\ORM\Table',
  3393. ['_insert'],
  3394. [['table' => 'authors', 'connection' => $this->connection]]
  3395. );
  3396. $supervisors = $this->getMock(
  3397. '\Cake\ORM\Table',
  3398. ['_insert', 'validate'],
  3399. [[
  3400. 'table' => 'authors',
  3401. 'alias' => 'supervisors',
  3402. 'connection' => $this->connection
  3403. ]]
  3404. );
  3405. $tags = $this->getMock(
  3406. '\Cake\ORM\Table',
  3407. ['_insert'],
  3408. [['table' => 'tags', 'connection' => $this->connection]]
  3409. );
  3410. $articles->belongsTo('authors', ['targetTable' => $authors]);
  3411. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  3412. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  3413. $entity = new \Cake\ORM\Entity([
  3414. 'title' => 'bar',
  3415. 'author' => new \Cake\ORM\Entity([
  3416. 'name' => 'Juan',
  3417. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  3418. 'tags' => [
  3419. new \Cake\ORM\Entity(['name' => 'foo'])
  3420. ]
  3421. ]),
  3422. ]);
  3423. $entity->isNew(true);
  3424. $entity->author->isNew(true);
  3425. $entity->author->supervisor->isNew(true);
  3426. $entity->author->tags[0]->isNew(true);
  3427. $articles->expects($this->once())
  3428. ->method('_insert')
  3429. ->with($entity, ['title' => 'bar'])
  3430. ->will($this->returnValue($entity));
  3431. $authors->expects($this->once())
  3432. ->method('_insert')
  3433. ->with($entity->author, ['name' => 'Juan'])
  3434. ->will($this->returnValue($entity->author));
  3435. $supervisors->expects($this->once())
  3436. ->method('_insert')
  3437. ->with($entity->author->supervisor, ['name' => 'Marc'])
  3438. ->will($this->returnValue($entity->author->supervisor));
  3439. $tags->expects($this->never())->method('_insert');
  3440. $this->assertSame($entity, $articles->save($entity, [
  3441. 'associated' => [
  3442. 'authors' => [],
  3443. 'authors.supervisors' => [
  3444. 'atomic' => false,
  3445. 'associated' => false
  3446. ]
  3447. ]
  3448. ]));
  3449. }
  3450. /**
  3451. * Integration test for linking entities with belongsToMany
  3452. *
  3453. * @return void
  3454. */
  3455. public function testLinkBelongsToMany()
  3456. {
  3457. $table = TableRegistry::get('articles');
  3458. $table->belongsToMany('tags');
  3459. $tagsTable = TableRegistry::get('tags');
  3460. $source = ['source' => 'tags'];
  3461. $options = ['markNew' => false];
  3462. $article = new \Cake\ORM\Entity([
  3463. 'id' => 1,
  3464. ], $options);
  3465. $newTag = new \TestApp\Model\Entity\Tag([
  3466. 'name' => 'Foo'
  3467. ], $source);
  3468. $tags[] = new \TestApp\Model\Entity\Tag([
  3469. 'id' => 3
  3470. ], $options + $source);
  3471. $tags[] = $newTag;
  3472. $tagsTable->save($newTag);
  3473. $table->association('tags')->link($article, $tags);
  3474. $this->assertEquals($article->tags, $tags);
  3475. foreach ($tags as $tag) {
  3476. $this->assertFalse($tag->isNew());
  3477. }
  3478. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3479. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  3480. $this->assertEquals($article->tags[3], $tags[1]);
  3481. }
  3482. /**
  3483. * Integration test for linking entities with HasMany
  3484. *
  3485. * @return void
  3486. */
  3487. public function testLinkHasMany()
  3488. {
  3489. $authors = TableRegistry::get('Authors');
  3490. $articles = TableRegistry::get('Articles');
  3491. $authors->hasMany('Articles', [
  3492. 'foreignKey' => 'author_id'
  3493. ]);
  3494. $author = $authors->newEntity(['name' => 'mylux']);
  3495. $author = $authors->save($author);
  3496. $newArticles = $articles->newEntities(
  3497. [
  3498. [
  3499. 'title' => 'New bakery next corner',
  3500. 'body' => 'They sell tastefull cakes'
  3501. ],
  3502. [
  3503. 'title' => 'Spicy cake recipe',
  3504. 'body' => 'chocolate and peppers'
  3505. ]
  3506. ]
  3507. );
  3508. $sizeArticles = count($newArticles);
  3509. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3510. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3511. $this->assertCount($sizeArticles, $author->articles);
  3512. $this->assertFalse($author->dirty('articles'));
  3513. }
  3514. /**
  3515. * Integration test for linking entities with HasMany combined with ReplaceSaveStrategy. It must append, not unlinking anything
  3516. *
  3517. * @return void
  3518. */
  3519. public function testLinkHasManyReplaceSaveStrategy()
  3520. {
  3521. $authors = TableRegistry::get('Authors');
  3522. $articles = TableRegistry::get('Articles');
  3523. $authors->hasMany('Articles', [
  3524. 'foreignKey' => 'author_id',
  3525. 'saveStrategy' => 'replace'
  3526. ]);
  3527. $author = $authors->newEntity(['name' => 'mylux']);
  3528. $author = $authors->save($author);
  3529. $newArticles = $articles->newEntities(
  3530. [
  3531. [
  3532. 'title' => 'New bakery next corner',
  3533. 'body' => 'They sell tastefull cakes'
  3534. ],
  3535. [
  3536. 'title' => 'Spicy cake recipe',
  3537. 'body' => 'chocolate and peppers'
  3538. ]
  3539. ]
  3540. );
  3541. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3542. $sizeArticles = count($newArticles);
  3543. $newArticles = $articles->newEntities(
  3544. [
  3545. [
  3546. 'title' => 'Nothing but the cake',
  3547. 'body' => 'It is all that we need'
  3548. ]
  3549. ]
  3550. );
  3551. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3552. $sizeArticles++;
  3553. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3554. $this->assertCount($sizeArticles, $author->articles);
  3555. $this->assertFalse($author->dirty('articles'));
  3556. }
  3557. /**
  3558. * Integration test for linking entities with HasMany. The input contains already linked entities and they should not appeat duplicated
  3559. *
  3560. * @return void
  3561. */
  3562. public function testLinkHasManyExisting()
  3563. {
  3564. $authors = TableRegistry::get('Authors');
  3565. $articles = TableRegistry::get('Articles');
  3566. $authors->hasMany('Articles', [
  3567. 'foreignKey' => 'author_id',
  3568. 'saveStrategy' => 'replace'
  3569. ]);
  3570. $author = $authors->newEntity(['name' => 'mylux']);
  3571. $author = $authors->save($author);
  3572. $newArticles = $articles->newEntities(
  3573. [
  3574. [
  3575. 'title' => 'New bakery next corner',
  3576. 'body' => 'They sell tastefull cakes'
  3577. ],
  3578. [
  3579. 'title' => 'Spicy cake recipe',
  3580. 'body' => 'chocolate and peppers'
  3581. ]
  3582. ]
  3583. );
  3584. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3585. $sizeArticles = count($newArticles);
  3586. $newArticles = array_merge(
  3587. $author->articles,
  3588. $articles->newEntities(
  3589. [
  3590. [
  3591. 'title' => 'Nothing but the cake',
  3592. 'body' => 'It is all that we need'
  3593. ]
  3594. ]
  3595. )
  3596. );
  3597. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3598. $sizeArticles++;
  3599. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3600. $this->assertCount($sizeArticles, $author->articles);
  3601. $this->assertFalse($author->dirty('articles'));
  3602. }
  3603. /**
  3604. * Integration test for unlinking entities with HasMany. The association property must be cleaned
  3605. *
  3606. * @return void
  3607. */
  3608. public function testUnlinkHasManyCleanProperty()
  3609. {
  3610. $authors = TableRegistry::get('Authors');
  3611. $articles = TableRegistry::get('Articles');
  3612. $authors->hasMany('Articles', [
  3613. 'foreignKey' => 'author_id',
  3614. 'saveStrategy' => 'replace'
  3615. ]);
  3616. $author = $authors->newEntity(['name' => 'mylux']);
  3617. $author = $authors->save($author);
  3618. $newArticles = $articles->newEntities(
  3619. [
  3620. [
  3621. 'title' => 'New bakery next corner',
  3622. 'body' => 'They sell tastefull cakes'
  3623. ],
  3624. [
  3625. 'title' => 'Spicy cake recipe',
  3626. 'body' => 'chocolate and peppers'
  3627. ],
  3628. [
  3629. 'title' => 'Creamy cake recipe',
  3630. 'body' => 'chocolate and cream'
  3631. ],
  3632. ]
  3633. );
  3634. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3635. $sizeArticles = count($newArticles);
  3636. $articlesToUnlink = [ $author->articles[0], $author->articles[1] ];
  3637. $authors->Articles->unlink($author, $articlesToUnlink);
  3638. $this->assertCount($sizeArticles - count($articlesToUnlink), $authors->Articles->findAllByAuthorId($author->id));
  3639. $this->assertCount($sizeArticles - count($articlesToUnlink), $author->articles);
  3640. $this->assertFalse($author->dirty('articles'));
  3641. }
  3642. /**
  3643. * Integration test for unlinking entities with HasMany. The association property must stay unchanged
  3644. *
  3645. * @return void
  3646. */
  3647. public function testUnlinkHasManyNotCleanProperty()
  3648. {
  3649. $authors = TableRegistry::get('Authors');
  3650. $articles = TableRegistry::get('Articles');
  3651. $authors->hasMany('Articles', [
  3652. 'foreignKey' => 'author_id',
  3653. 'saveStrategy' => 'replace'
  3654. ]);
  3655. $author = $authors->newEntity(['name' => 'mylux']);
  3656. $author = $authors->save($author);
  3657. $newArticles = $articles->newEntities(
  3658. [
  3659. [
  3660. 'title' => 'New bakery next corner',
  3661. 'body' => 'They sell tastefull cakes'
  3662. ],
  3663. [
  3664. 'title' => 'Spicy cake recipe',
  3665. 'body' => 'chocolate and peppers'
  3666. ],
  3667. [
  3668. 'title' => 'Creamy cake recipe',
  3669. 'body' => 'chocolate and cream'
  3670. ],
  3671. ]
  3672. );
  3673. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3674. $sizeArticles = count($newArticles);
  3675. $articlesToUnlink = [ $author->articles[0], $author->articles[1] ];
  3676. $authors->Articles->unlink($author, $articlesToUnlink, false);
  3677. $this->assertCount($sizeArticles - count($articlesToUnlink), $authors->Articles->findAllByAuthorId($author->id));
  3678. $this->assertCount($sizeArticles, $author->articles);
  3679. $this->assertFalse($author->dirty('articles'));
  3680. }
  3681. /**
  3682. * Integration test for replacing entities which depend on their source entity with HasMany and failing transaction. False should be returned when
  3683. * unlinking fails while replacing even when cascadeCallbacks is enabled
  3684. *
  3685. * @return void
  3686. */
  3687. public function testReplaceHasManyOnErrorDependentCascadeCallbacks()
  3688. {
  3689. $articles = $this->getMock(
  3690. 'Cake\ORM\Table',
  3691. ['delete'],
  3692. [[
  3693. 'connection' => $this->connection,
  3694. 'alias' => 'Articles',
  3695. 'table' => 'articles',
  3696. ]]
  3697. );
  3698. $articles->method('delete')->willReturn(false);
  3699. $associations = new AssociationCollection();
  3700. $hasManyArticles = $this->getMock(
  3701. 'Cake\ORM\Association\HasMany',
  3702. ['target'],
  3703. [
  3704. 'articles',
  3705. [
  3706. 'target' => $articles,
  3707. 'foreignKey' => 'author_id',
  3708. 'dependent' => true,
  3709. 'cascadeCallbacks' => true
  3710. ]
  3711. ]
  3712. );
  3713. $hasManyArticles->method('target')->willReturn($articles);
  3714. $associations->add('articles', $hasManyArticles);
  3715. $authors = new Table([
  3716. 'connection' => $this->connection,
  3717. 'alias' => 'Authors',
  3718. 'table' => 'authors',
  3719. 'associations' => $associations
  3720. ]);
  3721. $authors->Articles->source($authors);
  3722. $author = $authors->newEntity(['name' => 'mylux']);
  3723. $author = $authors->save($author);
  3724. $newArticles = $articles->newEntities(
  3725. [
  3726. [
  3727. 'title' => 'New bakery next corner',
  3728. 'body' => 'They sell tastefull cakes'
  3729. ],
  3730. [
  3731. 'title' => 'Spicy cake recipe',
  3732. 'body' => 'chocolate and peppers'
  3733. ]
  3734. ]
  3735. );
  3736. $sizeArticles = count($newArticles);
  3737. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3738. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3739. $this->assertEquals(count($author->articles), $sizeArticles);
  3740. $newArticles = array_merge(
  3741. $author->articles,
  3742. $articles->newEntities(
  3743. [
  3744. [
  3745. 'title' => 'Cheese cake recipe',
  3746. 'body' => 'The secrets of mixing salt and sugar'
  3747. ],
  3748. [
  3749. 'title' => 'Not another piece of cake',
  3750. 'body' => 'This is the best'
  3751. ]
  3752. ]
  3753. )
  3754. );
  3755. unset($newArticles[0]);
  3756. $this->assertFalse($authors->Articles->replace($author, $newArticles));
  3757. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3758. }
  3759. /**
  3760. * Integration test for replacing entities with HasMany and an empty target list. The transaction must be successfull
  3761. *
  3762. * @return void
  3763. */
  3764. public function testReplaceHasManyEmptyList()
  3765. {
  3766. $authors = new Table([
  3767. 'connection' => $this->connection,
  3768. 'alias' => 'Authors',
  3769. 'table' => 'authors',
  3770. ]);
  3771. $authors->hasMany('Articles');
  3772. $author = $authors->newEntity(['name' => 'mylux']);
  3773. $author = $authors->save($author);
  3774. $newArticles = $authors->Articles->newEntities(
  3775. [
  3776. [
  3777. 'title' => 'New bakery next corner',
  3778. 'body' => 'They sell tastefull cakes'
  3779. ],
  3780. [
  3781. 'title' => 'Spicy cake recipe',
  3782. 'body' => 'chocolate and peppers'
  3783. ]
  3784. ]
  3785. );
  3786. $sizeArticles = count($newArticles);
  3787. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3788. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3789. $this->assertEquals(count($author->articles), $sizeArticles);
  3790. $newArticles = [];
  3791. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  3792. $this->assertCount(0, $authors->Articles->findAllByAuthorId($author->id));
  3793. }
  3794. /**
  3795. * Integration test for replacing entities with HasMany and no already persisted entities. The transaction must be successfull.
  3796. * Replace operation should prevent considering 0 changed records an error when they are not found in the table
  3797. *
  3798. * @return void
  3799. */
  3800. public function testReplaceHasManyNoPersistedEntities()
  3801. {
  3802. $authors = new Table([
  3803. 'connection' => $this->connection,
  3804. 'alias' => 'Authors',
  3805. 'table' => 'authors',
  3806. ]);
  3807. $authors->hasMany('Articles');
  3808. $author = $authors->newEntity(['name' => 'mylux']);
  3809. $author = $authors->save($author);
  3810. $newArticles = $authors->Articles->newEntities(
  3811. [
  3812. [
  3813. 'title' => 'New bakery next corner',
  3814. 'body' => 'They sell tastefull cakes'
  3815. ],
  3816. [
  3817. 'title' => 'Spicy cake recipe',
  3818. 'body' => 'chocolate and peppers'
  3819. ]
  3820. ]
  3821. );
  3822. $authors->Articles->deleteAll(['1=1']);
  3823. $sizeArticles = count($newArticles);
  3824. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3825. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3826. $this->assertEquals(count($author->articles), $sizeArticles);
  3827. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  3828. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3829. }
  3830. /**
  3831. * Integration test for replacing entities with HasMany.
  3832. *
  3833. * @return void
  3834. */
  3835. public function testReplaceHasMany()
  3836. {
  3837. $authors = TableRegistry::get('Authors');
  3838. $articles = TableRegistry::get('Articles');
  3839. $authors->hasMany('Articles', [
  3840. 'foreignKey' => 'author_id'
  3841. ]);
  3842. $author = $authors->newEntity(['name' => 'mylux']);
  3843. $author = $authors->save($author);
  3844. $newArticles = $articles->newEntities(
  3845. [
  3846. [
  3847. 'title' => 'New bakery next corner',
  3848. 'body' => 'They sell tastefull cakes'
  3849. ],
  3850. [
  3851. 'title' => 'Spicy cake recipe',
  3852. 'body' => 'chocolate and peppers'
  3853. ]
  3854. ]
  3855. );
  3856. $sizeArticles = count($newArticles);
  3857. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3858. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3859. $this->assertEquals(count($author->articles), $sizeArticles);
  3860. $newArticles = array_merge(
  3861. $author->articles,
  3862. $articles->newEntities(
  3863. [
  3864. [
  3865. 'title' => 'Cheese cake recipe',
  3866. 'body' => 'The secrets of mixing salt and sugar'
  3867. ],
  3868. [
  3869. 'title' => 'Not another piece of cake',
  3870. 'body' => 'This is the best'
  3871. ]
  3872. ]
  3873. )
  3874. );
  3875. unset($newArticles[0]);
  3876. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  3877. $this->assertEquals(count($newArticles), count($author->articles));
  3878. $this->assertEquals((new Collection($newArticles))->extract('title'), (new Collection($author->articles))->extract('title'));
  3879. }
  3880. /**
  3881. * Integration test to show how to unlink a single record from a belongsToMany
  3882. *
  3883. * @return void
  3884. */
  3885. public function testUnlinkBelongsToMany()
  3886. {
  3887. $table = TableRegistry::get('articles');
  3888. $table->belongsToMany('tags');
  3889. $tagsTable = TableRegistry::get('tags');
  3890. $options = ['markNew' => false];
  3891. $article = $table->find('all')
  3892. ->where(['id' => 1])
  3893. ->contain(['tags'])->first();
  3894. $table->association('tags')->unlink($article, [$article->tags[0]]);
  3895. $this->assertCount(1, $article->tags);
  3896. $this->assertEquals(2, $article->tags[0]->get('id'));
  3897. $this->assertFalse($article->dirty('tags'));
  3898. }
  3899. /**
  3900. * Integration test to show how to unlink multiple records from a belongsToMany
  3901. *
  3902. * @return void
  3903. */
  3904. public function testUnlinkBelongsToManyMultiple()
  3905. {
  3906. $table = TableRegistry::get('articles');
  3907. $table->belongsToMany('tags');
  3908. $tagsTable = TableRegistry::get('tags');
  3909. $options = ['markNew' => false];
  3910. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3911. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  3912. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3913. $table->association('tags')->unlink($article, $tags);
  3914. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3915. $this->assertEmpty($left->tags);
  3916. }
  3917. /**
  3918. * Integration test to show how to unlink multiple records from a belongsToMany
  3919. * providing some of the joint
  3920. *
  3921. * @return void
  3922. */
  3923. public function testUnlinkBelongsToManyPassingJoint()
  3924. {
  3925. $table = TableRegistry::get('articles');
  3926. $table->belongsToMany('tags');
  3927. $tagsTable = TableRegistry::get('tags');
  3928. $options = ['markNew' => false];
  3929. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3930. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  3931. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3932. $tags[1]->_joinData = new \Cake\ORM\Entity([
  3933. 'article_id' => 1,
  3934. 'tag_id' => 2
  3935. ], $options);
  3936. $table->association('tags')->unlink($article, $tags);
  3937. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3938. $this->assertEmpty($left->tags);
  3939. }
  3940. /**
  3941. * Integration test to show how to replace records from a belongsToMany
  3942. *
  3943. * @return void
  3944. */
  3945. public function testReplacelinksBelongsToMany()
  3946. {
  3947. $table = TableRegistry::get('articles');
  3948. $table->belongsToMany('tags');
  3949. $tagsTable = TableRegistry::get('tags');
  3950. $options = ['markNew' => false];
  3951. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3952. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3953. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  3954. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  3955. $table->association('tags')->replaceLinks($article, $tags);
  3956. $this->assertEquals(2, $article->tags[0]->id);
  3957. $this->assertEquals(3, $article->tags[1]->id);
  3958. $this->assertEquals(4, $article->tags[2]->id);
  3959. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3960. $this->assertCount(3, $article->tags);
  3961. $this->assertEquals(2, $article->tags[0]->id);
  3962. $this->assertEquals(3, $article->tags[1]->id);
  3963. $this->assertEquals(4, $article->tags[2]->id);
  3964. $this->assertEquals('foo', $article->tags[2]->name);
  3965. }
  3966. /**
  3967. * Integration test to show how remove all links from a belongsToMany
  3968. *
  3969. * @return void
  3970. */
  3971. public function testReplacelinksBelongsToManyWithEmpty()
  3972. {
  3973. $table = TableRegistry::get('articles');
  3974. $table->belongsToMany('tags');
  3975. $tagsTable = TableRegistry::get('tags');
  3976. $options = ['markNew' => false];
  3977. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3978. $tags = [];
  3979. $table->association('tags')->replaceLinks($article, $tags);
  3980. $this->assertSame($tags, $article->tags);
  3981. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3982. $this->assertEmpty($article->tags);
  3983. }
  3984. /**
  3985. * Integration test to show how to replace records from a belongsToMany
  3986. * passing the joint property along in the target entity
  3987. *
  3988. * @return void
  3989. */
  3990. public function testReplacelinksBelongsToManyWithJoint()
  3991. {
  3992. $table = TableRegistry::get('articles');
  3993. $table->belongsToMany('tags');
  3994. $tagsTable = TableRegistry::get('tags');
  3995. $options = ['markNew' => false];
  3996. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3997. $tags[] = new \TestApp\Model\Entity\Tag([
  3998. 'id' => 2,
  3999. '_joinData' => new \Cake\ORM\Entity([
  4000. 'article_id' => 1,
  4001. 'tag_id' => 2,
  4002. ])
  4003. ], $options);
  4004. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  4005. $table->association('tags')->replaceLinks($article, $tags);
  4006. $this->assertSame($tags, $article->tags);
  4007. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4008. $this->assertCount(2, $article->tags);
  4009. $this->assertEquals(2, $article->tags[0]->id);
  4010. $this->assertEquals(3, $article->tags[1]->id);
  4011. }
  4012. /**
  4013. * Tests that it is possible to call find with no arguments
  4014. *
  4015. * @return void
  4016. */
  4017. public function testSimplifiedFind()
  4018. {
  4019. $table = $this->getMock(
  4020. '\Cake\ORM\Table',
  4021. ['callFinder'],
  4022. [[
  4023. 'connection' => $this->connection,
  4024. 'schema' => ['id' => ['type' => 'integer']]
  4025. ]]
  4026. );
  4027. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  4028. $table->expects($this->once())->method('callFinder')
  4029. ->with('all', $query, []);
  4030. $table->find();
  4031. }
  4032. public function providerForTestGet()
  4033. {
  4034. return [
  4035. [ ['fields' => ['id']] ],
  4036. [ ['fields' => ['id'], 'cache' => false] ]
  4037. ];
  4038. }
  4039. /**
  4040. * Test that get() will use the primary key for searching and return the first
  4041. * entity found
  4042. *
  4043. * @dataProvider providerForTestGet
  4044. * @param array $options
  4045. * @return void
  4046. */
  4047. public function testGet($options)
  4048. {
  4049. $table = $this->getMock(
  4050. '\Cake\ORM\Table',
  4051. ['callFinder', 'query'],
  4052. [[
  4053. 'connection' => $this->connection,
  4054. 'schema' => [
  4055. 'id' => ['type' => 'integer'],
  4056. 'bar' => ['type' => 'integer'],
  4057. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  4058. ]
  4059. ]]
  4060. );
  4061. $query = $this->getMock(
  4062. '\Cake\ORM\Query',
  4063. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  4064. [$this->connection, $table]
  4065. );
  4066. $entity = new \Cake\ORM\Entity;
  4067. $table->expects($this->once())->method('query')
  4068. ->will($this->returnValue($query));
  4069. $table->expects($this->once())->method('callFinder')
  4070. ->with('all', $query, ['fields' => ['id']])
  4071. ->will($this->returnValue($query));
  4072. $query->expects($this->once())->method('where')
  4073. ->with([$table->alias() . '.bar' => 10])
  4074. ->will($this->returnSelf());
  4075. $query->expects($this->never())->method('cache');
  4076. $query->expects($this->once())->method('firstOrFail')
  4077. ->will($this->returnValue($entity));
  4078. $result = $table->get(10, $options);
  4079. $this->assertSame($entity, $result);
  4080. }
  4081. public function providerForTestGetWithCustomFinder()
  4082. {
  4083. return [
  4084. [ ['fields' => ['id'], 'finder' => 'custom'] ]
  4085. ];
  4086. }
  4087. /**
  4088. * Test that get() will call a custom finder.
  4089. *
  4090. * @dataProvider providerForTestGetWithCustomFinder
  4091. * @param array $options
  4092. * @return void
  4093. */
  4094. public function testGetWithCustomFinder($options)
  4095. {
  4096. $table = $this->getMock(
  4097. '\Cake\ORM\Table',
  4098. ['callFinder', 'query'],
  4099. [[
  4100. 'connection' => $this->connection,
  4101. 'schema' => [
  4102. 'id' => ['type' => 'integer'],
  4103. 'bar' => ['type' => 'integer'],
  4104. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  4105. ]
  4106. ]]
  4107. );
  4108. $query = $this->getMock(
  4109. '\Cake\ORM\Query',
  4110. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  4111. [$this->connection, $table]
  4112. );
  4113. $entity = new \Cake\ORM\Entity;
  4114. $table->expects($this->once())->method('query')
  4115. ->will($this->returnValue($query));
  4116. $table->expects($this->once())->method('callFinder')
  4117. ->with('custom', $query, ['fields' => ['id']])
  4118. ->will($this->returnValue($query));
  4119. $query->expects($this->once())->method('where')
  4120. ->with([$table->alias() . '.bar' => 10])
  4121. ->will($this->returnSelf());
  4122. $query->expects($this->never())->method('cache');
  4123. $query->expects($this->once())->method('firstOrFail')
  4124. ->will($this->returnValue($entity));
  4125. $result = $table->get(10, $options);
  4126. $this->assertSame($entity, $result);
  4127. }
  4128. public function providerForTestGetWithCache()
  4129. {
  4130. return [
  4131. [
  4132. ['fields' => ['id'], 'cache' => 'default'],
  4133. 'get:test.table_name[10]', 'default'
  4134. ],
  4135. [
  4136. ['fields' => ['id'], 'cache' => 'default', 'key' => 'custom_key'],
  4137. 'custom_key', 'default'
  4138. ]
  4139. ];
  4140. }
  4141. /**
  4142. * Test that get() will use the cache.
  4143. *
  4144. * @dataProvider providerForTestGetWithCache
  4145. * @param array $options
  4146. * @param string $cacheKey
  4147. * @param string $cacheConfig
  4148. * @return void
  4149. */
  4150. public function testGetWithCache($options, $cacheKey, $cacheConfig)
  4151. {
  4152. $table = $this->getMock(
  4153. '\Cake\ORM\Table',
  4154. ['callFinder', 'query'],
  4155. [[
  4156. 'connection' => $this->connection,
  4157. 'schema' => [
  4158. 'id' => ['type' => 'integer'],
  4159. 'bar' => ['type' => 'integer'],
  4160. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  4161. ]
  4162. ]]
  4163. );
  4164. $table->table('table_name');
  4165. $query = $this->getMock(
  4166. '\Cake\ORM\Query',
  4167. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  4168. [$this->connection, $table]
  4169. );
  4170. $entity = new \Cake\ORM\Entity;
  4171. $table->expects($this->once())->method('query')
  4172. ->will($this->returnValue($query));
  4173. $table->expects($this->once())->method('callFinder')
  4174. ->with('all', $query, ['fields' => ['id']])
  4175. ->will($this->returnValue($query));
  4176. $query->expects($this->once())->method('where')
  4177. ->with([$table->alias() . '.bar' => 10])
  4178. ->will($this->returnSelf());
  4179. $query->expects($this->once())->method('cache')
  4180. ->with($cacheKey, $cacheConfig)
  4181. ->will($this->returnSelf());
  4182. $query->expects($this->once())->method('firstOrFail')
  4183. ->will($this->returnValue($entity));
  4184. $result = $table->get(10, $options);
  4185. $this->assertSame($entity, $result);
  4186. }
  4187. /**
  4188. * Tests that get() will throw an exception if the record was not found
  4189. *
  4190. * @expectedException Cake\Datasource\Exception\RecordNotFoundException
  4191. * @expectedExceptionMessage Record not found in table "articles"
  4192. * @return void
  4193. */
  4194. public function testGetNotFoundException()
  4195. {
  4196. $table = new Table([
  4197. 'name' => 'Articles',
  4198. 'connection' => $this->connection,
  4199. 'table' => 'articles',
  4200. ]);
  4201. $table->get(10);
  4202. }
  4203. /**
  4204. * Test that an exception is raised when there are not enough keys.
  4205. *
  4206. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  4207. * @expectedExceptionMessage Record not found in table "articles" with primary key [NULL]
  4208. * @return void
  4209. */
  4210. public function testGetExceptionOnNoData()
  4211. {
  4212. $table = new Table([
  4213. 'name' => 'Articles',
  4214. 'connection' => $this->connection,
  4215. 'table' => 'articles',
  4216. ]);
  4217. $table->get(null);
  4218. }
  4219. /**
  4220. * Test that an exception is raised when there are too many keys.
  4221. *
  4222. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  4223. * @expectedExceptionMessage Record not found in table "articles" with primary key [1, 'two']
  4224. * @return void
  4225. */
  4226. public function testGetExceptionOnTooMuchData()
  4227. {
  4228. $table = new Table([
  4229. 'name' => 'Articles',
  4230. 'connection' => $this->connection,
  4231. 'table' => 'articles',
  4232. ]);
  4233. $table->get([1, 'two']);
  4234. }
  4235. /**
  4236. * Tests that patchEntity delegates the task to the marshaller and passed
  4237. * all associations
  4238. *
  4239. * @return void
  4240. */
  4241. public function testPatchEntity()
  4242. {
  4243. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  4244. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  4245. $table->belongsTo('users');
  4246. $table->hasMany('articles');
  4247. $table->expects($this->once())->method('marshaller')
  4248. ->will($this->returnValue($marshaller));
  4249. $entity = new \Cake\ORM\Entity;
  4250. $data = ['foo' => 'bar'];
  4251. $marshaller->expects($this->once())
  4252. ->method('merge')
  4253. ->with($entity, $data, ['associated' => ['users', 'articles']])
  4254. ->will($this->returnValue($entity));
  4255. $table->patchEntity($entity, $data);
  4256. }
  4257. /**
  4258. * Tests that patchEntities delegates the task to the marshaller and passed
  4259. * all associations
  4260. *
  4261. * @return void
  4262. */
  4263. public function testPatchEntities()
  4264. {
  4265. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  4266. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  4267. $table->belongsTo('users');
  4268. $table->hasMany('articles');
  4269. $table->expects($this->once())->method('marshaller')
  4270. ->will($this->returnValue($marshaller));
  4271. $entities = [new \Cake\ORM\Entity];
  4272. $data = [['foo' => 'bar']];
  4273. $marshaller->expects($this->once())
  4274. ->method('mergeMany')
  4275. ->with($entities, $data, ['associated' => ['users', 'articles']])
  4276. ->will($this->returnValue($entities));
  4277. $table->patchEntities($entities, $data);
  4278. }
  4279. /**
  4280. * Tests __debugInfo
  4281. *
  4282. * @return void
  4283. */
  4284. public function testDebugInfo()
  4285. {
  4286. $articles = TableRegistry::get('articles');
  4287. $articles->addBehavior('Timestamp');
  4288. $result = $articles->__debugInfo();
  4289. $expected = [
  4290. 'registryAlias' => 'articles',
  4291. 'table' => 'articles',
  4292. 'alias' => 'articles',
  4293. 'entityClass' => 'TestApp\Model\Entity\Article',
  4294. 'associations' => ['authors', 'tags', 'articlestags'],
  4295. 'behaviors' => ['Timestamp'],
  4296. 'defaultConnection' => 'default',
  4297. 'connectionName' => 'test'
  4298. ];
  4299. $this->assertEquals($expected, $result);
  4300. $articles = TableRegistry::get('Foo.Articles');
  4301. $result = $articles->__debugInfo();
  4302. $expected = [
  4303. 'registryAlias' => 'Foo.Articles',
  4304. 'table' => 'articles',
  4305. 'alias' => 'Articles',
  4306. 'entityClass' => '\Cake\ORM\Entity',
  4307. 'associations' => [],
  4308. 'behaviors' => [],
  4309. 'defaultConnection' => 'default',
  4310. 'connectionName' => 'test'
  4311. ];
  4312. $this->assertEquals($expected, $result);
  4313. }
  4314. /**
  4315. * Test the findOrCreate method.
  4316. *
  4317. * @return void
  4318. */
  4319. public function testFindOrCreate()
  4320. {
  4321. $articles = TableRegistry::get('Articles');
  4322. $article = $articles->findOrCreate(['title' => 'Not there'], function ($article) {
  4323. $article->body = 'New body';
  4324. });
  4325. $this->assertFalse($article->isNew());
  4326. $this->assertNotNull($article->id);
  4327. $this->assertEquals('Not there', $article->title);
  4328. $this->assertEquals('New body', $article->body);
  4329. $article = $articles->findOrCreate(['title' => 'Not there']);
  4330. $this->assertFalse($article->isNew());
  4331. $this->assertNotNull($article->id);
  4332. $this->assertEquals('Not there', $article->title);
  4333. $article = $articles->findOrCreate(['title' => 'First Article'], function ($article) {
  4334. $this->fail('Should not be called for existing entities.');
  4335. });
  4336. $this->assertFalse($article->isNew());
  4337. $this->assertNotNull($article->id);
  4338. $this->assertEquals('First Article', $article->title);
  4339. $article = $articles->findOrCreate(
  4340. ['author_id' => 2, 'title' => 'First Article'],
  4341. function ($article) {
  4342. $article->set(['published' => 'N', 'body' => 'New body']);
  4343. }
  4344. );
  4345. $this->assertFalse($article->isNew());
  4346. $this->assertNotNull($article->id);
  4347. $this->assertEquals('First Article', $article->title);
  4348. $this->assertEquals('New body', $article->body);
  4349. $this->assertEquals('N', $article->published);
  4350. $this->assertEquals(2, $article->author_id);
  4351. }
  4352. /**
  4353. * Test that creating a table fires the initialize event.
  4354. *
  4355. * @return void
  4356. */
  4357. public function testInitializeEvent()
  4358. {
  4359. $count = 0;
  4360. $cb = function ($event) use (&$count) {
  4361. $count++;
  4362. };
  4363. EventManager::instance()->on('Model.initialize', $cb);
  4364. $articles = TableRegistry::get('Articles');
  4365. $this->assertEquals(1, $count, 'Callback should be called');
  4366. EventManager::instance()->detach($cb, 'Model.initialize');
  4367. }
  4368. /**
  4369. * Tests the hasFinder method
  4370. *
  4371. * @return void
  4372. */
  4373. public function testHasFinder()
  4374. {
  4375. $table = TableRegistry::get('articles');
  4376. $table->addBehavior('Sluggable');
  4377. $this->assertTrue($table->hasFinder('list'));
  4378. $this->assertTrue($table->hasFinder('noSlug'));
  4379. $this->assertFalse($table->hasFinder('noFind'));
  4380. }
  4381. /**
  4382. * Tests that calling validator() trigger the buildValidator event
  4383. *
  4384. * @return void
  4385. */
  4386. public function testBuildValidatorEvent()
  4387. {
  4388. $count = 0;
  4389. $cb = function ($event) use (&$count) {
  4390. $count++;
  4391. };
  4392. EventManager::instance()->on('Model.buildValidator', $cb);
  4393. $articles = TableRegistry::get('Articles');
  4394. $articles->validator();
  4395. $this->assertEquals(1, $count, 'Callback should be called');
  4396. $articles->validator();
  4397. $this->assertEquals(1, $count, 'Callback should be called only once');
  4398. }
  4399. /**
  4400. * Tests the validateUnique method with different combinations
  4401. *
  4402. * @return void
  4403. */
  4404. public function testValidateUnique()
  4405. {
  4406. $table = TableRegistry::get('Users');
  4407. $validator = new Validator;
  4408. $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
  4409. $validator->provider('table', $table);
  4410. $data = ['username' => 'larry'];
  4411. $this->assertNotEmpty($validator->errors($data));
  4412. $data = ['username' => 'jose'];
  4413. $this->assertEmpty($validator->errors($data));
  4414. $data = ['username' => 'larry', 'id' => 3];
  4415. $this->assertEmpty($validator->errors($data, false));
  4416. $data = ['username' => 'larry', 'id' => 3];
  4417. $this->assertNotEmpty($validator->errors($data));
  4418. $data = ['username' => 'larry'];
  4419. $this->assertNotEmpty($validator->errors($data, false));
  4420. $validator->add('username', 'unique', [
  4421. 'rule' => 'validateUnique', 'provider' => 'table'
  4422. ]);
  4423. $data = ['username' => 'larry'];
  4424. $this->assertNotEmpty($validator->errors($data, false));
  4425. }
  4426. /**
  4427. * Tests the validateUnique method with scope
  4428. *
  4429. * @return void
  4430. */
  4431. public function testValidateUniqueScope()
  4432. {
  4433. $table = TableRegistry::get('Users');
  4434. $validator = new Validator;
  4435. $validator->add('username', 'unique', [
  4436. 'rule' => ['validateUnique', ['derp' => 'erp', 'scope' => 'id']],
  4437. 'provider' => 'table'
  4438. ]);
  4439. $validator->provider('table', $table);
  4440. $data = ['username' => 'larry', 'id' => 3];
  4441. $this->assertNotEmpty($validator->errors($data));
  4442. $data = ['username' => 'larry', 'id' => 1];
  4443. $this->assertEmpty($validator->errors($data));
  4444. $data = ['username' => 'jose'];
  4445. $this->assertEmpty($validator->errors($data));
  4446. }
  4447. /**
  4448. * Tests that the callbacks receive the expected types of arguments.
  4449. *
  4450. * @return void
  4451. */
  4452. public function testCallbackArgumentTypes()
  4453. {
  4454. $table = TableRegistry::get('articles');
  4455. $table->belongsTo('authors');
  4456. $eventManager = $table->eventManager();
  4457. $associationBeforeFindCount = 0;
  4458. $table->association('authors')->target()->eventManager()->on(
  4459. 'Model.beforeFind',
  4460. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) {
  4461. $this->assertTrue(is_bool($primary));
  4462. $associationBeforeFindCount ++;
  4463. }
  4464. );
  4465. $beforeFindCount = 0;
  4466. $eventManager->on(
  4467. 'Model.beforeFind',
  4468. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) {
  4469. $this->assertTrue(is_bool($primary));
  4470. $beforeFindCount ++;
  4471. }
  4472. );
  4473. $table->find()->contain('authors')->first();
  4474. $this->assertEquals(1, $associationBeforeFindCount);
  4475. $this->assertEquals(1, $beforeFindCount);
  4476. $buildValidatorCount = 0;
  4477. $eventManager->on(
  4478. 'Model.buildValidator',
  4479. $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) {
  4480. $this->assertTrue(is_string($name));
  4481. $buildValidatorCount ++;
  4482. }
  4483. );
  4484. $table->validator();
  4485. $this->assertEquals(1, $buildValidatorCount);
  4486. $buildRulesCount =
  4487. $beforeRulesCount =
  4488. $afterRulesCount =
  4489. $beforeSaveCount =
  4490. $afterSaveCount = 0;
  4491. $eventManager->on(
  4492. 'Model.buildRules',
  4493. function (Event $event, RulesChecker $rules) use (&$buildRulesCount) {
  4494. $buildRulesCount ++;
  4495. }
  4496. );
  4497. $eventManager->on(
  4498. 'Model.beforeRules',
  4499. function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) {
  4500. $this->assertTrue(is_string($operation));
  4501. $beforeRulesCount ++;
  4502. }
  4503. );
  4504. $eventManager->on(
  4505. 'Model.afterRules',
  4506. function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) {
  4507. $this->assertTrue(is_bool($result));
  4508. $this->assertTrue(is_string($operation));
  4509. $afterRulesCount ++;
  4510. }
  4511. );
  4512. $eventManager->on(
  4513. 'Model.beforeSave',
  4514. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) {
  4515. $beforeSaveCount ++;
  4516. }
  4517. );
  4518. $eventManager->on(
  4519. 'Model.afterSave',
  4520. $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) {
  4521. $afterSaveCount ++;
  4522. }
  4523. );
  4524. $entity = new Entity(['title' => 'Title']);
  4525. $this->assertNotFalse($table->save($entity));
  4526. $this->assertEquals(1, $buildRulesCount);
  4527. $this->assertEquals(1, $beforeRulesCount);
  4528. $this->assertEquals(1, $afterRulesCount);
  4529. $this->assertEquals(1, $beforeSaveCount);
  4530. $this->assertEquals(1, $afterSaveCount);
  4531. $beforeDeleteCount =
  4532. $afterDeleteCount = 0;
  4533. $eventManager->on(
  4534. 'Model.beforeDelete',
  4535. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) {
  4536. $beforeDeleteCount ++;
  4537. }
  4538. );
  4539. $eventManager->on(
  4540. 'Model.afterDelete',
  4541. function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) {
  4542. $afterDeleteCount ++;
  4543. }
  4544. );
  4545. $this->assertTrue($table->delete($entity, ['checkRules' => false]));
  4546. $this->assertEquals(1, $beforeDeleteCount);
  4547. $this->assertEquals(1, $afterDeleteCount);
  4548. }
  4549. /**
  4550. * Tests that calling newEntity() on a table sets the right source alias
  4551. *
  4552. * @return void
  4553. */
  4554. public function testEntitySource()
  4555. {
  4556. $table = TableRegistry::get('Articles');
  4557. $this->assertEquals('Articles', $table->newEntity()->source());
  4558. Plugin::load('TestPlugin');
  4559. $table = TableRegistry::get('TestPlugin.Comments');
  4560. $this->assertEquals('TestPlugin.Comments', $table->newEntity()->source());
  4561. }
  4562. /**
  4563. * Tests that passing a coned entity that was marked as new to save() will
  4564. * actaully save it as a new entity
  4565. *
  4566. * @group save
  4567. * @return void
  4568. */
  4569. public function testSaveWithClonedEntity()
  4570. {
  4571. $table = TableRegistry::get('Articles');
  4572. $article = $table->get(1);
  4573. $cloned = clone $article;
  4574. $cloned->unsetProperty('id');
  4575. $cloned->isNew(true);
  4576. $this->assertSame($cloned, $table->save($cloned));
  4577. $this->assertEquals(
  4578. $article->extract(['title', 'author_id']),
  4579. $cloned->extract(['title', 'author_id'])
  4580. );
  4581. $this->assertEquals(4, $cloned->id);
  4582. }
  4583. /**
  4584. * Tests that the _ids notation can be used for HasMany
  4585. *
  4586. * @return void
  4587. */
  4588. public function testSaveHasManyWithIds()
  4589. {
  4590. $data = [
  4591. 'username' => 'lux',
  4592. 'password' => 'passphrase',
  4593. 'comments' => [
  4594. '_ids' => [1, 2]
  4595. ]
  4596. ];
  4597. $userTable = TableRegistry::get('Users');
  4598. $userTable->hasMany('Comments');
  4599. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  4600. $retrievedUser = $userTable->find('all')->where(['id' => $savedUser->id])->contain(['Comments'])->first();
  4601. $this->assertEquals($savedUser->comments[0]->user_id, $retrievedUser->comments[0]->user_id);
  4602. $this->assertEquals($savedUser->comments[1]->user_id, $retrievedUser->comments[1]->user_id);
  4603. }
  4604. /**
  4605. * Tests that on second save, entities for the has many relation are not marked
  4606. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  4607. * for a cleaner transaction log
  4608. *
  4609. * @return void
  4610. */
  4611. public function testSaveHasManyNoWasteSave()
  4612. {
  4613. $data = [
  4614. 'username' => 'lux',
  4615. 'password' => 'passphrase',
  4616. 'comments' => [
  4617. '_ids' => [1, 2]
  4618. ]
  4619. ];
  4620. $userTable = TableRegistry::get('Users');
  4621. $userTable->hasMany('Comments');
  4622. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  4623. $counter = 0;
  4624. $userTable->Comments
  4625. ->eventManager()
  4626. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  4627. if ($entity->dirty()) {
  4628. $counter++;
  4629. }
  4630. });
  4631. $savedUser->comments[] = $userTable->Comments->get(5);
  4632. $this->assertCount(3, $savedUser->comments);
  4633. $savedUser->dirty('comments', true);
  4634. $userTable->save($savedUser);
  4635. $this->assertEquals(1, $counter);
  4636. }
  4637. /**
  4638. * Tests that on second save, entities for the belongsToMany relation are not marked
  4639. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  4640. * for a cleaner transaction log
  4641. *
  4642. * @return void
  4643. */
  4644. public function testSaveBelongsToManyNoWasteSave()
  4645. {
  4646. $data = [
  4647. 'title' => 'foo',
  4648. 'body' => 'bar',
  4649. 'tags' => [
  4650. '_ids' => [1, 2]
  4651. ]
  4652. ];
  4653. $table = TableRegistry::get('Articles');
  4654. $table->belongsToMany('Tags');
  4655. $article = $table->save($table->newEntity($data, ['associated' => ['Tags']]));
  4656. $counter = 0;
  4657. $table->Tags->junction()
  4658. ->eventManager()
  4659. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  4660. if ($entity->dirty()) {
  4661. $counter++;
  4662. }
  4663. });
  4664. $article->tags[] = $table->Tags->get(3);
  4665. $this->assertCount(3, $article->tags);
  4666. $article->dirty('tags', true);
  4667. $table->save($article);
  4668. $this->assertEquals(1, $counter);
  4669. }
  4670. /**
  4671. * Tests that after saving then entity contains the right primary
  4672. * key casted to the right type
  4673. *
  4674. * @group save
  4675. * @return void
  4676. */
  4677. public function testSaveCorrectPrimaryKeyType()
  4678. {
  4679. $entity = new Entity([
  4680. 'username' => 'superuser',
  4681. 'created' => new Time('2013-10-10 00:00'),
  4682. 'updated' => new Time('2013-10-10 00:00')
  4683. ], ['markNew' => true]);
  4684. $table = TableRegistry::get('Users');
  4685. $this->assertSame($entity, $table->save($entity));
  4686. $this->assertSame(self::$nextUserId, $entity->id);
  4687. }
  4688. /**
  4689. * Tests the loadInto() method
  4690. *
  4691. * @return void
  4692. */
  4693. public function testLoadIntoEntity()
  4694. {
  4695. $table = TableRegistry::get('Authors');
  4696. $table->hasMany('SiteArticles');
  4697. $articles = $table->hasMany('Articles');
  4698. $articles->belongsToMany('Tags');
  4699. $entity = $table->get(1);
  4700. $result = $table->loadInto($entity, ['SiteArticles', 'Articles.Tags']);
  4701. $this->assertSame($entity, $result);
  4702. $expected = $table->get(1, ['contain' => ['SiteArticles', 'Articles.Tags']]);
  4703. $this->assertEquals($expected, $result);
  4704. }
  4705. /**
  4706. * Tests that it is possible to pass conditions and fields to loadInto()
  4707. *
  4708. * @return void
  4709. */
  4710. public function testLoadIntoWithConditions()
  4711. {
  4712. $table = TableRegistry::get('Authors');
  4713. $table->hasMany('SiteArticles');
  4714. $articles = $table->hasMany('Articles');
  4715. $articles->belongsToMany('Tags');
  4716. $entity = $table->get(1);
  4717. $options = [
  4718. 'SiteArticles' => ['fields' => ['title', 'author_id']],
  4719. 'Articles.Tags' => function ($q) {
  4720. return $q->where(['Tags.name' => 'tag2']);
  4721. }
  4722. ];
  4723. $result = $table->loadInto($entity, $options);
  4724. $this->assertSame($entity, $result);
  4725. $expected = $table->get(1, ['contain' => $options]);
  4726. $this->assertEquals($expected, $result);
  4727. }
  4728. /**
  4729. * Tests loadInto() with a belongsTo association
  4730. *
  4731. * @return void
  4732. */
  4733. public function testLoadBelognsTo()
  4734. {
  4735. $table = TableRegistry::get('Articles');
  4736. $table->belongsTo('Authors');
  4737. $entity = $table->get(2);
  4738. $result = $table->loadInto($entity, ['Authors']);
  4739. $this->assertSame($entity, $result);
  4740. $expected = $table->get(2, ['contain' => ['Authors']]);
  4741. $this->assertEquals($expected, $entity);
  4742. }
  4743. /**
  4744. * Tests that it is possible to post-load associations for many entities at
  4745. * the same time
  4746. *
  4747. * @return void
  4748. */
  4749. public function testLoadIntoMany()
  4750. {
  4751. $table = TableRegistry::get('Authors');
  4752. $table->hasMany('SiteArticles');
  4753. $articles = $table->hasMany('Articles');
  4754. $articles->belongsToMany('Tags');
  4755. $entities = $table->find()->compile();
  4756. $contain = ['SiteArticles', 'Articles.Tags'];
  4757. $result = $table->loadInto($entities, $contain);
  4758. foreach ($entities as $k => $v) {
  4759. $this->assertSame($v, $result[$k]);
  4760. }
  4761. $expected = $table->find()->contain($contain)->toList();
  4762. $this->assertEquals($expected, $result);
  4763. }
  4764. /**
  4765. * Helper method to skip tests when connection is SQLServer.
  4766. *
  4767. * @return void
  4768. */
  4769. public function skipIfSqlServer()
  4770. {
  4771. $this->skipIf(
  4772. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  4773. 'SQLServer does not support the requirements of this test.'
  4774. );
  4775. }
  4776. }