TableTest.php 183 KB

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