TableTest.php 183 KB

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