TableTest.php 197 KB

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