TableTest.php 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092
  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. */
  49. class TableTest extends TestCase
  50. {
  51. public $fixtures = [
  52. 'core.articles',
  53. 'core.tags',
  54. 'core.articles_tags',
  55. 'core.authors',
  56. 'core.categories',
  57. 'core.comments',
  58. 'core.groups',
  59. 'core.groups_members',
  60. 'core.members',
  61. 'core.polymorphic_tagged',
  62. 'core.site_articles',
  63. 'core.users'
  64. ];
  65. /**
  66. * Handy variable containing the next primary key that will be inserted in the
  67. * users table
  68. *
  69. * @var int
  70. */
  71. public static $nextUserId = 5;
  72. public function setUp()
  73. {
  74. parent::setUp();
  75. $this->connection = ConnectionManager::get('test');
  76. Configure::write('App.namespace', 'TestApp');
  77. $this->usersTypeMap = new TypeMap([
  78. 'Users.id' => 'integer',
  79. 'id' => 'integer',
  80. 'Users__id' => 'integer',
  81. 'Users.username' => 'string',
  82. 'Users__username' => 'string',
  83. 'username' => 'string',
  84. 'Users.password' => 'string',
  85. 'Users__password' => 'string',
  86. 'password' => 'string',
  87. 'Users.created' => 'timestamp',
  88. 'Users__created' => 'timestamp',
  89. 'created' => 'timestamp',
  90. 'Users.updated' => 'timestamp',
  91. 'Users__updated' => 'timestamp',
  92. 'updated' => 'timestamp',
  93. ]);
  94. $this->articlesTypeMap = new TypeMap([
  95. 'Articles.id' => 'integer',
  96. 'Articles__id' => 'integer',
  97. 'id' => 'integer',
  98. 'Articles.title' => 'string',
  99. 'Articles__title' => 'string',
  100. 'title' => 'string',
  101. 'Articles.author_id' => 'integer',
  102. 'Articles__author_id' => 'integer',
  103. 'author_id' => 'integer',
  104. 'Articles.body' => 'text',
  105. 'Articles__body' => 'text',
  106. 'body' => 'text',
  107. 'Articles.published' => 'string',
  108. 'Articles__published' => 'string',
  109. 'published' => 'string',
  110. ]);
  111. }
  112. /**
  113. * teardown method
  114. *
  115. * @return void
  116. */
  117. public function tearDown()
  118. {
  119. parent::tearDown();
  120. TableRegistry::clear();
  121. }
  122. /**
  123. * Tests the table method
  124. *
  125. * @return void
  126. */
  127. public function testTableMethod()
  128. {
  129. $table = new Table(['table' => 'users']);
  130. $this->assertEquals('users', $table->table());
  131. $table = new UsersTable;
  132. $this->assertEquals('users', $table->table());
  133. $table = $this->getMockBuilder('\Cake\ORM\Table')
  134. ->setMethods(['find'])
  135. ->setMockClassName('SpecialThingsTable')
  136. ->getMock();
  137. $this->assertEquals('special_things', $table->table());
  138. $table = new Table(['alias' => 'LoveBoats']);
  139. $this->assertEquals('love_boats', $table->table());
  140. $table->table('other');
  141. $this->assertEquals('other', $table->table());
  142. $table->table('database.other');
  143. $this->assertEquals('database.other', $table->table());
  144. }
  145. /**
  146. * Tests the alias method
  147. *
  148. * @return void
  149. */
  150. public function testAliasMethod()
  151. {
  152. $table = new Table(['alias' => 'users']);
  153. $this->assertEquals('users', $table->alias());
  154. $table = new Table(['table' => 'stuffs']);
  155. $this->assertEquals('stuffs', $table->alias());
  156. $table = new UsersTable;
  157. $this->assertEquals('Users', $table->alias());
  158. $table = $this->getMockBuilder('\Cake\ORM\Table')
  159. ->setMethods(['find'])
  160. ->setMockClassName('SpecialThingTable')
  161. ->getMock();
  162. $this->assertEquals('SpecialThing', $table->alias());
  163. $table->alias('AnotherOne');
  164. $this->assertEquals('AnotherOne', $table->alias());
  165. }
  166. /**
  167. * Test that aliasField() works.
  168. *
  169. * @return void
  170. */
  171. public function testAliasField()
  172. {
  173. $table = new Table(['alias' => 'Users']);
  174. $this->assertEquals('Users.id', $table->aliasField('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(['beforeFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete'])
  1525. ->getMock();
  1526. $result = $table->implementedEvents();
  1527. $expected = [
  1528. 'Model.beforeFind' => 'beforeFind',
  1529. 'Model.beforeSave' => 'beforeSave',
  1530. 'Model.afterSave' => 'afterSave',
  1531. 'Model.beforeDelete' => 'beforeDelete',
  1532. 'Model.afterDelete' => 'afterDelete',
  1533. ];
  1534. $this->assertEquals($expected, $result, 'Events do not match.');
  1535. }
  1536. /**
  1537. * Tests that it is possible to insert a new row using the save method
  1538. *
  1539. * @group save
  1540. * @return void
  1541. */
  1542. public function testSaveNewEntity()
  1543. {
  1544. $entity = new \Cake\ORM\Entity([
  1545. 'username' => 'superuser',
  1546. 'password' => 'root',
  1547. 'created' => new Time('2013-10-10 00:00'),
  1548. 'updated' => new Time('2013-10-10 00:00')
  1549. ]);
  1550. $table = TableRegistry::get('users');
  1551. $this->assertSame($entity, $table->save($entity));
  1552. $this->assertEquals($entity->id, self::$nextUserId);
  1553. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1554. $this->assertEquals($entity->toArray(), $row->toArray());
  1555. }
  1556. /**
  1557. * Test that saving a new empty entity does nothing.
  1558. *
  1559. * @group save
  1560. * @return void
  1561. */
  1562. public function testSaveNewEmptyEntity()
  1563. {
  1564. $entity = new \Cake\ORM\Entity();
  1565. $table = TableRegistry::get('users');
  1566. $this->assertFalse($table->save($entity));
  1567. }
  1568. /**
  1569. * Test that saving a new empty entity does not call exists.
  1570. *
  1571. * @group save
  1572. * @return void
  1573. */
  1574. public function testSaveNewEntityNoExists()
  1575. {
  1576. $table = $this->getMockBuilder('Cake\ORM\Table')
  1577. ->setMethods(['exists'])
  1578. ->setConstructorArgs([[
  1579. 'connection' => $this->connection,
  1580. 'alias' => 'Users',
  1581. 'table' => 'users',
  1582. ]])
  1583. ->getMock();
  1584. $entity = $table->newEntity(['username' => 'mark']);
  1585. $this->assertTrue($entity->isNew());
  1586. $table->expects($this->never())
  1587. ->method('exists');
  1588. $this->assertSame($entity, $table->save($entity));
  1589. }
  1590. /**
  1591. * Test that saving a new entity with a Primary Key set does call exists.
  1592. *
  1593. * @group save
  1594. * @return void
  1595. */
  1596. public function testSavePrimaryKeyEntityExists()
  1597. {
  1598. $this->skipIfSqlServer();
  1599. $table = $this->getMockBuilder('Cake\ORM\Table')
  1600. ->setMethods(['exists'])
  1601. ->setConstructorArgs([[
  1602. 'connection' => $this->connection,
  1603. 'alias' => 'Users',
  1604. 'table' => 'users',
  1605. ]])
  1606. ->getMock();
  1607. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1608. $this->assertTrue($entity->isNew());
  1609. $table->expects($this->once())->method('exists');
  1610. $this->assertSame($entity, $table->save($entity));
  1611. }
  1612. /**
  1613. * Test that save works with replace saveStrategy and are not deleted once they are not null
  1614. *
  1615. * @return void
  1616. */
  1617. public function testSaveReplaceSaveStrategy()
  1618. {
  1619. $authors = new Table(
  1620. [
  1621. 'table' => 'authors',
  1622. 'alias' => 'Authors',
  1623. 'connection' => $this->connection,
  1624. 'entityClass' => 'Cake\ORM\Entity',
  1625. ]
  1626. );
  1627. $authors->hasMany('Articles', ['saveStrategy' => 'replace']);
  1628. $entity = $authors->newEntity([
  1629. 'name' => 'mylux',
  1630. 'articles' => [
  1631. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1632. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1633. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1634. ]
  1635. ], ['associated' => ['Articles']]);
  1636. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1637. $sizeArticles = count($entity->articles);
  1638. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1639. $articleId = $entity->articles[0]->id;
  1640. unset($entity->articles[0]);
  1641. $entity->dirty('articles', true);
  1642. $authors->save($entity, ['associated' => ['Articles']]);
  1643. $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1644. $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
  1645. }
  1646. /**
  1647. * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed
  1648. *
  1649. * @return void
  1650. */
  1651. public function testSaveReplaceSaveStrategyNotAdding()
  1652. {
  1653. $authors = new Table(
  1654. [
  1655. 'table' => 'authors',
  1656. 'alias' => 'Authors',
  1657. 'connection' => $this->connection,
  1658. 'entityClass' => 'Cake\ORM\Entity',
  1659. ]
  1660. );
  1661. $authors->hasMany('Articles', ['saveStrategy' => 'replace']);
  1662. $entity = $authors->newEntity([
  1663. 'name' => 'mylux',
  1664. 'articles' => [
  1665. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1666. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1667. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1668. ]
  1669. ], ['associated' => ['Articles']]);
  1670. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1671. $sizeArticles = count($entity->articles);
  1672. $this->assertCount($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
  1673. $entity->set('articles', []);
  1674. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1675. $this->assertCount(0, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
  1676. }
  1677. /**
  1678. * Test that save works with append saveStrategy not deleting or setting null anything
  1679. *
  1680. * @return void
  1681. */
  1682. public function testSaveAppendSaveStrategy()
  1683. {
  1684. $authors = new Table(
  1685. [
  1686. 'table' => 'authors',
  1687. 'alias' => 'Authors',
  1688. 'connection' => $this->connection,
  1689. 'entityClass' => 'Cake\ORM\Entity',
  1690. ]
  1691. );
  1692. $authors->hasMany('Articles', ['saveStrategy' => 'append']);
  1693. $entity = $authors->newEntity([
  1694. 'name' => 'mylux',
  1695. 'articles' => [
  1696. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1697. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1698. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1699. ]
  1700. ], ['associated' => ['Articles']]);
  1701. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1702. $sizeArticles = count($entity->articles);
  1703. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1704. $articleId = $entity->articles[0]->id;
  1705. unset($entity->articles[0]);
  1706. $entity->dirty('articles', true);
  1707. $authors->save($entity, ['associated' => ['Articles']]);
  1708. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1709. $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
  1710. }
  1711. /**
  1712. * Test that save has append as the default save strategy
  1713. *
  1714. * @return void
  1715. */
  1716. public function testSaveDefaultSaveStrategy()
  1717. {
  1718. $authors = new Table(
  1719. [
  1720. 'table' => 'authors',
  1721. 'alias' => 'Authors',
  1722. 'connection' => $this->connection,
  1723. 'entityClass' => 'Cake\ORM\Entity',
  1724. ]
  1725. );
  1726. $authors->hasMany('Articles', ['saveStrategy' => 'append']);
  1727. $this->assertEquals('append', $authors->association('articles')->saveStrategy());
  1728. }
  1729. /**
  1730. * Test that the associated entities are unlinked and deleted when they are dependent
  1731. *
  1732. * @return void
  1733. */
  1734. public function testSaveReplaceSaveStrategyDependent()
  1735. {
  1736. $authors = new Table(
  1737. [
  1738. 'table' => 'authors',
  1739. 'alias' => 'Authors',
  1740. 'connection' => $this->connection,
  1741. 'entityClass' => 'Cake\ORM\Entity',
  1742. ]
  1743. );
  1744. $authors->hasMany('Articles', ['saveStrategy' => 'replace', 'dependent' => true]);
  1745. $entity = $authors->newEntity([
  1746. 'name' => 'mylux',
  1747. 'articles' => [
  1748. ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
  1749. ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
  1750. ['title' => 'One more random post', 'body' => 'The cake is forever']
  1751. ]
  1752. ], ['associated' => ['Articles']]);
  1753. $entity = $authors->save($entity, ['associated' => ['Articles']]);
  1754. $sizeArticles = count($entity->articles);
  1755. $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1756. $articleId = $entity->articles[0]->id;
  1757. unset($entity->articles[0]);
  1758. $entity->dirty('articles', true);
  1759. $authors->save($entity, ['associated' => ['Articles']]);
  1760. $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
  1761. $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
  1762. }
  1763. /**
  1764. * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  1765. *
  1766. * @return void
  1767. */
  1768. public function testSaveReplaceSaveStrategyNotNullable()
  1769. {
  1770. $articles = new Table(
  1771. [
  1772. 'table' => 'articles',
  1773. 'alias' => 'Articles',
  1774. 'connection' => $this->connection,
  1775. 'entityClass' => 'Cake\ORM\Entity',
  1776. ]
  1777. );
  1778. $articles->hasMany('Comments', ['saveStrategy' => 'replace']);
  1779. $article = $articles->newEntity([
  1780. 'title' => 'Bakeries are sky rocketing',
  1781. 'body' => 'All because of cake',
  1782. 'comments' => [
  1783. [
  1784. 'user_id' => 1,
  1785. 'comment' => 'That is true!'
  1786. ],
  1787. [
  1788. 'user_id' => 2,
  1789. 'comment' => 'Of course'
  1790. ]
  1791. ]
  1792. ], ['associated' => ['Comments']]);
  1793. $article = $articles->save($article, ['associated' => ['Comments']]);
  1794. $commentId = $article->comments[0]->id;
  1795. $sizeComments = count($article->comments);
  1796. $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1797. $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
  1798. unset($article->comments[0]);
  1799. $article->dirty('comments', true);
  1800. $article = $articles->save($article, ['associated' => ['Comments']]);
  1801. $this->assertEquals($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1802. $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
  1803. }
  1804. /**
  1805. * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
  1806. *
  1807. * @return void
  1808. */
  1809. public function testSaveReplaceSaveStrategyAdding()
  1810. {
  1811. $articles = new Table(
  1812. [
  1813. 'table' => 'articles',
  1814. 'alias' => 'Articles',
  1815. 'connection' => $this->connection,
  1816. 'entityClass' => 'Cake\ORM\Entity',
  1817. ]
  1818. );
  1819. $articles->hasMany('Comments', ['saveStrategy' => 'replace']);
  1820. $article = $articles->newEntity([
  1821. 'title' => 'Bakeries are sky rocketing',
  1822. 'body' => 'All because of cake',
  1823. 'comments' => [
  1824. [
  1825. 'user_id' => 1,
  1826. 'comment' => 'That is true!'
  1827. ],
  1828. [
  1829. 'user_id' => 2,
  1830. 'comment' => 'Of course'
  1831. ]
  1832. ]
  1833. ], ['associated' => ['Comments']]);
  1834. $article = $articles->save($article, ['associated' => ['Comments']]);
  1835. $commentId = $article->comments[0]->id;
  1836. $sizeComments = count($article->comments);
  1837. $articleId = $article->id;
  1838. $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1839. $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
  1840. unset($article->comments[0]);
  1841. $article->comments[] = $articles->Comments->newEntity([
  1842. 'user_id' => 1,
  1843. 'comment' => 'new comment'
  1844. ]);
  1845. $article->dirty('comments', true);
  1846. $article = $articles->save($article, ['associated' => ['Comments']]);
  1847. $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
  1848. $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
  1849. $this->assertTrue($articles->Comments->exists(['comment' => 'new comment', 'article_id' => $articleId]));
  1850. }
  1851. /**
  1852. * Test that saving a new entity with a Primary Key set does not call exists when checkExisting is false.
  1853. *
  1854. * @group save
  1855. * @return void
  1856. */
  1857. public function testSavePrimaryKeyEntityNoExists()
  1858. {
  1859. $this->skipIfSqlServer();
  1860. $table = $this->getMockBuilder('Cake\ORM\Table')
  1861. ->setMethods(['exists'])
  1862. ->setConstructorArgs([[
  1863. 'connection' => $this->connection,
  1864. 'alias' => 'Users',
  1865. 'table' => 'users',
  1866. ]])
  1867. ->getMock();
  1868. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1869. $this->assertTrue($entity->isNew());
  1870. $table->expects($this->never())->method('exists');
  1871. $this->assertSame($entity, $table->save($entity, ['checkExisting' => false]));
  1872. }
  1873. /**
  1874. * Tests that saving an entity will filter out properties that
  1875. * are not present in the table schema when saving
  1876. *
  1877. * @group save
  1878. * @return void
  1879. */
  1880. public function testSaveEntityOnlySchemaFields()
  1881. {
  1882. $entity = new \Cake\ORM\Entity([
  1883. 'username' => 'superuser',
  1884. 'password' => 'root',
  1885. 'crazyness' => 'super crazy value',
  1886. 'created' => new Time('2013-10-10 00:00'),
  1887. 'updated' => new Time('2013-10-10 00:00'),
  1888. ]);
  1889. $table = TableRegistry::get('users');
  1890. $this->assertSame($entity, $table->save($entity));
  1891. $this->assertEquals($entity->id, self::$nextUserId);
  1892. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1893. $entity->unsetProperty('crazyness');
  1894. $this->assertEquals($entity->toArray(), $row->toArray());
  1895. }
  1896. /**
  1897. * Tests that it is possible to modify data from the beforeSave callback
  1898. *
  1899. * @group save
  1900. * @return void
  1901. */
  1902. public function testBeforeSaveModifyData()
  1903. {
  1904. $table = TableRegistry::get('users');
  1905. $data = new \Cake\ORM\Entity([
  1906. 'username' => 'superuser',
  1907. 'created' => new Time('2013-10-10 00:00'),
  1908. 'updated' => new Time('2013-10-10 00:00')
  1909. ]);
  1910. $listener = function ($e, $entity, $options) use ($data) {
  1911. $this->assertSame($data, $entity);
  1912. $entity->set('password', 'foo');
  1913. };
  1914. $table->eventManager()->on('Model.beforeSave', $listener);
  1915. $this->assertSame($data, $table->save($data));
  1916. $this->assertEquals($data->id, self::$nextUserId);
  1917. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1918. $this->assertEquals('foo', $row->get('password'));
  1919. }
  1920. /**
  1921. * Tests that it is possible to modify the options array in beforeSave
  1922. *
  1923. * @group save
  1924. * @return void
  1925. */
  1926. public function testBeforeSaveModifyOptions()
  1927. {
  1928. $table = TableRegistry::get('users');
  1929. $data = new \Cake\ORM\Entity([
  1930. 'username' => 'superuser',
  1931. 'password' => 'foo',
  1932. 'created' => new Time('2013-10-10 00:00'),
  1933. 'updated' => new Time('2013-10-10 00:00')
  1934. ]);
  1935. $listener1 = function ($e, $entity, $options) {
  1936. $options['crazy'] = true;
  1937. };
  1938. $listener2 = function ($e, $entity, $options) {
  1939. $this->assertTrue($options['crazy']);
  1940. };
  1941. $table->eventManager()->on('Model.beforeSave', $listener1);
  1942. $table->eventManager()->on('Model.beforeSave', $listener2);
  1943. $this->assertSame($data, $table->save($data));
  1944. $this->assertEquals($data->id, self::$nextUserId);
  1945. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1946. $this->assertEquals($data->toArray(), $row->toArray());
  1947. }
  1948. /**
  1949. * Tests that it is possible to stop the saving altogether, without implying
  1950. * the save operation failed
  1951. *
  1952. * @group save
  1953. * @return void
  1954. */
  1955. public function testBeforeSaveStopEvent()
  1956. {
  1957. $table = TableRegistry::get('users');
  1958. $data = new \Cake\ORM\Entity([
  1959. 'username' => 'superuser',
  1960. 'created' => new Time('2013-10-10 00:00'),
  1961. 'updated' => new Time('2013-10-10 00:00')
  1962. ]);
  1963. $listener = function ($e, $entity) {
  1964. $e->stopPropagation();
  1965. return $entity;
  1966. };
  1967. $table->eventManager()->on('Model.beforeSave', $listener);
  1968. $this->assertSame($data, $table->save($data));
  1969. $this->assertNull($data->id);
  1970. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1971. $this->assertNull($row);
  1972. }
  1973. /**
  1974. * Asserts that afterSave callback is called on successful save
  1975. *
  1976. * @group save
  1977. * @return void
  1978. */
  1979. public function testAfterSave()
  1980. {
  1981. $table = TableRegistry::get('users');
  1982. $data = new \Cake\ORM\Entity([
  1983. 'username' => 'superuser',
  1984. 'created' => new Time('2013-10-10 00:00'),
  1985. 'updated' => new Time('2013-10-10 00:00')
  1986. ]);
  1987. $called = false;
  1988. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1989. $this->assertSame($data, $entity);
  1990. $this->assertTrue($entity->dirty());
  1991. $called = true;
  1992. };
  1993. $table->eventManager()->on('Model.afterSave', $listener);
  1994. $calledAfterCommit = false;
  1995. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1996. $this->assertSame($data, $entity);
  1997. $this->assertFalse($entity->dirty());
  1998. $calledAfterCommit = true;
  1999. };
  2000. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2001. $this->assertSame($data, $table->save($data));
  2002. $this->assertEquals($data->id, self::$nextUserId);
  2003. $this->assertTrue($called);
  2004. $this->assertTrue($calledAfterCommit);
  2005. }
  2006. /**
  2007. * Asserts that afterSaveCommit is also triggered for non-atomic saves
  2008. *
  2009. * @return void
  2010. */
  2011. public function testAfterSaveCommitForNonAtomic()
  2012. {
  2013. $table = TableRegistry::get('users');
  2014. $data = new \Cake\ORM\Entity([
  2015. 'username' => 'superuser',
  2016. 'created' => new Time('2013-10-10 00:00'),
  2017. 'updated' => new Time('2013-10-10 00:00')
  2018. ]);
  2019. $called = false;
  2020. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2021. $this->assertSame($data, $entity);
  2022. $called = true;
  2023. };
  2024. $table->eventManager()->on('Model.afterSave', $listener);
  2025. $calledAfterCommit = false;
  2026. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2027. $calledAfterCommit = true;
  2028. };
  2029. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2030. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  2031. $this->assertEquals($data->id, self::$nextUserId);
  2032. $this->assertTrue($called);
  2033. $this->assertTrue($calledAfterCommit);
  2034. }
  2035. /**
  2036. * Asserts the afterSaveCommit is not triggered if transaction is running.
  2037. *
  2038. * @return void
  2039. */
  2040. public function testAfterSaveCommitWithTransactionRunning()
  2041. {
  2042. $table = TableRegistry::get('users');
  2043. $data = new \Cake\ORM\Entity([
  2044. 'username' => 'superuser',
  2045. 'created' => new Time('2013-10-10 00:00'),
  2046. 'updated' => new Time('2013-10-10 00:00')
  2047. ]);
  2048. $called = false;
  2049. $listener = function ($e, $entity, $options) use (&$called) {
  2050. $called = true;
  2051. };
  2052. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  2053. $this->connection->begin();
  2054. $this->assertSame($data, $table->save($data));
  2055. $this->assertFalse($called);
  2056. $this->connection->commit();
  2057. }
  2058. /**
  2059. * Asserts the afterSaveCommit is not triggered if transaction is running.
  2060. *
  2061. * @return void
  2062. */
  2063. public function testAfterSaveCommitWithNonAtomicAndTransactionRunning()
  2064. {
  2065. $table = TableRegistry::get('users');
  2066. $data = new \Cake\ORM\Entity([
  2067. 'username' => 'superuser',
  2068. 'created' => new Time('2013-10-10 00:00'),
  2069. 'updated' => new Time('2013-10-10 00:00')
  2070. ]);
  2071. $called = false;
  2072. $listener = function ($e, $entity, $options) use (&$called) {
  2073. $called = true;
  2074. };
  2075. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  2076. $this->connection->begin();
  2077. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  2078. $this->assertFalse($called);
  2079. $this->connection->commit();
  2080. }
  2081. /**
  2082. * Asserts that afterSave callback not is called on unsuccessful save
  2083. *
  2084. * @group save
  2085. * @return void
  2086. */
  2087. public function testAfterSaveNotCalled()
  2088. {
  2089. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2090. ->setMethods(['query'])
  2091. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2092. ->getMock();
  2093. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2094. ->setMethods(['execute', 'addDefaultTypes'])
  2095. ->setConstructorArgs([null, $table])
  2096. ->getMock();
  2097. $statement = $this->getMockBuilder('\Cake\Database\Statement\StatementDecorator')->getMock();
  2098. $data = new \Cake\ORM\Entity([
  2099. 'username' => 'superuser',
  2100. 'created' => new Time('2013-10-10 00:00'),
  2101. 'updated' => new Time('2013-10-10 00:00')
  2102. ]);
  2103. $table->expects($this->once())->method('query')
  2104. ->will($this->returnValue($query));
  2105. $query->expects($this->once())->method('execute')
  2106. ->will($this->returnValue($statement));
  2107. $statement->expects($this->once())->method('rowCount')
  2108. ->will($this->returnValue(0));
  2109. $called = false;
  2110. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2111. $called = true;
  2112. };
  2113. $table->eventManager()->on('Model.afterSave', $listener);
  2114. $calledAfterCommit = false;
  2115. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2116. $calledAfterCommit = true;
  2117. };
  2118. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  2119. $this->assertFalse($table->save($data));
  2120. $this->assertFalse($called);
  2121. $this->assertFalse($calledAfterCommit);
  2122. }
  2123. /**
  2124. * Asserts that afterSaveCommit callback is triggered only for primary table
  2125. *
  2126. * @group save
  2127. * @return void
  2128. */
  2129. public function testAfterSaveCommitTriggeredOnlyForPrimaryTable()
  2130. {
  2131. $entity = new \Cake\ORM\Entity([
  2132. 'title' => 'A Title',
  2133. 'body' => 'A body'
  2134. ]);
  2135. $entity->author = new \Cake\ORM\Entity([
  2136. 'name' => 'Jose'
  2137. ]);
  2138. $table = TableRegistry::get('articles');
  2139. $table->belongsTo('authors');
  2140. $calledForArticle = false;
  2141. $listenerForArticle = function ($e, $entity, $options) use (&$calledForArticle) {
  2142. $calledForArticle = true;
  2143. };
  2144. $table->eventManager()->on('Model.afterSaveCommit', $listenerForArticle);
  2145. $calledForAuthor = false;
  2146. $listenerForAuthor = function ($e, $entity, $options) use (&$calledForAuthor) {
  2147. $calledForAuthor = true;
  2148. };
  2149. $table->authors->eventManager()->on('Model.afterSaveCommit', $listenerForAuthor);
  2150. $this->assertSame($entity, $table->save($entity));
  2151. $this->assertFalse($entity->isNew());
  2152. $this->assertFalse($entity->author->isNew());
  2153. $this->assertTrue($calledForArticle);
  2154. $this->assertFalse($calledForAuthor);
  2155. }
  2156. /**
  2157. * Test that you cannot save rows without a primary key.
  2158. *
  2159. * @group save
  2160. * @expectedException \RuntimeException
  2161. * @expectedExceptionMessage Cannot insert row in "users" table, it has no primary key
  2162. * @return void
  2163. */
  2164. public function testSaveNewErrorOnNoPrimaryKey()
  2165. {
  2166. $entity = new \Cake\ORM\Entity(['username' => 'superuser']);
  2167. $table = TableRegistry::get('users', [
  2168. 'schema' => [
  2169. 'id' => ['type' => 'integer'],
  2170. 'username' => ['type' => 'string'],
  2171. ]
  2172. ]);
  2173. $table->save($entity);
  2174. }
  2175. /**
  2176. * Tests that save is wrapped around a transaction
  2177. *
  2178. * @group save
  2179. * @return void
  2180. */
  2181. public function testAtomicSave()
  2182. {
  2183. $config = ConnectionManager::config('test');
  2184. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  2185. ->setMethods(['begin', 'commit', 'inTransaction'])
  2186. ->setConstructorArgs([$config])
  2187. ->getMock();
  2188. $connection->driver($this->connection->driver());
  2189. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2190. ->setMethods(['connection'])
  2191. ->setConstructorArgs([['table' => 'users']])
  2192. ->getMock();
  2193. $table->expects($this->any())->method('connection')
  2194. ->will($this->returnValue($connection));
  2195. $connection->expects($this->once())->method('begin');
  2196. $connection->expects($this->once())->method('commit');
  2197. $connection->expects($this->any())->method('inTransaction')->will($this->returnValue(true));
  2198. $data = new \Cake\ORM\Entity([
  2199. 'username' => 'superuser',
  2200. 'created' => new Time('2013-10-10 00:00'),
  2201. 'updated' => new Time('2013-10-10 00:00')
  2202. ]);
  2203. $this->assertSame($data, $table->save($data));
  2204. }
  2205. /**
  2206. * Tests that save will rollback the transaction in the case of an exception
  2207. *
  2208. * @group save
  2209. * @expectedException \PDOException
  2210. * @return void
  2211. */
  2212. public function testAtomicSaveRollback()
  2213. {
  2214. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  2215. ->setMethods(['begin', 'rollback'])
  2216. ->setConstructorArgs([ConnectionManager::config('test')])
  2217. ->getMock();
  2218. $connection->driver(ConnectionManager::get('test')->driver());
  2219. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2220. ->setMethods(['query', 'connection'])
  2221. ->setConstructorArgs([['table' => 'users']])
  2222. ->getMock();
  2223. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2224. ->setMethods(['execute', 'addDefaultTypes'])
  2225. ->setConstructorArgs([null, $table])
  2226. ->getMock();
  2227. $table->expects($this->any())->method('connection')
  2228. ->will($this->returnValue($connection));
  2229. $table->expects($this->once())->method('query')
  2230. ->will($this->returnValue($query));
  2231. $connection->expects($this->once())->method('begin');
  2232. $connection->expects($this->once())->method('rollback');
  2233. $query->expects($this->once())->method('execute')
  2234. ->will($this->throwException(new \PDOException));
  2235. $data = new \Cake\ORM\Entity([
  2236. 'username' => 'superuser',
  2237. 'created' => new Time('2013-10-10 00:00'),
  2238. 'updated' => new Time('2013-10-10 00:00')
  2239. ]);
  2240. $table->save($data);
  2241. }
  2242. /**
  2243. * Tests that save will rollback the transaction in the case of an exception
  2244. *
  2245. * @group save
  2246. * @return void
  2247. */
  2248. public function testAtomicSaveRollbackOnFailure()
  2249. {
  2250. $connection = $this->getMockBuilder('\Cake\Database\Connection')
  2251. ->setMethods(['begin', 'rollback'])
  2252. ->setConstructorArgs([ConnectionManager::config('test')])
  2253. ->getMock();
  2254. $connection->driver(ConnectionManager::get('test')->driver());
  2255. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2256. ->setMethods(['query', 'connection', 'exists'])
  2257. ->setConstructorArgs([['table' => 'users']])
  2258. ->getMock();
  2259. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2260. ->setMethods(['execute', 'addDefaultTypes'])
  2261. ->setConstructorArgs([null, $table])
  2262. ->getMock();
  2263. $table->expects($this->any())->method('connection')
  2264. ->will($this->returnValue($connection));
  2265. $table->expects($this->once())->method('query')
  2266. ->will($this->returnValue($query));
  2267. $statement = $this->getMockBuilder('\Cake\Database\Statement\StatementDecorator')->getMock();
  2268. $statement->expects($this->once())
  2269. ->method('rowCount')
  2270. ->will($this->returnValue(0));
  2271. $connection->expects($this->once())->method('begin');
  2272. $connection->expects($this->once())->method('rollback');
  2273. $query->expects($this->once())
  2274. ->method('execute')
  2275. ->will($this->returnValue($statement));
  2276. $data = new \Cake\ORM\Entity([
  2277. 'username' => 'superuser',
  2278. 'created' => new Time('2013-10-10 00:00'),
  2279. 'updated' => new Time('2013-10-10 00:00')
  2280. ]);
  2281. $table->save($data);
  2282. }
  2283. /**
  2284. * Tests that only the properties marked as dirty are actually saved
  2285. * to the database
  2286. *
  2287. * @group save
  2288. * @return void
  2289. */
  2290. public function testSaveOnlyDirtyProperties()
  2291. {
  2292. $entity = new \Cake\ORM\Entity([
  2293. 'username' => 'superuser',
  2294. 'password' => 'root',
  2295. 'created' => new Time('2013-10-10 00:00'),
  2296. 'updated' => new Time('2013-10-10 00:00')
  2297. ]);
  2298. $entity->clean();
  2299. $entity->dirty('username', true);
  2300. $entity->dirty('created', true);
  2301. $entity->dirty('updated', true);
  2302. $table = TableRegistry::get('users');
  2303. $this->assertSame($entity, $table->save($entity));
  2304. $this->assertEquals($entity->id, self::$nextUserId);
  2305. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  2306. $entity->set('password', null);
  2307. $this->assertEquals($entity->toArray(), $row->toArray());
  2308. }
  2309. /**
  2310. * Tests that a recently saved entity is marked as clean
  2311. *
  2312. * @group save
  2313. * @return void
  2314. */
  2315. public function testASavedEntityIsClean()
  2316. {
  2317. $entity = new \Cake\ORM\Entity([
  2318. 'username' => 'superuser',
  2319. 'password' => 'root',
  2320. 'created' => new Time('2013-10-10 00:00'),
  2321. 'updated' => new Time('2013-10-10 00:00')
  2322. ]);
  2323. $table = TableRegistry::get('users');
  2324. $this->assertSame($entity, $table->save($entity));
  2325. $this->assertFalse($entity->dirty('usermane'));
  2326. $this->assertFalse($entity->dirty('password'));
  2327. $this->assertFalse($entity->dirty('created'));
  2328. $this->assertFalse($entity->dirty('updated'));
  2329. }
  2330. /**
  2331. * Tests that a recently saved entity is marked as not new
  2332. *
  2333. * @group save
  2334. * @return void
  2335. */
  2336. public function testASavedEntityIsNotNew()
  2337. {
  2338. $entity = new \Cake\ORM\Entity([
  2339. 'username' => 'superuser',
  2340. 'password' => 'root',
  2341. 'created' => new Time('2013-10-10 00:00'),
  2342. 'updated' => new Time('2013-10-10 00:00')
  2343. ]);
  2344. $table = TableRegistry::get('users');
  2345. $this->assertSame($entity, $table->save($entity));
  2346. $this->assertFalse($entity->isNew());
  2347. }
  2348. /**
  2349. * Tests that save can detect automatically if it needs to insert
  2350. * or update a row
  2351. *
  2352. * @group save
  2353. * @return void
  2354. */
  2355. public function testSaveUpdateAuto()
  2356. {
  2357. $entity = new \Cake\ORM\Entity([
  2358. 'id' => 2,
  2359. 'username' => 'baggins'
  2360. ]);
  2361. $table = TableRegistry::get('users');
  2362. $original = $table->find('all')->where(['id' => 2])->first();
  2363. $this->assertSame($entity, $table->save($entity));
  2364. $row = $table->find('all')->where(['id' => 2])->first();
  2365. $this->assertEquals('baggins', $row->username);
  2366. $this->assertEquals($original->password, $row->password);
  2367. $this->assertEquals($original->created, $row->created);
  2368. $this->assertEquals($original->updated, $row->updated);
  2369. $this->assertFalse($entity->isNew());
  2370. $this->assertFalse($entity->dirty('id'));
  2371. $this->assertFalse($entity->dirty('username'));
  2372. }
  2373. /**
  2374. * Tests that beforeFind gets the correct isNew() state for the entity
  2375. *
  2376. * @return void
  2377. */
  2378. public function testBeforeSaveGetsCorrectPersistance()
  2379. {
  2380. $entity = new \Cake\ORM\Entity([
  2381. 'id' => 2,
  2382. 'username' => 'baggins'
  2383. ]);
  2384. $table = TableRegistry::get('users');
  2385. $called = false;
  2386. $listener = function ($event, $entity) use (&$called) {
  2387. $this->assertFalse($entity->isNew());
  2388. $called = true;
  2389. };
  2390. $table->eventManager()->on('Model.beforeSave', $listener);
  2391. $this->assertSame($entity, $table->save($entity));
  2392. $this->assertTrue($called);
  2393. }
  2394. /**
  2395. * Tests that marking an entity as already persisted will prevent the save
  2396. * method from trying to infer the entity's actual status.
  2397. *
  2398. * @group save
  2399. * @return void
  2400. */
  2401. public function testSaveUpdateWithHint()
  2402. {
  2403. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2404. ->setMethods(['exists'])
  2405. ->setConstructorArgs([['table' => 'users', 'connection' => ConnectionManager::get('test')]])
  2406. ->getMock();
  2407. $entity = new \Cake\ORM\Entity([
  2408. 'id' => 2,
  2409. 'username' => 'baggins'
  2410. ], ['markNew' => false]);
  2411. $this->assertFalse($entity->isNew());
  2412. $table->expects($this->never())->method('exists');
  2413. $this->assertSame($entity, $table->save($entity));
  2414. }
  2415. /**
  2416. * Tests that when updating the primary key is not passed to the list of
  2417. * attributes to change
  2418. *
  2419. * @group save
  2420. * @return void
  2421. */
  2422. public function testSaveUpdatePrimaryKeyNotModified()
  2423. {
  2424. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2425. ->setMethods(['query'])
  2426. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2427. ->getMock();
  2428. $query = $this->getMockBuilder('\Cake\ORM\Query')
  2429. ->setMethods(['execute', 'addDefaultTypes', 'set'])
  2430. ->setConstructorArgs([null, $table])
  2431. ->getMock();
  2432. $table->expects($this->once())->method('query')
  2433. ->will($this->returnValue($query));
  2434. $statement = $this->getMockBuilder('\Cake\Database\Statement\StatementDecorator')->getMock();
  2435. $statement->expects($this->once())
  2436. ->method('errorCode')
  2437. ->will($this->returnValue('00000'));
  2438. $query->expects($this->once())
  2439. ->method('execute')
  2440. ->will($this->returnValue($statement));
  2441. $query->expects($this->once())->method('set')
  2442. ->with(['username' => 'baggins'])
  2443. ->will($this->returnValue($query));
  2444. $entity = new \Cake\ORM\Entity([
  2445. 'id' => 2,
  2446. 'username' => 'baggins'
  2447. ], ['markNew' => false]);
  2448. $this->assertSame($entity, $table->save($entity));
  2449. }
  2450. /**
  2451. * Tests that passing only the primary key to save will not execute any queries
  2452. * but still return success
  2453. *
  2454. * @group save
  2455. * @return void
  2456. */
  2457. public function testUpdateNoChange()
  2458. {
  2459. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2460. ->setMethods(['query'])
  2461. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2462. ->getMock();
  2463. $table->expects($this->never())->method('query');
  2464. $entity = new \Cake\ORM\Entity([
  2465. 'id' => 2,
  2466. ], ['markNew' => false]);
  2467. $this->assertSame($entity, $table->save($entity));
  2468. }
  2469. /**
  2470. * Tests that passing only the primary key to save will not execute any queries
  2471. * but still return success
  2472. *
  2473. * @group save
  2474. * @group integration
  2475. * @return void
  2476. */
  2477. public function testUpdateDirtyNoActualChanges()
  2478. {
  2479. $table = TableRegistry::get('Articles');
  2480. $entity = $table->get(1);
  2481. $entity->accessible('*', true);
  2482. $entity->set($entity->toArray());
  2483. $this->assertSame($entity, $table->save($entity));
  2484. }
  2485. /**
  2486. * Tests that failing to pass a primary key to save will result in exception
  2487. *
  2488. * @group save
  2489. * @expectedException \InvalidArgumentException
  2490. * @return void
  2491. */
  2492. public function testUpdateNoPrimaryButOtherKeys()
  2493. {
  2494. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2495. ->setMethods(['query'])
  2496. ->setConstructorArgs([['table' => 'users', 'connection' => $this->connection]])
  2497. ->getMock();
  2498. $table->expects($this->never())->method('query');
  2499. $entity = new \Cake\ORM\Entity([
  2500. 'username' => 'mariano',
  2501. ], ['markNew' => false]);
  2502. $this->assertSame($entity, $table->save($entity));
  2503. }
  2504. /**
  2505. * Test saveMany() with entities array
  2506. *
  2507. * @return void
  2508. */
  2509. public function testSaveManyArray()
  2510. {
  2511. $entities = [
  2512. new Entity(['name' => 'admad']),
  2513. new Entity(['name' => 'dakota'])
  2514. ];
  2515. $table = TableRegistry::get('authors');
  2516. $result = $table->saveMany($entities);
  2517. $this->assertSame($entities, $result);
  2518. $this->assertTrue(isset($result[0]->id));
  2519. foreach ($entities as $entity) {
  2520. $this->assertFalse($entity->isNew());
  2521. }
  2522. }
  2523. /**
  2524. * Test saveMany() with ResultSet instance
  2525. *
  2526. * @return void
  2527. */
  2528. public function testSaveManyResultSet()
  2529. {
  2530. $table = TableRegistry::get('authors');
  2531. $entities = $table->find()
  2532. ->order(['id' => 'ASC'])
  2533. ->all();
  2534. $entities->first()->name = 'admad';
  2535. $result = $table->saveMany($entities);
  2536. $this->assertSame($entities, $result);
  2537. $first = $table->find()
  2538. ->order(['id' => 'ASC'])
  2539. ->first();
  2540. $this->assertSame('admad', $first->name);
  2541. }
  2542. /**
  2543. * Test saveMany() with failed save
  2544. *
  2545. * @return void
  2546. */
  2547. public function testSaveManyFailed()
  2548. {
  2549. $table = TableRegistry::get('authors');
  2550. $entities = [
  2551. new Entity(['name' => 'mark']),
  2552. new Entity(['name' => 'jose'])
  2553. ];
  2554. $entities[1]->errors(['name' => ['message']]);
  2555. $result = $table->saveMany($entities);
  2556. $this->assertFalse($result);
  2557. foreach ($entities as $entity) {
  2558. $this->assertTrue($entity->isNew());
  2559. }
  2560. }
  2561. /**
  2562. * Test simple delete.
  2563. *
  2564. * @return void
  2565. */
  2566. public function testDelete()
  2567. {
  2568. $table = TableRegistry::get('users');
  2569. $conditions = [
  2570. 'limit' => 1,
  2571. 'conditions' => [
  2572. 'username' => 'nate'
  2573. ]
  2574. ];
  2575. $query = $table->find('all', $conditions);
  2576. $entity = $query->first();
  2577. $result = $table->delete($entity);
  2578. $this->assertTrue($result);
  2579. $query = $table->find('all', $conditions);
  2580. $results = $query->execute();
  2581. $this->assertCount(0, $results, 'Find should fail.');
  2582. }
  2583. /**
  2584. * Test delete with dependent records
  2585. *
  2586. * @return void
  2587. */
  2588. public function testDeleteDependent()
  2589. {
  2590. $table = TableRegistry::get('authors');
  2591. $table->hasOne('articles', [
  2592. 'foreignKey' => 'author_id',
  2593. 'dependent' => true,
  2594. ]);
  2595. $entity = $table->get(1);
  2596. $result = $table->delete($entity);
  2597. $articles = $table->association('articles')->target();
  2598. $query = $articles->find('all', [
  2599. 'conditions' => [
  2600. 'author_id' => $entity->id
  2601. ]
  2602. ]);
  2603. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2604. }
  2605. /**
  2606. * Test delete with dependent records
  2607. *
  2608. * @return void
  2609. */
  2610. public function testDeleteDependentHasMany()
  2611. {
  2612. $table = TableRegistry::get('authors');
  2613. $table->hasMany('articles', [
  2614. 'foreignKey' => 'author_id',
  2615. 'dependent' => true,
  2616. 'cascadeCallbacks' => true,
  2617. ]);
  2618. $entity = $table->get(1);
  2619. $result = $table->delete($entity);
  2620. $this->assertTrue($result);
  2621. }
  2622. /**
  2623. * Test delete with dependent = false does not cascade.
  2624. *
  2625. * @return void
  2626. */
  2627. public function testDeleteNoDependentNoCascade()
  2628. {
  2629. $table = TableRegistry::get('authors');
  2630. $table->hasMany('article', [
  2631. 'foreignKey' => 'author_id',
  2632. 'dependent' => false,
  2633. ]);
  2634. $query = $table->find('all')->where(['id' => 1]);
  2635. $entity = $query->first();
  2636. $result = $table->delete($entity);
  2637. $articles = $table->association('articles')->target();
  2638. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  2639. $this->assertCount(2, $query->execute(), 'Should find rows.');
  2640. }
  2641. /**
  2642. * Test delete with BelongsToMany
  2643. *
  2644. * @return void
  2645. */
  2646. public function testDeleteBelongsToMany()
  2647. {
  2648. $table = TableRegistry::get('articles');
  2649. $table->belongsToMany('tag', [
  2650. 'foreignKey' => 'article_id',
  2651. 'joinTable' => 'articles_tags'
  2652. ]);
  2653. $query = $table->find('all')->where(['id' => 1]);
  2654. $entity = $query->first();
  2655. $table->delete($entity);
  2656. $junction = $table->association('tags')->junction();
  2657. $query = $junction->find('all')->where(['article_id' => 1]);
  2658. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2659. }
  2660. /**
  2661. * Test delete with dependent records belonging to an aliased
  2662. * belongsToMany association.
  2663. *
  2664. * @return void
  2665. */
  2666. public function testDeleteDependentAliased()
  2667. {
  2668. $Authors = TableRegistry::get('authors');
  2669. $Authors->associations()->removeAll();
  2670. $Articles = TableRegistry::get('articles');
  2671. $Articles->associations()->removeAll();
  2672. $Authors->hasMany('AliasedArticles', [
  2673. 'className' => 'articles',
  2674. 'dependent' => true,
  2675. 'cascadeCallbacks' => true
  2676. ]);
  2677. $Articles->belongsToMany('Tags');
  2678. $author = $Authors->get(1);
  2679. $result = $Authors->delete($author);
  2680. $this->assertTrue($result);
  2681. }
  2682. /**
  2683. * Test that cascading associations are deleted first.
  2684. *
  2685. * @return void
  2686. */
  2687. public function testDeleteAssociationsCascadingCallbacksOrder()
  2688. {
  2689. $groups = TableRegistry::get('Groups');
  2690. $members = TableRegistry::get('Members');
  2691. $groupsMembers = TableRegistry::get('GroupsMembers');
  2692. $groups->belongsToMany('Members');
  2693. $groups->hasMany('GroupsMembers', [
  2694. 'dependent' => true,
  2695. 'cascadeCallbacks' => true,
  2696. ]);
  2697. $groupsMembers->belongsTo('Members');
  2698. $groupsMembers->addBehavior('CounterCache', [
  2699. 'Members' => ['group_count']
  2700. ]);
  2701. $member = $members->get(1);
  2702. $this->assertEquals(2, $member->group_count);
  2703. $group = $groups->get(1);
  2704. $groups->delete($group);
  2705. $member = $members->get(1);
  2706. $this->assertEquals(1, $member->group_count);
  2707. }
  2708. /**
  2709. * Test delete callbacks
  2710. *
  2711. * @return void
  2712. */
  2713. public function testDeleteCallbacks()
  2714. {
  2715. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2716. $options = new \ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]);
  2717. $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  2718. $mock->expects($this->at(0))
  2719. ->method('on');
  2720. $mock->expects($this->at(1))
  2721. ->method('dispatch');
  2722. $mock->expects($this->at(2))
  2723. ->method('dispatch')
  2724. ->with($this->logicalAnd(
  2725. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  2726. $this->attributeEqualTo(
  2727. 'data',
  2728. ['entity' => $entity, 'options' => $options]
  2729. )
  2730. ));
  2731. $mock->expects($this->at(3))
  2732. ->method('dispatch')
  2733. ->with($this->logicalAnd(
  2734. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  2735. $this->attributeEqualTo(
  2736. 'data',
  2737. ['entity' => $entity, 'options' => $options]
  2738. )
  2739. ));
  2740. $mock->expects($this->at(4))
  2741. ->method('dispatch')
  2742. ->with($this->logicalAnd(
  2743. $this->attributeEqualTo('_name', 'Model.afterDeleteCommit'),
  2744. $this->attributeEqualTo(
  2745. 'data',
  2746. ['entity' => $entity, 'options' => $options]
  2747. )
  2748. ));
  2749. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2750. $entity->isNew(false);
  2751. $table->delete($entity, ['checkRules' => false]);
  2752. }
  2753. /**
  2754. * Test afterDeleteCommit is also called for non-atomic delete
  2755. *
  2756. * @return void
  2757. */
  2758. public function testDeleteCallbacksNonAtomic()
  2759. {
  2760. $table = TableRegistry::get('users');
  2761. $data = $table->get(1);
  2762. $options = new \ArrayObject(['atomic' => false, 'checkRules' => false]);
  2763. $called = false;
  2764. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2765. $this->assertSame($data, $entity);
  2766. $called = true;
  2767. };
  2768. $table->eventManager()->on('Model.afterDelete', $listener);
  2769. $calledAfterCommit = false;
  2770. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2771. $calledAfterCommit = true;
  2772. };
  2773. $table->eventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit);
  2774. $table->delete($data, ['atomic' => false]);
  2775. $this->assertTrue($called);
  2776. $this->assertTrue($calledAfterCommit);
  2777. }
  2778. /**
  2779. * Test that afterDeleteCommit is only triggered for primary table
  2780. *
  2781. * @return void
  2782. */
  2783. public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable()
  2784. {
  2785. $table = TableRegistry::get('authors');
  2786. $table->hasOne('articles', [
  2787. 'foreignKey' => 'author_id',
  2788. 'dependent' => true,
  2789. ]);
  2790. $called = false;
  2791. $listener = function ($e, $entity, $options) use (&$called) {
  2792. $called = true;
  2793. };
  2794. $table->eventManager()->on('Model.afterDeleteCommit', $listener);
  2795. $called2 = false;
  2796. $listener = function ($e, $entity, $options) use (&$called2) {
  2797. $called2 = true;
  2798. };
  2799. $table->articles->eventManager()->on('Model.afterDeleteCommit', $listener);
  2800. $entity = $table->get(1);
  2801. $this->assertTrue($table->delete($entity));
  2802. $this->assertTrue($called);
  2803. $this->assertFalse($called2);
  2804. }
  2805. /**
  2806. * Test delete beforeDelete can abort the delete.
  2807. *
  2808. * @return void
  2809. */
  2810. public function testDeleteBeforeDeleteAbort()
  2811. {
  2812. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2813. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2814. $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  2815. $mock->expects($this->at(2))
  2816. ->method('dispatch')
  2817. ->will($this->returnCallback(function ($event) {
  2818. $event->stopPropagation();
  2819. }));
  2820. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2821. $entity->isNew(false);
  2822. $result = $table->delete($entity, ['checkRules' => false]);
  2823. $this->assertNull($result);
  2824. }
  2825. /**
  2826. * Test delete beforeDelete return result
  2827. *
  2828. * @return void
  2829. */
  2830. public function testDeleteBeforeDeleteReturnResult()
  2831. {
  2832. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2833. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2834. $mock = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  2835. $mock->expects($this->at(2))
  2836. ->method('dispatch')
  2837. ->will($this->returnCallback(function ($event) {
  2838. $event->stopPropagation();
  2839. $event->result = 'got stopped';
  2840. }));
  2841. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2842. $entity->isNew(false);
  2843. $result = $table->delete($entity, ['checkRules' => false]);
  2844. $this->assertEquals('got stopped', $result);
  2845. }
  2846. /**
  2847. * Test deleting new entities does nothing.
  2848. *
  2849. * @return void
  2850. */
  2851. public function testDeleteIsNew()
  2852. {
  2853. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2854. $table = $this->getMockBuilder('Cake\ORM\Table')
  2855. ->setMethods(['query'])
  2856. ->setConstructorArgs([['connection' => $this->connection]])
  2857. ->getMock();
  2858. $table->expects($this->never())
  2859. ->method('query');
  2860. $entity->isNew(true);
  2861. $result = $table->delete($entity);
  2862. $this->assertFalse($result);
  2863. }
  2864. /**
  2865. * test hasField()
  2866. *
  2867. * @return void
  2868. */
  2869. public function testHasField()
  2870. {
  2871. $table = TableRegistry::get('articles');
  2872. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  2873. $this->assertTrue($table->hasField('title'), 'Should be there.');
  2874. $this->assertTrue($table->hasField('body'), 'Should be there.');
  2875. }
  2876. /**
  2877. * Tests that there exists a default validator
  2878. *
  2879. * @return void
  2880. */
  2881. public function testValidatorDefault()
  2882. {
  2883. $table = new Table();
  2884. $validator = $table->validator();
  2885. $this->assertSame($table, $validator->provider('table'));
  2886. $this->assertInstanceOf('Cake\Validation\Validator', $validator);
  2887. $default = $table->validator('default');
  2888. $this->assertSame($validator, $default);
  2889. }
  2890. /**
  2891. * Tests that it is possible to define custom validator methods
  2892. *
  2893. * @return void
  2894. */
  2895. public function testValidationWithDefiner()
  2896. {
  2897. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2898. ->setMethods(['validationForOtherStuff'])
  2899. ->getMock();
  2900. $table->expects($this->once())->method('validationForOtherStuff')
  2901. ->will($this->returnArgument(0));
  2902. $other = $table->validator('forOtherStuff');
  2903. $this->assertInstanceOf('Cake\Validation\Validator', $other);
  2904. $this->assertNotSame($other, $table->validator());
  2905. $this->assertSame($table, $other->provider('table'));
  2906. }
  2907. /**
  2908. * Tests that a RuntimeException is thrown if the custom validator does not return an Validator instance
  2909. *
  2910. * @return void
  2911. * @expectedException \RuntimeException
  2912. * @expectedExceptionMessage The Cake\ORM\Table::validationBad() validation method must return an instance of Cake\Validation\Validator.
  2913. */
  2914. public function testValidationWithBadDefiner()
  2915. {
  2916. $table = $this->getMockBuilder('\Cake\ORM\Table')
  2917. ->setMethods(['validationBad'])
  2918. ->getMock();
  2919. $table->expects($this->once())
  2920. ->method('validationBad');
  2921. $table->validator('bad');
  2922. }
  2923. /**
  2924. * Tests that it is possible to set a custom validator under a name
  2925. *
  2926. * @return void
  2927. */
  2928. public function testValidatorSetter()
  2929. {
  2930. $table = new Table;
  2931. $validator = new \Cake\Validation\Validator;
  2932. $table->validator('other', $validator);
  2933. $this->assertSame($validator, $table->validator('other'));
  2934. $this->assertSame($table, $validator->provider('table'));
  2935. }
  2936. /**
  2937. * Tests that the source of an existing Entity is the same as a new one
  2938. *
  2939. * @return void
  2940. */
  2941. public function testEntitySourceExistingAndNew()
  2942. {
  2943. Plugin::load('TestPlugin');
  2944. $table = TableRegistry::get('TestPlugin.Authors');
  2945. $existingAuthor = $table->find()->first();
  2946. $newAuthor = $table->newEntity();
  2947. $this->assertEquals('TestPlugin.Authors', $existingAuthor->source());
  2948. $this->assertEquals('TestPlugin.Authors', $newAuthor->source());
  2949. }
  2950. /**
  2951. * Tests that calling an entity with an empty array will run validation
  2952. * whereas calling it with no parameters will not run any validation.
  2953. *
  2954. * @return void
  2955. */
  2956. public function testNewEntityAndValidation()
  2957. {
  2958. $table = TableRegistry::get('Articles');
  2959. $validator = $table->validator()->requirePresence('title');
  2960. $entity = $table->newEntity([]);
  2961. $errors = $entity->errors();
  2962. $this->assertNotEmpty($errors['title']);
  2963. $entity = $table->newEntity();
  2964. $this->assertEmpty($entity->errors());
  2965. }
  2966. /**
  2967. * Test magic findByXX method.
  2968. *
  2969. * @return void
  2970. */
  2971. public function testMagicFindDefaultToAll()
  2972. {
  2973. $table = TableRegistry::get('Users');
  2974. $result = $table->findByUsername('garrett');
  2975. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2976. $expected = new QueryExpression(['Users.username' => 'garrett'], $this->usersTypeMap);
  2977. $this->assertEquals($expected, $result->clause('where'));
  2978. }
  2979. /**
  2980. * Test magic findByXX errors on missing arguments.
  2981. *
  2982. * @expectedException \BadMethodCallException
  2983. * @expectedExceptionMessage Not enough arguments for magic finder. Got 0 required 1
  2984. * @return void
  2985. */
  2986. public function testMagicFindError()
  2987. {
  2988. $table = TableRegistry::get('Users');
  2989. $table->findByUsername();
  2990. }
  2991. /**
  2992. * Test magic findByXX errors on missing arguments.
  2993. *
  2994. * @expectedException \BadMethodCallException
  2995. * @expectedExceptionMessage Not enough arguments for magic finder. Got 1 required 2
  2996. * @return void
  2997. */
  2998. public function testMagicFindErrorMissingField()
  2999. {
  3000. $table = TableRegistry::get('Users');
  3001. $table->findByUsernameAndId('garrett');
  3002. }
  3003. /**
  3004. * Test magic findByXX errors when there is a mix of or & and.
  3005. *
  3006. * @expectedException \BadMethodCallException
  3007. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  3008. * @return void
  3009. */
  3010. public function testMagicFindErrorMixOfOperators()
  3011. {
  3012. $table = TableRegistry::get('Users');
  3013. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  3014. }
  3015. /**
  3016. * Test magic findByXX method.
  3017. *
  3018. * @return void
  3019. */
  3020. public function testMagicFindFirstAnd()
  3021. {
  3022. $table = TableRegistry::get('Users');
  3023. $result = $table->findByUsernameAndId('garrett', 4);
  3024. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3025. $expected = new QueryExpression(['Users.username' => 'garrett', 'Users.id' => 4], $this->usersTypeMap);
  3026. $this->assertEquals($expected, $result->clause('where'));
  3027. }
  3028. /**
  3029. * Test magic findByXX method.
  3030. *
  3031. * @return void
  3032. */
  3033. public function testMagicFindFirstOr()
  3034. {
  3035. $table = TableRegistry::get('Users');
  3036. $result = $table->findByUsernameOrId('garrett', 4);
  3037. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3038. $expected = new QueryExpression([], $this->usersTypeMap);
  3039. $expected->add(
  3040. [
  3041. 'OR' => [
  3042. 'Users.username' => 'garrett',
  3043. 'Users.id' => 4
  3044. ]]
  3045. );
  3046. $this->assertEquals($expected, $result->clause('where'));
  3047. }
  3048. /**
  3049. * Test magic findAllByXX method.
  3050. *
  3051. * @return void
  3052. */
  3053. public function testMagicFindAll()
  3054. {
  3055. $table = TableRegistry::get('Articles');
  3056. $result = $table->findAllByAuthorId(1);
  3057. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3058. $this->assertNull($result->clause('limit'));
  3059. $expected = new QueryExpression(['Articles.author_id' => 1], $this->articlesTypeMap);
  3060. $this->assertEquals($expected, $result->clause('where'));
  3061. }
  3062. /**
  3063. * Test magic findAllByXX method.
  3064. *
  3065. * @return void
  3066. */
  3067. public function testMagicFindAllAnd()
  3068. {
  3069. $table = TableRegistry::get('Users');
  3070. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  3071. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3072. $this->assertNull($result->clause('limit'));
  3073. $expected = new QueryExpression(
  3074. ['Users.author_id' => 1, 'Users.published' => 'Y'],
  3075. $this->usersTypeMap
  3076. );
  3077. $this->assertEquals($expected, $result->clause('where'));
  3078. }
  3079. /**
  3080. * Test magic findAllByXX method.
  3081. *
  3082. * @return void
  3083. */
  3084. public function testMagicFindAllOr()
  3085. {
  3086. $table = TableRegistry::get('Users');
  3087. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  3088. $this->assertInstanceOf('Cake\ORM\Query', $result);
  3089. $this->assertNull($result->clause('limit'));
  3090. $expected = new QueryExpression();
  3091. $expected->typeMap()->defaults($this->usersTypeMap->toArray());
  3092. $expected->add(
  3093. ['or' => ['Users.author_id' => 1, 'Users.published' => 'Y']]
  3094. );
  3095. $this->assertEquals($expected, $result->clause('where'));
  3096. $this->assertNull($result->clause('order'));
  3097. }
  3098. /**
  3099. * Test the behavior method.
  3100. *
  3101. * @return void
  3102. */
  3103. public function testBehaviorIntrospection()
  3104. {
  3105. $table = TableRegistry::get('users');
  3106. $table->addBehavior('Timestamp');
  3107. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  3108. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  3109. }
  3110. /**
  3111. * Tests saving belongsTo association
  3112. *
  3113. * @group save
  3114. * @return void
  3115. */
  3116. public function testSaveBelongsTo()
  3117. {
  3118. $entity = new \Cake\ORM\Entity([
  3119. 'title' => 'A Title',
  3120. 'body' => 'A body'
  3121. ]);
  3122. $entity->author = new \Cake\ORM\Entity([
  3123. 'name' => 'Jose'
  3124. ]);
  3125. $table = TableRegistry::get('articles');
  3126. $table->belongsTo('authors');
  3127. $this->assertSame($entity, $table->save($entity));
  3128. $this->assertFalse($entity->isNew());
  3129. $this->assertFalse($entity->author->isNew());
  3130. $this->assertEquals(5, $entity->author->id);
  3131. $this->assertEquals(5, $entity->get('author_id'));
  3132. }
  3133. /**
  3134. * Tests saving hasOne association
  3135. *
  3136. * @group save
  3137. * @return void
  3138. */
  3139. public function testSaveHasOne()
  3140. {
  3141. $entity = new \Cake\ORM\Entity([
  3142. 'name' => 'Jose'
  3143. ]);
  3144. $entity->article = new \Cake\ORM\Entity([
  3145. 'title' => 'A Title',
  3146. 'body' => 'A body'
  3147. ]);
  3148. $table = TableRegistry::get('authors');
  3149. $table->hasOne('articles');
  3150. $this->assertSame($entity, $table->save($entity));
  3151. $this->assertFalse($entity->isNew());
  3152. $this->assertFalse($entity->article->isNew());
  3153. $this->assertEquals(4, $entity->article->id);
  3154. $this->assertEquals(5, $entity->article->get('author_id'));
  3155. $this->assertFalse($entity->article->dirty('author_id'));
  3156. }
  3157. /**
  3158. * Tests saving associations only saves associations
  3159. * if they are entities.
  3160. *
  3161. * @group save
  3162. * @return void
  3163. */
  3164. public function testSaveOnlySaveAssociatedEntities()
  3165. {
  3166. $entity = new \Cake\ORM\Entity([
  3167. 'name' => 'Jose'
  3168. ]);
  3169. // Not an entity.
  3170. $entity->article = [
  3171. 'title' => 'A Title',
  3172. 'body' => 'A body'
  3173. ];
  3174. $table = TableRegistry::get('authors');
  3175. $table->hasOne('articles');
  3176. $table->save($entity);
  3177. $this->assertFalse($entity->isNew());
  3178. $this->assertInternalType('array', $entity->article);
  3179. }
  3180. /**
  3181. * Tests saving multiple entities in a hasMany association
  3182. *
  3183. * @return void
  3184. */
  3185. public function testSaveHasMany()
  3186. {
  3187. $entity = new \Cake\ORM\Entity([
  3188. 'name' => 'Jose'
  3189. ]);
  3190. $entity->articles = [
  3191. new \Cake\ORM\Entity([
  3192. 'title' => 'A Title',
  3193. 'body' => 'A body'
  3194. ]),
  3195. new \Cake\ORM\Entity([
  3196. 'title' => 'Another Title',
  3197. 'body' => 'Another body'
  3198. ])
  3199. ];
  3200. $table = TableRegistry::get('authors');
  3201. $table->hasMany('articles');
  3202. $this->assertSame($entity, $table->save($entity));
  3203. $this->assertFalse($entity->isNew());
  3204. $this->assertFalse($entity->articles[0]->isNew());
  3205. $this->assertFalse($entity->articles[1]->isNew());
  3206. $this->assertEquals(4, $entity->articles[0]->id);
  3207. $this->assertEquals(5, $entity->articles[1]->id);
  3208. $this->assertEquals(5, $entity->articles[0]->author_id);
  3209. $this->assertEquals(5, $entity->articles[1]->author_id);
  3210. }
  3211. /**
  3212. * Tests saving belongsToMany records
  3213. *
  3214. * @group save
  3215. * @return void
  3216. */
  3217. public function testSaveBelongsToMany()
  3218. {
  3219. $entity = new \Cake\ORM\Entity([
  3220. 'title' => 'A Title',
  3221. 'body' => 'A body'
  3222. ]);
  3223. $entity->tags = [
  3224. new \Cake\ORM\Entity([
  3225. 'name' => 'Something New'
  3226. ]),
  3227. new \Cake\ORM\Entity([
  3228. 'name' => 'Another Something'
  3229. ])
  3230. ];
  3231. $table = TableRegistry::get('articles');
  3232. $table->belongsToMany('tags');
  3233. $this->assertSame($entity, $table->save($entity));
  3234. $this->assertFalse($entity->isNew());
  3235. $this->assertFalse($entity->tags[0]->isNew());
  3236. $this->assertFalse($entity->tags[1]->isNew());
  3237. $this->assertEquals(4, $entity->tags[0]->id);
  3238. $this->assertEquals(5, $entity->tags[1]->id);
  3239. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  3240. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  3241. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  3242. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  3243. }
  3244. /**
  3245. * Tests saving belongsToMany records when record exists.
  3246. *
  3247. * @group save
  3248. * @return void
  3249. */
  3250. public function testSaveBelongsToManyJoinDataOnExistingRecord()
  3251. {
  3252. $tags = TableRegistry::get('Tags');
  3253. $table = TableRegistry::get('Articles');
  3254. $table->belongsToMany('Tags');
  3255. $entity = $table->find()->contain('Tags')->first();
  3256. // not associated to the article already.
  3257. $entity->tags[] = $tags->get(3);
  3258. $entity->dirty('tags', true);
  3259. $this->assertSame($entity, $table->save($entity));
  3260. $this->assertFalse($entity->isNew());
  3261. $this->assertFalse($entity->tags[0]->isNew());
  3262. $this->assertFalse($entity->tags[1]->isNew());
  3263. $this->assertFalse($entity->tags[2]->isNew());
  3264. $this->assertNotEmpty($entity->tags[0]->_joinData);
  3265. $this->assertNotEmpty($entity->tags[1]->_joinData);
  3266. $this->assertNotEmpty($entity->tags[2]->_joinData);
  3267. }
  3268. /**
  3269. * Test that belongsToMany can be saved with _joinData data.
  3270. *
  3271. * @return void
  3272. */
  3273. public function testSaveBelongsToManyJoinData()
  3274. {
  3275. $articles = TableRegistry::get('Articles');
  3276. $article = $articles->get(1, ['contain' => ['tags']]);
  3277. $data = [
  3278. 'tags' => [
  3279. ['id' => 1, '_joinData' => ['highlighted' => 1]],
  3280. ['id' => 3]
  3281. ]
  3282. ];
  3283. $article = $articles->patchEntity($article, $data);
  3284. $result = $articles->save($article);
  3285. $this->assertSame($result, $article);
  3286. }
  3287. /**
  3288. * Test to check that association condition are used when fetching existing
  3289. * records to decide which records to unlink.
  3290. *
  3291. * @return void
  3292. */
  3293. public function testPolymorphicBelongsToManySave()
  3294. {
  3295. $articles = TableRegistry::get('Articles');
  3296. $articles->belongsToMany('Tags', [
  3297. 'through' => 'PolymorphicTagged',
  3298. 'foreignKey' => 'foreign_key',
  3299. 'conditions' => [
  3300. 'PolymorphicTagged.foreign_model' => 'Articles'
  3301. ],
  3302. 'sort' => ['PolymorphicTagged.position' => 'ASC']
  3303. ]);
  3304. $articles->Tags->junction()->belongsTo('Tags');
  3305. $entity = $articles->get(1, ['contain' => ['Tags']]);
  3306. $data = [
  3307. 'id' => 1,
  3308. 'tags' => [
  3309. [
  3310. 'id' => 1,
  3311. '_joinData' => [
  3312. 'id' => 2,
  3313. 'foreign_model' => 'Articles',
  3314. 'position' => 2
  3315. ]
  3316. ],
  3317. [
  3318. 'id' => 2,
  3319. '_joinData' => [
  3320. 'foreign_model' => 'Articles',
  3321. 'position' => 1
  3322. ]
  3323. ]
  3324. ]
  3325. ];
  3326. $entity = $articles->patchEntity($entity, $data, ['associated' => ['Tags._joinData']]);
  3327. $entity = $articles->save($entity);
  3328. $expected = [
  3329. [
  3330. 'id' => 1,
  3331. 'tag_id' => 1,
  3332. 'foreign_key' => 1,
  3333. 'foreign_model' => 'Posts',
  3334. 'position' => 1
  3335. ],
  3336. [
  3337. 'id' => 2,
  3338. 'tag_id' => 1,
  3339. 'foreign_key' => 1,
  3340. 'foreign_model' => 'Articles',
  3341. 'position' => 2
  3342. ],
  3343. [
  3344. 'id' => 3,
  3345. 'tag_id' => 2,
  3346. 'foreign_key' => 1,
  3347. 'foreign_model' => 'Articles',
  3348. 'position' => 1
  3349. ]
  3350. ];
  3351. $result = TableRegistry::get('PolymorphicTagged')
  3352. ->find('all', ['sort' => ['id' => 'DESC']])
  3353. ->hydrate(false)
  3354. ->toArray();
  3355. $this->assertEquals($expected, $result);
  3356. }
  3357. /**
  3358. * Tests saving belongsToMany records can delete all links.
  3359. *
  3360. * @group save
  3361. * @return void
  3362. */
  3363. public function testSaveBelongsToManyDeleteAllLinks()
  3364. {
  3365. $table = TableRegistry::get('articles');
  3366. $table->belongsToMany('tags', [
  3367. 'saveStrategy' => 'replace',
  3368. ]);
  3369. $entity = $table->get(1, ['contain' => 'tags']);
  3370. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3371. $entity->tags = [];
  3372. $result = $table->save($entity);
  3373. $this->assertSame($result, $entity);
  3374. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  3375. $entity = $table->get(1, ['contain' => 'tags']);
  3376. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  3377. }
  3378. /**
  3379. * Tests saving belongsToMany records can delete some links.
  3380. *
  3381. * @group save
  3382. * @return void
  3383. */
  3384. public function testSaveBelongsToManyDeleteSomeLinks()
  3385. {
  3386. $table = TableRegistry::get('articles');
  3387. $table->belongsToMany('tags', [
  3388. 'saveStrategy' => 'replace',
  3389. ]);
  3390. $entity = $table->get(1, ['contain' => 'tags']);
  3391. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3392. $tag = new \Cake\ORM\Entity([
  3393. 'id' => 2,
  3394. ]);
  3395. $entity->tags = [$tag];
  3396. $result = $table->save($entity);
  3397. $this->assertSame($result, $entity);
  3398. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  3399. $this->assertEquals($tag, $entity->tags[0]);
  3400. $entity = $table->get(1, ['contain' => 'tags']);
  3401. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  3402. $this->assertEquals($tag->id, $entity->tags[0]->id);
  3403. }
  3404. /**
  3405. * Test that belongsToMany ignores non-entity data.
  3406. *
  3407. * @return void
  3408. */
  3409. public function testSaveBelongsToManyIgnoreNonEntityData()
  3410. {
  3411. $articles = TableRegistry::get('articles');
  3412. $article = $articles->get(1, ['contain' => ['tags']]);
  3413. $article->tags = [
  3414. '_ids' => [2, 1]
  3415. ];
  3416. $result = $articles->save($article);
  3417. $this->assertSame($result, $article);
  3418. }
  3419. /**
  3420. * Test that a save call takes a SaveOptionBuilder object as well.
  3421. *
  3422. * @group save
  3423. * @return void
  3424. */
  3425. public function testSaveWithOptionBuilder()
  3426. {
  3427. $articles = new Table([
  3428. 'table' => 'articles',
  3429. 'connection' => $this->connection,
  3430. ]);
  3431. $articles->belongsTo('Authors');
  3432. $optionBuilder = new SaveOptionsBuilder($articles, [
  3433. 'associated' => [
  3434. 'Authors'
  3435. ]
  3436. ]);
  3437. $entity = $articles->newEntity([
  3438. 'title' => 'test save options',
  3439. 'author' => [
  3440. 'name' => 'author name'
  3441. ]
  3442. ]);
  3443. $articles->save($entity, $optionBuilder);
  3444. $this->assertFalse($entity->isNew());
  3445. $this->assertEquals('test save options', $entity->title);
  3446. $this->assertNotEmpty($entity->id);
  3447. $this->assertNotEmpty($entity->author->id);
  3448. $this->assertEquals('author name', $entity->author->name);
  3449. $entity = $articles->newEntity([
  3450. 'title' => 'test save options 2',
  3451. 'author' => [
  3452. 'name' => 'author name'
  3453. ]
  3454. ]);
  3455. $optionBuilder = new SaveOptionsBuilder($articles, [
  3456. 'associated' => []
  3457. ]);
  3458. $articles->save($entity, $optionBuilder);
  3459. $this->assertFalse($entity->isNew());
  3460. $this->assertEquals('test save options 2', $entity->title);
  3461. $this->assertNotEmpty($entity->id);
  3462. $this->assertEmpty($entity->author->id);
  3463. $this->assertTrue($entity->author->isNew());
  3464. }
  3465. /**
  3466. * Tests that saving a persisted and clean entity will is a no-op
  3467. *
  3468. * @group save
  3469. * @return void
  3470. */
  3471. public function testSaveCleanEntity()
  3472. {
  3473. $table = $this->getMockBuilder('\Cake\ORM\Table')
  3474. ->setMethods(['_processSave'])
  3475. ->getMock();
  3476. $entity = new \Cake\ORM\Entity(
  3477. ['id' => 'foo'],
  3478. ['markNew' => false, 'markClean' => true]
  3479. );
  3480. $table->expects($this->never())->method('_processSave');
  3481. $this->assertSame($entity, $table->save($entity));
  3482. }
  3483. /**
  3484. * Integration test to show how to append a new tag to an article
  3485. *
  3486. * @group save
  3487. * @return void
  3488. */
  3489. public function testBelongsToManyIntegration()
  3490. {
  3491. $table = TableRegistry::get('articles');
  3492. $table->belongsToMany('tags');
  3493. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3494. $tags = $article->tags;
  3495. $this->assertNotEmpty($tags);
  3496. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  3497. $article->tags = $tags;
  3498. $this->assertSame($article, $table->save($article));
  3499. $tags = $article->tags;
  3500. $this->assertCount(3, $tags);
  3501. $this->assertFalse($tags[2]->isNew());
  3502. $this->assertEquals(4, $tags[2]->id);
  3503. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  3504. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  3505. }
  3506. /**
  3507. * Tests that it is possible to do a deep save and control what associations get saved,
  3508. * while having control of the options passed to each level of the save
  3509. *
  3510. * @group save
  3511. * @return void
  3512. */
  3513. public function testSaveDeepAssociationOptions()
  3514. {
  3515. $articles = $this->getMockBuilder('\Cake\ORM\Table')
  3516. ->setMethods(['_insert'])
  3517. ->setConstructorArgs([['table' => 'articles', 'connection' => $this->connection]])
  3518. ->getMock();
  3519. $authors = $this->getMockBuilder('\Cake\ORM\Table')
  3520. ->setMethods(['_insert'])
  3521. ->setConstructorArgs([['table' => 'authors', 'connection' => $this->connection]])
  3522. ->getMock();
  3523. $supervisors = $this->getMockBuilder('\Cake\ORM\Table')
  3524. ->setMethods(['_insert', 'validate'])
  3525. ->setConstructorArgs([[
  3526. 'table' => 'authors',
  3527. 'alias' => 'supervisors',
  3528. 'connection' => $this->connection
  3529. ]])
  3530. ->getMock();
  3531. $tags = $this->getMockBuilder('\Cake\ORM\Table')
  3532. ->setMethods(['_insert'])
  3533. ->setConstructorArgs([['table' => 'tags', 'connection' => $this->connection]])
  3534. ->getMock();
  3535. $articles->belongsTo('authors', ['targetTable' => $authors]);
  3536. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  3537. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  3538. $entity = new \Cake\ORM\Entity([
  3539. 'title' => 'bar',
  3540. 'author' => new \Cake\ORM\Entity([
  3541. 'name' => 'Juan',
  3542. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  3543. 'tags' => [
  3544. new \Cake\ORM\Entity(['name' => 'foo'])
  3545. ]
  3546. ]),
  3547. ]);
  3548. $entity->isNew(true);
  3549. $entity->author->isNew(true);
  3550. $entity->author->supervisor->isNew(true);
  3551. $entity->author->tags[0]->isNew(true);
  3552. $articles->expects($this->once())
  3553. ->method('_insert')
  3554. ->with($entity, ['title' => 'bar'])
  3555. ->will($this->returnValue($entity));
  3556. $authors->expects($this->once())
  3557. ->method('_insert')
  3558. ->with($entity->author, ['name' => 'Juan'])
  3559. ->will($this->returnValue($entity->author));
  3560. $supervisors->expects($this->once())
  3561. ->method('_insert')
  3562. ->with($entity->author->supervisor, ['name' => 'Marc'])
  3563. ->will($this->returnValue($entity->author->supervisor));
  3564. $tags->expects($this->never())->method('_insert');
  3565. $this->assertSame($entity, $articles->save($entity, [
  3566. 'associated' => [
  3567. 'authors' => [],
  3568. 'authors.supervisors' => [
  3569. 'atomic' => false,
  3570. 'associated' => false
  3571. ]
  3572. ]
  3573. ]));
  3574. }
  3575. /**
  3576. * Integration test for linking entities with belongsToMany
  3577. *
  3578. * @return void
  3579. */
  3580. public function testLinkBelongsToMany()
  3581. {
  3582. $table = TableRegistry::get('articles');
  3583. $table->belongsToMany('tags');
  3584. $tagsTable = TableRegistry::get('tags');
  3585. $source = ['source' => 'tags'];
  3586. $options = ['markNew' => false];
  3587. $article = new \Cake\ORM\Entity([
  3588. 'id' => 1,
  3589. ], $options);
  3590. $newTag = new \TestApp\Model\Entity\Tag([
  3591. 'name' => 'Foo',
  3592. 'description' => 'Foo desc'
  3593. ], $source);
  3594. $tags[] = new \TestApp\Model\Entity\Tag([
  3595. 'id' => 3
  3596. ], $options + $source);
  3597. $tags[] = $newTag;
  3598. $tagsTable->save($newTag);
  3599. $table->association('tags')->link($article, $tags);
  3600. $this->assertEquals($article->tags, $tags);
  3601. foreach ($tags as $tag) {
  3602. $this->assertFalse($tag->isNew());
  3603. }
  3604. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3605. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  3606. $this->assertEquals($article->tags[3], $tags[1]);
  3607. }
  3608. /**
  3609. * Integration test for linking entities with HasMany
  3610. *
  3611. * @return void
  3612. */
  3613. public function testLinkHasMany()
  3614. {
  3615. $authors = TableRegistry::get('Authors');
  3616. $articles = TableRegistry::get('Articles');
  3617. $authors->hasMany('Articles', [
  3618. 'foreignKey' => 'author_id'
  3619. ]);
  3620. $author = $authors->newEntity(['name' => 'mylux']);
  3621. $author = $authors->save($author);
  3622. $newArticles = $articles->newEntities(
  3623. [
  3624. [
  3625. 'title' => 'New bakery next corner',
  3626. 'body' => 'They sell tastefull cakes'
  3627. ],
  3628. [
  3629. 'title' => 'Spicy cake recipe',
  3630. 'body' => 'chocolate and peppers'
  3631. ]
  3632. ]
  3633. );
  3634. $sizeArticles = count($newArticles);
  3635. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3636. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3637. $this->assertCount($sizeArticles, $author->articles);
  3638. $this->assertFalse($author->dirty('articles'));
  3639. }
  3640. /**
  3641. * Integration test for linking entities with HasMany combined with ReplaceSaveStrategy. It must append, not unlinking anything
  3642. *
  3643. * @return void
  3644. */
  3645. public function testLinkHasManyReplaceSaveStrategy()
  3646. {
  3647. $authors = TableRegistry::get('Authors');
  3648. $articles = TableRegistry::get('Articles');
  3649. $authors->hasMany('Articles', [
  3650. 'foreignKey' => 'author_id',
  3651. 'saveStrategy' => 'replace'
  3652. ]);
  3653. $author = $authors->newEntity(['name' => 'mylux']);
  3654. $author = $authors->save($author);
  3655. $newArticles = $articles->newEntities(
  3656. [
  3657. [
  3658. 'title' => 'New bakery next corner',
  3659. 'body' => 'They sell tastefull cakes'
  3660. ],
  3661. [
  3662. 'title' => 'Spicy cake recipe',
  3663. 'body' => 'chocolate and peppers'
  3664. ]
  3665. ]
  3666. );
  3667. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3668. $sizeArticles = count($newArticles);
  3669. $newArticles = $articles->newEntities(
  3670. [
  3671. [
  3672. 'title' => 'Nothing but the cake',
  3673. 'body' => 'It is all that we need'
  3674. ]
  3675. ]
  3676. );
  3677. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3678. $sizeArticles++;
  3679. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3680. $this->assertCount($sizeArticles, $author->articles);
  3681. $this->assertFalse($author->dirty('articles'));
  3682. }
  3683. /**
  3684. * Integration test for linking entities with HasMany. The input contains already linked entities and they should not appeat duplicated
  3685. *
  3686. * @return void
  3687. */
  3688. public function testLinkHasManyExisting()
  3689. {
  3690. $authors = TableRegistry::get('Authors');
  3691. $articles = TableRegistry::get('Articles');
  3692. $authors->hasMany('Articles', [
  3693. 'foreignKey' => 'author_id',
  3694. 'saveStrategy' => 'replace'
  3695. ]);
  3696. $author = $authors->newEntity(['name' => 'mylux']);
  3697. $author = $authors->save($author);
  3698. $newArticles = $articles->newEntities(
  3699. [
  3700. [
  3701. 'title' => 'New bakery next corner',
  3702. 'body' => 'They sell tastefull cakes'
  3703. ],
  3704. [
  3705. 'title' => 'Spicy cake recipe',
  3706. 'body' => 'chocolate and peppers'
  3707. ]
  3708. ]
  3709. );
  3710. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3711. $sizeArticles = count($newArticles);
  3712. $newArticles = array_merge(
  3713. $author->articles,
  3714. $articles->newEntities(
  3715. [
  3716. [
  3717. 'title' => 'Nothing but the cake',
  3718. 'body' => 'It is all that we need'
  3719. ]
  3720. ]
  3721. )
  3722. );
  3723. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3724. $sizeArticles++;
  3725. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3726. $this->assertCount($sizeArticles, $author->articles);
  3727. $this->assertFalse($author->dirty('articles'));
  3728. }
  3729. /**
  3730. * Integration test for unlinking entities with HasMany. The association property must be cleaned
  3731. *
  3732. * @return void
  3733. */
  3734. public function testUnlinkHasManyCleanProperty()
  3735. {
  3736. $authors = TableRegistry::get('Authors');
  3737. $articles = TableRegistry::get('Articles');
  3738. $authors->hasMany('Articles', [
  3739. 'foreignKey' => 'author_id',
  3740. 'saveStrategy' => 'replace'
  3741. ]);
  3742. $author = $authors->newEntity(['name' => 'mylux']);
  3743. $author = $authors->save($author);
  3744. $newArticles = $articles->newEntities(
  3745. [
  3746. [
  3747. 'title' => 'New bakery next corner',
  3748. 'body' => 'They sell tastefull cakes'
  3749. ],
  3750. [
  3751. 'title' => 'Spicy cake recipe',
  3752. 'body' => 'chocolate and peppers'
  3753. ],
  3754. [
  3755. 'title' => 'Creamy cake recipe',
  3756. 'body' => 'chocolate and cream'
  3757. ],
  3758. ]
  3759. );
  3760. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3761. $sizeArticles = count($newArticles);
  3762. $articlesToUnlink = [ $author->articles[0], $author->articles[1] ];
  3763. $authors->Articles->unlink($author, $articlesToUnlink);
  3764. $this->assertCount($sizeArticles - count($articlesToUnlink), $authors->Articles->findAllByAuthorId($author->id));
  3765. $this->assertCount($sizeArticles - count($articlesToUnlink), $author->articles);
  3766. $this->assertFalse($author->dirty('articles'));
  3767. }
  3768. /**
  3769. * Integration test for unlinking entities with HasMany. The association property must stay unchanged
  3770. *
  3771. * @return void
  3772. */
  3773. public function testUnlinkHasManyNotCleanProperty()
  3774. {
  3775. $authors = TableRegistry::get('Authors');
  3776. $articles = TableRegistry::get('Articles');
  3777. $authors->hasMany('Articles', [
  3778. 'foreignKey' => 'author_id',
  3779. 'saveStrategy' => 'replace'
  3780. ]);
  3781. $author = $authors->newEntity(['name' => 'mylux']);
  3782. $author = $authors->save($author);
  3783. $newArticles = $articles->newEntities(
  3784. [
  3785. [
  3786. 'title' => 'New bakery next corner',
  3787. 'body' => 'They sell tastefull cakes'
  3788. ],
  3789. [
  3790. 'title' => 'Spicy cake recipe',
  3791. 'body' => 'chocolate and peppers'
  3792. ],
  3793. [
  3794. 'title' => 'Creamy cake recipe',
  3795. 'body' => 'chocolate and cream'
  3796. ],
  3797. ]
  3798. );
  3799. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3800. $sizeArticles = count($newArticles);
  3801. $articlesToUnlink = [ $author->articles[0], $author->articles[1] ];
  3802. $authors->Articles->unlink($author, $articlesToUnlink, ['cleanProperty' => false]);
  3803. $this->assertCount($sizeArticles - count($articlesToUnlink), $authors->Articles->findAllByAuthorId($author->id));
  3804. $this->assertCount($sizeArticles, $author->articles);
  3805. $this->assertFalse($author->dirty('articles'));
  3806. }
  3807. /**
  3808. * Integration test for unlinking entities with HasMany.
  3809. * Checking that no error happens when the hasMany property is originally
  3810. * null
  3811. *
  3812. * @return void
  3813. */
  3814. public function testUnlinkHasManyEmpty()
  3815. {
  3816. $authors = TableRegistry::get('Authors');
  3817. $articles = TableRegistry::get('Articles');
  3818. $authors->hasMany('Articles');
  3819. $author = $authors->get(1);
  3820. $article = $authors->Articles->get(1);
  3821. $authors->Articles->unlink($author, [$article]);
  3822. }
  3823. /**
  3824. * Integration test for replacing entities which depend on their source entity with HasMany and failing transaction. False should be returned when
  3825. * unlinking fails while replacing even when cascadeCallbacks is enabled
  3826. *
  3827. * @return void
  3828. */
  3829. public function testReplaceHasManyOnErrorDependentCascadeCallbacks()
  3830. {
  3831. $articles = $this->getMockBuilder('Cake\ORM\Table')
  3832. ->setMethods(['delete'])
  3833. ->setConstructorArgs([[
  3834. 'connection' => $this->connection,
  3835. 'alias' => 'Articles',
  3836. 'table' => 'articles',
  3837. ]])
  3838. ->getMock();
  3839. $articles->method('delete')->willReturn(false);
  3840. $associations = new AssociationCollection();
  3841. $hasManyArticles = $this->getMockBuilder('Cake\ORM\Association\HasMany')
  3842. ->setMethods(['target'])
  3843. ->setConstructorArgs([
  3844. 'articles',
  3845. [
  3846. 'target' => $articles,
  3847. 'foreignKey' => 'author_id',
  3848. 'dependent' => true,
  3849. 'cascadeCallbacks' => true
  3850. ]
  3851. ])
  3852. ->getMock();
  3853. $hasManyArticles->method('target')->willReturn($articles);
  3854. $associations->add('articles', $hasManyArticles);
  3855. $authors = new Table([
  3856. 'connection' => $this->connection,
  3857. 'alias' => 'Authors',
  3858. 'table' => 'authors',
  3859. 'associations' => $associations
  3860. ]);
  3861. $authors->Articles->source($authors);
  3862. $author = $authors->newEntity(['name' => 'mylux']);
  3863. $author = $authors->save($author);
  3864. $newArticles = $articles->newEntities(
  3865. [
  3866. [
  3867. 'title' => 'New bakery next corner',
  3868. 'body' => 'They sell tastefull cakes'
  3869. ],
  3870. [
  3871. 'title' => 'Spicy cake recipe',
  3872. 'body' => 'chocolate and peppers'
  3873. ]
  3874. ]
  3875. );
  3876. $sizeArticles = count($newArticles);
  3877. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3878. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3879. $this->assertEquals(count($author->articles), $sizeArticles);
  3880. $newArticles = array_merge(
  3881. $author->articles,
  3882. $articles->newEntities(
  3883. [
  3884. [
  3885. 'title' => 'Cheese cake recipe',
  3886. 'body' => 'The secrets of mixing salt and sugar'
  3887. ],
  3888. [
  3889. 'title' => 'Not another piece of cake',
  3890. 'body' => 'This is the best'
  3891. ]
  3892. ]
  3893. )
  3894. );
  3895. unset($newArticles[0]);
  3896. $this->assertFalse($authors->Articles->replace($author, $newArticles));
  3897. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3898. }
  3899. /**
  3900. * Integration test for replacing entities with HasMany and an empty target list. The transaction must be successfull
  3901. *
  3902. * @return void
  3903. */
  3904. public function testReplaceHasManyEmptyList()
  3905. {
  3906. $authors = new Table([
  3907. 'connection' => $this->connection,
  3908. 'alias' => 'Authors',
  3909. 'table' => 'authors',
  3910. ]);
  3911. $authors->hasMany('Articles');
  3912. $author = $authors->newEntity(['name' => 'mylux']);
  3913. $author = $authors->save($author);
  3914. $newArticles = $authors->Articles->newEntities(
  3915. [
  3916. [
  3917. 'title' => 'New bakery next corner',
  3918. 'body' => 'They sell tastefull cakes'
  3919. ],
  3920. [
  3921. 'title' => 'Spicy cake recipe',
  3922. 'body' => 'chocolate and peppers'
  3923. ]
  3924. ]
  3925. );
  3926. $sizeArticles = count($newArticles);
  3927. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3928. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3929. $this->assertEquals(count($author->articles), $sizeArticles);
  3930. $newArticles = [];
  3931. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  3932. $this->assertCount(0, $authors->Articles->findAllByAuthorId($author->id));
  3933. }
  3934. /**
  3935. * Integration test for replacing entities with HasMany and no already persisted entities. The transaction must be successfull.
  3936. * Replace operation should prevent considering 0 changed records an error when they are not found in the table
  3937. *
  3938. * @return void
  3939. */
  3940. public function testReplaceHasManyNoPersistedEntities()
  3941. {
  3942. $authors = new Table([
  3943. 'connection' => $this->connection,
  3944. 'alias' => 'Authors',
  3945. 'table' => 'authors',
  3946. ]);
  3947. $authors->hasMany('Articles');
  3948. $author = $authors->newEntity(['name' => 'mylux']);
  3949. $author = $authors->save($author);
  3950. $newArticles = $authors->Articles->newEntities(
  3951. [
  3952. [
  3953. 'title' => 'New bakery next corner',
  3954. 'body' => 'They sell tastefull cakes'
  3955. ],
  3956. [
  3957. 'title' => 'Spicy cake recipe',
  3958. 'body' => 'chocolate and peppers'
  3959. ]
  3960. ]
  3961. );
  3962. $authors->Articles->deleteAll(['1=1']);
  3963. $sizeArticles = count($newArticles);
  3964. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3965. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3966. $this->assertEquals(count($author->articles), $sizeArticles);
  3967. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  3968. $this->assertCount($sizeArticles, $authors->Articles->findAllByAuthorId($author->id));
  3969. }
  3970. /**
  3971. * Integration test for replacing entities with HasMany.
  3972. *
  3973. * @return void
  3974. */
  3975. public function testReplaceHasMany()
  3976. {
  3977. $authors = TableRegistry::get('Authors');
  3978. $articles = TableRegistry::get('Articles');
  3979. $authors->hasMany('Articles', [
  3980. 'foreignKey' => 'author_id'
  3981. ]);
  3982. $author = $authors->newEntity(['name' => 'mylux']);
  3983. $author = $authors->save($author);
  3984. $newArticles = $articles->newEntities(
  3985. [
  3986. [
  3987. 'title' => 'New bakery next corner',
  3988. 'body' => 'They sell tastefull cakes'
  3989. ],
  3990. [
  3991. 'title' => 'Spicy cake recipe',
  3992. 'body' => 'chocolate and peppers'
  3993. ]
  3994. ]
  3995. );
  3996. $sizeArticles = count($newArticles);
  3997. $this->assertTrue($authors->Articles->link($author, $newArticles));
  3998. $this->assertEquals($authors->Articles->findAllByAuthorId($author->id)->count(), $sizeArticles);
  3999. $this->assertEquals(count($author->articles), $sizeArticles);
  4000. $newArticles = array_merge(
  4001. $author->articles,
  4002. $articles->newEntities(
  4003. [
  4004. [
  4005. 'title' => 'Cheese cake recipe',
  4006. 'body' => 'The secrets of mixing salt and sugar'
  4007. ],
  4008. [
  4009. 'title' => 'Not another piece of cake',
  4010. 'body' => 'This is the best'
  4011. ]
  4012. ]
  4013. )
  4014. );
  4015. unset($newArticles[0]);
  4016. $this->assertTrue($authors->Articles->replace($author, $newArticles));
  4017. $this->assertEquals(count($newArticles), count($author->articles));
  4018. $this->assertEquals((new Collection($newArticles))->extract('title'), (new Collection($author->articles))->extract('title'));
  4019. }
  4020. /**
  4021. * Integration test to show how to unlink a single record from a belongsToMany
  4022. *
  4023. * @return void
  4024. */
  4025. public function testUnlinkBelongsToMany()
  4026. {
  4027. $table = TableRegistry::get('articles');
  4028. $table->belongsToMany('tags');
  4029. $tagsTable = TableRegistry::get('tags');
  4030. $options = ['markNew' => false];
  4031. $article = $table->find('all')
  4032. ->where(['id' => 1])
  4033. ->contain(['tags'])->first();
  4034. $table->association('tags')->unlink($article, [$article->tags[0]]);
  4035. $this->assertCount(1, $article->tags);
  4036. $this->assertEquals(2, $article->tags[0]->get('id'));
  4037. $this->assertFalse($article->dirty('tags'));
  4038. }
  4039. /**
  4040. * Integration test to show how to unlink multiple records from a belongsToMany
  4041. *
  4042. * @return void
  4043. */
  4044. public function testUnlinkBelongsToManyMultiple()
  4045. {
  4046. $table = TableRegistry::get('articles');
  4047. $table->belongsToMany('tags');
  4048. $tagsTable = TableRegistry::get('tags');
  4049. $options = ['markNew' => false];
  4050. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  4051. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  4052. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  4053. $table->association('tags')->unlink($article, $tags);
  4054. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4055. $this->assertEmpty($left->tags);
  4056. }
  4057. /**
  4058. * Integration test to show how to unlink multiple records from a belongsToMany
  4059. * providing some of the joint
  4060. *
  4061. * @return void
  4062. */
  4063. public function testUnlinkBelongsToManyPassingJoint()
  4064. {
  4065. $table = TableRegistry::get('articles');
  4066. $table->belongsToMany('tags');
  4067. $tagsTable = TableRegistry::get('tags');
  4068. $options = ['markNew' => false];
  4069. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  4070. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  4071. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  4072. $tags[1]->_joinData = new \Cake\ORM\Entity([
  4073. 'article_id' => 1,
  4074. 'tag_id' => 2
  4075. ], $options);
  4076. $table->association('tags')->unlink($article, $tags);
  4077. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4078. $this->assertEmpty($left->tags);
  4079. }
  4080. /**
  4081. * Integration test to show how to replace records from a belongsToMany
  4082. *
  4083. * @return void
  4084. */
  4085. public function testReplacelinksBelongsToMany()
  4086. {
  4087. $table = TableRegistry::get('articles');
  4088. $table->belongsToMany('tags');
  4089. $tagsTable = TableRegistry::get('tags');
  4090. $options = ['markNew' => false];
  4091. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  4092. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  4093. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  4094. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  4095. $table->association('tags')->replaceLinks($article, $tags);
  4096. $this->assertEquals(2, $article->tags[0]->id);
  4097. $this->assertEquals(3, $article->tags[1]->id);
  4098. $this->assertEquals(4, $article->tags[2]->id);
  4099. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4100. $this->assertCount(3, $article->tags);
  4101. $this->assertEquals(2, $article->tags[0]->id);
  4102. $this->assertEquals(3, $article->tags[1]->id);
  4103. $this->assertEquals(4, $article->tags[2]->id);
  4104. $this->assertEquals('foo', $article->tags[2]->name);
  4105. }
  4106. /**
  4107. * Integration test to show how remove all links from a belongsToMany
  4108. *
  4109. * @return void
  4110. */
  4111. public function testReplacelinksBelongsToManyWithEmpty()
  4112. {
  4113. $table = TableRegistry::get('articles');
  4114. $table->belongsToMany('tags');
  4115. $tagsTable = TableRegistry::get('tags');
  4116. $options = ['markNew' => false];
  4117. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  4118. $tags = [];
  4119. $table->association('tags')->replaceLinks($article, $tags);
  4120. $this->assertSame($tags, $article->tags);
  4121. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4122. $this->assertEmpty($article->tags);
  4123. }
  4124. /**
  4125. * Integration test to show how to replace records from a belongsToMany
  4126. * passing the joint property along in the target entity
  4127. *
  4128. * @return void
  4129. */
  4130. public function testReplacelinksBelongsToManyWithJoint()
  4131. {
  4132. $table = TableRegistry::get('articles');
  4133. $table->belongsToMany('tags');
  4134. $tagsTable = TableRegistry::get('tags');
  4135. $options = ['markNew' => false];
  4136. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  4137. $tags[] = new \TestApp\Model\Entity\Tag([
  4138. 'id' => 2,
  4139. '_joinData' => new \Cake\ORM\Entity([
  4140. 'article_id' => 1,
  4141. 'tag_id' => 2,
  4142. ])
  4143. ], $options);
  4144. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  4145. $table->association('tags')->replaceLinks($article, $tags);
  4146. $this->assertSame($tags, $article->tags);
  4147. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  4148. $this->assertCount(2, $article->tags);
  4149. $this->assertEquals(2, $article->tags[0]->id);
  4150. $this->assertEquals(3, $article->tags[1]->id);
  4151. }
  4152. /**
  4153. * Tests that options are being passed through to the internal table method calls.
  4154. *
  4155. * @return void
  4156. */
  4157. public function testOptionsBeingPassedToImplicitBelongsToManyDeletesUsingSaveReplace()
  4158. {
  4159. $articles = TableRegistry::get('Articles');
  4160. $tags = $articles->belongsToMany('Tags');
  4161. $tags->saveStrategy(BelongsToMany::SAVE_REPLACE);
  4162. $tags->dependent(true);
  4163. $tags->cascadeCallbacks(true);
  4164. $actualOptions = null;
  4165. $tags->junction()->eventManager()->on(
  4166. 'Model.beforeDelete',
  4167. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4168. $actualOptions = $options->getArrayCopy();
  4169. }
  4170. );
  4171. $article = $articles->get(1);
  4172. $article->tags = [];
  4173. $article->dirty('tags', true);
  4174. $result = $articles->save($article, ['foo' => 'bar']);
  4175. $this->assertNotEmpty($result);
  4176. $expected = [
  4177. '_primary' => false,
  4178. 'foo' => 'bar',
  4179. 'atomic' => true,
  4180. 'checkRules' => true,
  4181. 'checkExisting' => true
  4182. ];
  4183. $this->assertEquals($expected, $actualOptions);
  4184. }
  4185. /**
  4186. * Tests that options are being passed through to the internal table method calls.
  4187. *
  4188. * @return void
  4189. */
  4190. public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyLink()
  4191. {
  4192. $articles = TableRegistry::get('Articles');
  4193. $tags = $articles->belongsToMany('Tags');
  4194. $actualOptions = null;
  4195. $tags->junction()->eventManager()->on(
  4196. 'Model.beforeSave',
  4197. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4198. $actualOptions = $options->getArrayCopy();
  4199. }
  4200. );
  4201. $article = $articles->get(1);
  4202. $result = $tags->link($article, [$tags->target()->get(2)], ['foo' => 'bar']);
  4203. $this->assertTrue($result);
  4204. $expected = [
  4205. '_primary' => true,
  4206. 'foo' => 'bar',
  4207. 'atomic' => true,
  4208. 'checkRules' => true,
  4209. 'checkExisting' => true,
  4210. 'associated' => [
  4211. 'articles' => [],
  4212. 'tags' => []
  4213. ]
  4214. ];
  4215. $this->assertEquals($expected, $actualOptions);
  4216. }
  4217. /**
  4218. * Tests that options are being passed through to the internal table method calls.
  4219. *
  4220. * @return void
  4221. */
  4222. public function testOptionsBeingPassedToInternalSaveCallsUsingBelongsToManyUnlink()
  4223. {
  4224. $articles = TableRegistry::get('Articles');
  4225. $tags = $articles->belongsToMany('Tags');
  4226. $actualOptions = null;
  4227. $tags->junction()->eventManager()->on(
  4228. 'Model.beforeDelete',
  4229. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4230. $actualOptions = $options->getArrayCopy();
  4231. }
  4232. );
  4233. $article = $articles->get(1);
  4234. $tags->unlink($article, [$tags->target()->get(2)], ['foo' => 'bar']);
  4235. $expected = [
  4236. '_primary' => true,
  4237. 'foo' => 'bar',
  4238. 'atomic' => true,
  4239. 'checkRules' => true,
  4240. 'cleanProperty' => true
  4241. ];
  4242. $this->assertEquals($expected, $actualOptions);
  4243. }
  4244. /**
  4245. * Tests that options are being passed through to the internal table method calls.
  4246. *
  4247. * @return void
  4248. */
  4249. public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingBelongsToManyReplaceLinks()
  4250. {
  4251. $articles = TableRegistry::get('Articles');
  4252. $tags = $articles->belongsToMany('Tags');
  4253. $actualSaveOptions = null;
  4254. $actualDeleteOptions = null;
  4255. $tags->junction()->eventManager()->on(
  4256. 'Model.beforeSave',
  4257. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) {
  4258. $actualSaveOptions = $options->getArrayCopy();
  4259. }
  4260. );
  4261. $tags->junction()->eventManager()->on(
  4262. 'Model.beforeDelete',
  4263. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) {
  4264. $actualDeleteOptions = $options->getArrayCopy();
  4265. }
  4266. );
  4267. $article = $articles->get(1);
  4268. $result = $tags->replaceLinks(
  4269. $article,
  4270. [
  4271. $tags->target()->newEntity(['name' => 'new']),
  4272. $tags->target()->get(2)
  4273. ],
  4274. ['foo' => 'bar']
  4275. );
  4276. $this->assertTrue($result);
  4277. $expected = [
  4278. '_primary' => true,
  4279. 'foo' => 'bar',
  4280. 'atomic' => true,
  4281. 'checkRules' => true,
  4282. 'checkExisting' => true,
  4283. 'associated' => []
  4284. ];
  4285. $this->assertEquals($expected, $actualSaveOptions);
  4286. $expected = [
  4287. '_primary' => true,
  4288. 'foo' => 'bar',
  4289. 'atomic' => true,
  4290. 'checkRules' => true
  4291. ];
  4292. $this->assertEquals($expected, $actualDeleteOptions);
  4293. }
  4294. /**
  4295. * Tests that options are being passed through to the internal table method calls.
  4296. *
  4297. * @return void
  4298. */
  4299. public function testOptionsBeingPassedToImplicitHasManyDeletesUsingSaveReplace()
  4300. {
  4301. $authors = TableRegistry::get('Authors');
  4302. $articles = $authors->hasMany('Articles');
  4303. $articles->saveStrategy(HasMany::SAVE_REPLACE);
  4304. $articles->dependent(true);
  4305. $articles->cascadeCallbacks(true);
  4306. $actualOptions = null;
  4307. $articles->target()->eventManager()->on(
  4308. 'Model.beforeDelete',
  4309. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4310. $actualOptions = $options->getArrayCopy();
  4311. }
  4312. );
  4313. $author = $authors->get(1);
  4314. $author->articles = [];
  4315. $author->dirty('articles', true);
  4316. $result = $authors->save($author, ['foo' => 'bar']);
  4317. $this->assertNotEmpty($result);
  4318. $expected = [
  4319. '_primary' => false,
  4320. 'foo' => 'bar',
  4321. 'atomic' => true,
  4322. 'checkRules' => true,
  4323. 'checkExisting' => true,
  4324. '_sourceTable' => $authors
  4325. ];
  4326. $this->assertEquals($expected, $actualOptions);
  4327. }
  4328. /**
  4329. * Tests that options are being passed through to the internal table method calls.
  4330. *
  4331. * @return void
  4332. */
  4333. public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyLink()
  4334. {
  4335. $authors = TableRegistry::get('Authors');
  4336. $articles = $authors->hasMany('Articles');
  4337. $actualOptions = null;
  4338. $articles->target()->eventManager()->on(
  4339. 'Model.beforeSave',
  4340. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4341. $actualOptions = $options->getArrayCopy();
  4342. }
  4343. );
  4344. $author = $authors->get(1);
  4345. $author->articles = [];
  4346. $author->dirty('articles', true);
  4347. $result = $articles->link($author, [$articles->target()->get(2)], ['foo' => 'bar']);
  4348. $this->assertTrue($result);
  4349. $expected = [
  4350. '_primary' => true,
  4351. 'foo' => 'bar',
  4352. 'atomic' => true,
  4353. 'checkRules' => true,
  4354. 'checkExisting' => true,
  4355. '_sourceTable' => $authors,
  4356. 'associated' => [
  4357. 'authors' => [],
  4358. 'tags' => [],
  4359. 'articlestags' => []
  4360. ]
  4361. ];
  4362. $this->assertEquals($expected, $actualOptions);
  4363. }
  4364. /**
  4365. * Tests that options are being passed through to the internal table method calls.
  4366. *
  4367. * @return void
  4368. */
  4369. public function testOptionsBeingPassedToInternalSaveCallsUsingHasManyUnlink()
  4370. {
  4371. $authors = TableRegistry::get('Authors');
  4372. $articles = $authors->hasMany('Articles');
  4373. $articles->dependent(true);
  4374. $articles->cascadeCallbacks(true);
  4375. $actualOptions = null;
  4376. $articles->target()->eventManager()->on(
  4377. 'Model.beforeDelete',
  4378. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4379. $actualOptions = $options->getArrayCopy();
  4380. }
  4381. );
  4382. $author = $authors->get(1);
  4383. $author->articles = [];
  4384. $author->dirty('articles', true);
  4385. $articles->unlink($author, [$articles->target()->get(1)], ['foo' => 'bar']);
  4386. $expected = [
  4387. '_primary' => true,
  4388. 'foo' => 'bar',
  4389. 'atomic' => true,
  4390. 'checkRules' => true,
  4391. 'cleanProperty' => true
  4392. ];
  4393. $this->assertEquals($expected, $actualOptions);
  4394. }
  4395. /**
  4396. * Tests that options are being passed through to the internal table method calls.
  4397. *
  4398. * @return void
  4399. */
  4400. public function testOptionsBeingPassedToInternalSaveAndDeleteCallsUsingHasManyReplace()
  4401. {
  4402. $authors = TableRegistry::get('Authors');
  4403. $articles = $authors->hasMany('Articles');
  4404. $articles->dependent(true);
  4405. $articles->cascadeCallbacks(true);
  4406. $actualSaveOptions = null;
  4407. $actualDeleteOptions = null;
  4408. $articles->target()->eventManager()->on(
  4409. 'Model.beforeSave',
  4410. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualSaveOptions) {
  4411. $actualSaveOptions = $options->getArrayCopy();
  4412. }
  4413. );
  4414. $articles->target()->eventManager()->on(
  4415. 'Model.beforeDelete',
  4416. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualDeleteOptions) {
  4417. $actualDeleteOptions = $options->getArrayCopy();
  4418. }
  4419. );
  4420. $author = $authors->get(1);
  4421. $result = $articles->replace(
  4422. $author,
  4423. [
  4424. $articles->target()->newEntity(['title' => 'new', 'body' => 'new']),
  4425. $articles->target()->get(1)
  4426. ],
  4427. ['foo' => 'bar']
  4428. );
  4429. $this->assertTrue($result);
  4430. $expected = [
  4431. '_primary' => true,
  4432. 'foo' => 'bar',
  4433. 'atomic' => true,
  4434. 'checkRules' => true,
  4435. 'checkExisting' => true,
  4436. '_sourceTable' => $authors,
  4437. 'associated' => [
  4438. 'authors' => [],
  4439. 'tags' => [],
  4440. 'articlestags' => []
  4441. ]
  4442. ];
  4443. $this->assertEquals($expected, $actualSaveOptions);
  4444. $expected = [
  4445. '_primary' => true,
  4446. 'foo' => 'bar',
  4447. 'atomic' => true,
  4448. 'checkRules' => true,
  4449. '_sourceTable' => $authors
  4450. ];
  4451. $this->assertEquals($expected, $actualDeleteOptions);
  4452. }
  4453. /**
  4454. * Tests backwards compatibility of the the `$options` argument, formerly `$cleanProperty`.
  4455. *
  4456. * @return void
  4457. */
  4458. public function testBackwardsCompatibilityForBelongsToManyUnlinkCleanPropertyOption()
  4459. {
  4460. $articles = TableRegistry::get('Articles');
  4461. $tags = $articles->belongsToMany('Tags');
  4462. $actualOptions = null;
  4463. $tags->junction()->eventManager()->on(
  4464. 'Model.beforeDelete',
  4465. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4466. $actualOptions = $options->getArrayCopy();
  4467. }
  4468. );
  4469. $article = $articles->get(1);
  4470. $tags->unlink($article, [$tags->target()->get(1)], false);
  4471. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4472. $this->assertFalse($actualOptions['cleanProperty']);
  4473. $actualOptions = null;
  4474. $tags->unlink($article, [$tags->target()->get(2)]);
  4475. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4476. $this->assertTrue($actualOptions['cleanProperty']);
  4477. }
  4478. /**
  4479. * Tests backwards compatibility of the the `$options` argument, formerly `$cleanProperty`.
  4480. *
  4481. * @return void
  4482. */
  4483. public function testBackwardsCompatibilityForHasManyUnlinkCleanPropertyOption()
  4484. {
  4485. $authors = TableRegistry::get('Authors');
  4486. $articles = $authors->hasMany('Articles');
  4487. $articles->dependent(true);
  4488. $articles->cascadeCallbacks(true);
  4489. $actualOptions = null;
  4490. $articles->target()->eventManager()->on(
  4491. 'Model.beforeDelete',
  4492. function (Event $event, Entity $entity, ArrayObject $options) use (&$actualOptions) {
  4493. $actualOptions = $options->getArrayCopy();
  4494. }
  4495. );
  4496. $author = $authors->get(1);
  4497. $author->articles = [];
  4498. $author->dirty('articles', true);
  4499. $articles->unlink($author, [$articles->target()->get(1)], false);
  4500. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4501. $this->assertFalse($actualOptions['cleanProperty']);
  4502. $actualOptions = null;
  4503. $articles->unlink($author, [$articles->target()->get(3)]);
  4504. $this->assertArrayHasKey('cleanProperty', $actualOptions);
  4505. $this->assertTrue($actualOptions['cleanProperty']);
  4506. }
  4507. /**
  4508. * Tests that it is possible to call find with no arguments
  4509. *
  4510. * @return void
  4511. */
  4512. public function testSimplifiedFind()
  4513. {
  4514. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4515. ->setMethods(['callFinder'])
  4516. ->setConstructorArgs([[
  4517. 'connection' => $this->connection,
  4518. 'schema' => ['id' => ['type' => 'integer']]
  4519. ]])
  4520. ->getMock();
  4521. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  4522. $table->expects($this->once())->method('callFinder')
  4523. ->with('all', $query, []);
  4524. $table->find();
  4525. }
  4526. public function providerForTestGet()
  4527. {
  4528. return [
  4529. [ ['fields' => ['id']] ],
  4530. [ ['fields' => ['id'], 'cache' => false] ]
  4531. ];
  4532. }
  4533. /**
  4534. * Test that get() will use the primary key for searching and return the first
  4535. * entity found
  4536. *
  4537. * @dataProvider providerForTestGet
  4538. * @param array $options
  4539. * @return void
  4540. */
  4541. public function testGet($options)
  4542. {
  4543. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4544. ->setMethods(['callFinder', 'query'])
  4545. ->setConstructorArgs([[
  4546. 'connection' => $this->connection,
  4547. 'schema' => [
  4548. 'id' => ['type' => 'integer'],
  4549. 'bar' => ['type' => 'integer'],
  4550. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  4551. ]
  4552. ]])
  4553. ->getMock();
  4554. $query = $this->getMockBuilder('\Cake\ORM\Query')
  4555. ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
  4556. ->setConstructorArgs([$this->connection, $table])
  4557. ->getMock();
  4558. $entity = new \Cake\ORM\Entity;
  4559. $table->expects($this->once())->method('query')
  4560. ->will($this->returnValue($query));
  4561. $table->expects($this->once())->method('callFinder')
  4562. ->with('all', $query, ['fields' => ['id']])
  4563. ->will($this->returnValue($query));
  4564. $query->expects($this->once())->method('where')
  4565. ->with([$table->alias() . '.bar' => 10])
  4566. ->will($this->returnSelf());
  4567. $query->expects($this->never())->method('cache');
  4568. $query->expects($this->once())->method('firstOrFail')
  4569. ->will($this->returnValue($entity));
  4570. $result = $table->get(10, $options);
  4571. $this->assertSame($entity, $result);
  4572. }
  4573. public function providerForTestGetWithCustomFinder()
  4574. {
  4575. return [
  4576. [ ['fields' => ['id'], 'finder' => 'custom'] ]
  4577. ];
  4578. }
  4579. /**
  4580. * Test that get() will call a custom finder.
  4581. *
  4582. * @dataProvider providerForTestGetWithCustomFinder
  4583. * @param array $options
  4584. * @return void
  4585. */
  4586. public function testGetWithCustomFinder($options)
  4587. {
  4588. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4589. ->setMethods(['callFinder', 'query'])
  4590. ->setConstructorArgs([[
  4591. 'connection' => $this->connection,
  4592. 'schema' => [
  4593. 'id' => ['type' => 'integer'],
  4594. 'bar' => ['type' => 'integer'],
  4595. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  4596. ]
  4597. ]])
  4598. ->getMock();
  4599. $query = $this->getMockBuilder('\Cake\ORM\Query')
  4600. ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
  4601. ->setConstructorArgs([$this->connection, $table])
  4602. ->getMock();
  4603. $entity = new \Cake\ORM\Entity;
  4604. $table->expects($this->once())->method('query')
  4605. ->will($this->returnValue($query));
  4606. $table->expects($this->once())->method('callFinder')
  4607. ->with('custom', $query, ['fields' => ['id']])
  4608. ->will($this->returnValue($query));
  4609. $query->expects($this->once())->method('where')
  4610. ->with([$table->alias() . '.bar' => 10])
  4611. ->will($this->returnSelf());
  4612. $query->expects($this->never())->method('cache');
  4613. $query->expects($this->once())->method('firstOrFail')
  4614. ->will($this->returnValue($entity));
  4615. $result = $table->get(10, $options);
  4616. $this->assertSame($entity, $result);
  4617. }
  4618. public function providerForTestGetWithCache()
  4619. {
  4620. return [
  4621. [
  4622. ['fields' => ['id'], 'cache' => 'default'],
  4623. 'get:test.table_name[10]', 'default'
  4624. ],
  4625. [
  4626. ['fields' => ['id'], 'cache' => 'default', 'key' => 'custom_key'],
  4627. 'custom_key', 'default'
  4628. ]
  4629. ];
  4630. }
  4631. /**
  4632. * Test that get() will use the cache.
  4633. *
  4634. * @dataProvider providerForTestGetWithCache
  4635. * @param array $options
  4636. * @param string $cacheKey
  4637. * @param string $cacheConfig
  4638. * @return void
  4639. */
  4640. public function testGetWithCache($options, $cacheKey, $cacheConfig)
  4641. {
  4642. $table = $this->getMockBuilder('\Cake\ORM\Table')
  4643. ->setMethods(['callFinder', 'query'])
  4644. ->setConstructorArgs([[
  4645. 'connection' => $this->connection,
  4646. 'schema' => [
  4647. 'id' => ['type' => 'integer'],
  4648. 'bar' => ['type' => 'integer'],
  4649. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  4650. ]
  4651. ]])
  4652. ->getMock();
  4653. $table->table('table_name');
  4654. $query = $this->getMockBuilder('\Cake\ORM\Query')
  4655. ->setMethods(['addDefaultTypes', 'firstOrFail', 'where', 'cache'])
  4656. ->setConstructorArgs([$this->connection, $table])
  4657. ->getMock();
  4658. $entity = new \Cake\ORM\Entity;
  4659. $table->expects($this->once())->method('query')
  4660. ->will($this->returnValue($query));
  4661. $table->expects($this->once())->method('callFinder')
  4662. ->with('all', $query, ['fields' => ['id']])
  4663. ->will($this->returnValue($query));
  4664. $query->expects($this->once())->method('where')
  4665. ->with([$table->alias() . '.bar' => 10])
  4666. ->will($this->returnSelf());
  4667. $query->expects($this->once())->method('cache')
  4668. ->with($cacheKey, $cacheConfig)
  4669. ->will($this->returnSelf());
  4670. $query->expects($this->once())->method('firstOrFail')
  4671. ->will($this->returnValue($entity));
  4672. $result = $table->get(10, $options);
  4673. $this->assertSame($entity, $result);
  4674. }
  4675. /**
  4676. * Tests that get() will throw an exception if the record was not found
  4677. *
  4678. * @expectedException Cake\Datasource\Exception\RecordNotFoundException
  4679. * @expectedExceptionMessage Record not found in table "articles"
  4680. * @return void
  4681. */
  4682. public function testGetNotFoundException()
  4683. {
  4684. $table = new Table([
  4685. 'name' => 'Articles',
  4686. 'connection' => $this->connection,
  4687. 'table' => 'articles',
  4688. ]);
  4689. $table->get(10);
  4690. }
  4691. /**
  4692. * Test that an exception is raised when there are not enough keys.
  4693. *
  4694. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  4695. * @expectedExceptionMessage Record not found in table "articles" with primary key [NULL]
  4696. * @return void
  4697. */
  4698. public function testGetExceptionOnNoData()
  4699. {
  4700. $table = new Table([
  4701. 'name' => 'Articles',
  4702. 'connection' => $this->connection,
  4703. 'table' => 'articles',
  4704. ]);
  4705. $table->get(null);
  4706. }
  4707. /**
  4708. * Test that an exception is raised when there are too many keys.
  4709. *
  4710. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  4711. * @expectedExceptionMessage Record not found in table "articles" with primary key [1, 'two']
  4712. * @return void
  4713. */
  4714. public function testGetExceptionOnTooMuchData()
  4715. {
  4716. $table = new Table([
  4717. 'name' => 'Articles',
  4718. 'connection' => $this->connection,
  4719. 'table' => 'articles',
  4720. ]);
  4721. $table->get([1, 'two']);
  4722. }
  4723. /**
  4724. * Tests that patchEntity delegates the task to the marshaller and passed
  4725. * all associations
  4726. *
  4727. * @return void
  4728. */
  4729. public function testPatchEntity()
  4730. {
  4731. $table = $this->getMockBuilder('Cake\ORM\Table')
  4732. ->setMethods(['marshaller'])
  4733. ->getMock();
  4734. $marshaller = $this->getMockBuilder('Cake\ORM\Marshaller')
  4735. ->setConstructorArgs([$table])
  4736. ->getMock();
  4737. $table->belongsTo('users');
  4738. $table->hasMany('articles');
  4739. $table->expects($this->once())->method('marshaller')
  4740. ->will($this->returnValue($marshaller));
  4741. $entity = new \Cake\ORM\Entity;
  4742. $data = ['foo' => 'bar'];
  4743. $marshaller->expects($this->once())
  4744. ->method('merge')
  4745. ->with($entity, $data, ['associated' => ['users', 'articles']])
  4746. ->will($this->returnValue($entity));
  4747. $table->patchEntity($entity, $data);
  4748. }
  4749. /**
  4750. * Tests that patchEntities delegates the task to the marshaller and passed
  4751. * all associations
  4752. *
  4753. * @return void
  4754. */
  4755. public function testPatchEntities()
  4756. {
  4757. $table = $this->getMockBuilder('Cake\ORM\Table')
  4758. ->setMethods(['marshaller'])
  4759. ->getMock();
  4760. $marshaller = $this->getMockBuilder('Cake\ORM\Marshaller')
  4761. ->setConstructorArgs([$table])
  4762. ->getMock();
  4763. $table->belongsTo('users');
  4764. $table->hasMany('articles');
  4765. $table->expects($this->once())->method('marshaller')
  4766. ->will($this->returnValue($marshaller));
  4767. $entities = [new \Cake\ORM\Entity];
  4768. $data = [['foo' => 'bar']];
  4769. $marshaller->expects($this->once())
  4770. ->method('mergeMany')
  4771. ->with($entities, $data, ['associated' => ['users', 'articles']])
  4772. ->will($this->returnValue($entities));
  4773. $table->patchEntities($entities, $data);
  4774. }
  4775. /**
  4776. * Tests __debugInfo
  4777. *
  4778. * @return void
  4779. */
  4780. public function testDebugInfo()
  4781. {
  4782. $articles = TableRegistry::get('articles');
  4783. $articles->addBehavior('Timestamp');
  4784. $result = $articles->__debugInfo();
  4785. $expected = [
  4786. 'registryAlias' => 'articles',
  4787. 'table' => 'articles',
  4788. 'alias' => 'articles',
  4789. 'entityClass' => 'TestApp\Model\Entity\Article',
  4790. 'associations' => ['authors', 'tags', 'articlestags'],
  4791. 'behaviors' => ['Timestamp'],
  4792. 'defaultConnection' => 'default',
  4793. 'connectionName' => 'test'
  4794. ];
  4795. $this->assertEquals($expected, $result);
  4796. $articles = TableRegistry::get('Foo.Articles');
  4797. $result = $articles->__debugInfo();
  4798. $expected = [
  4799. 'registryAlias' => 'Foo.Articles',
  4800. 'table' => 'articles',
  4801. 'alias' => 'Articles',
  4802. 'entityClass' => '\Cake\ORM\Entity',
  4803. 'associations' => [],
  4804. 'behaviors' => [],
  4805. 'defaultConnection' => 'default',
  4806. 'connectionName' => 'test'
  4807. ];
  4808. $this->assertEquals($expected, $result);
  4809. }
  4810. /**
  4811. * Test that findOrCreate creates a new entity, and then finds that entity.
  4812. *
  4813. * @return void
  4814. */
  4815. public function testFindOrCreateNewEntity()
  4816. {
  4817. $articles = TableRegistry::get('Articles');
  4818. $callbackExecuted = false;
  4819. $firstArticle = $articles->findOrCreate(['title' => 'Not there'], function ($article) use (&$callbackExecuted) {
  4820. $this->assertTrue($article instanceof EntityInterface);
  4821. $article->body = 'New body';
  4822. $callbackExecuted = true;
  4823. });
  4824. $this->assertTrue($callbackExecuted);
  4825. $this->assertFalse($firstArticle->isNew());
  4826. $this->assertNotNull($firstArticle->id);
  4827. $this->assertEquals('Not there', $firstArticle->title);
  4828. $this->assertEquals('New body', $firstArticle->body);
  4829. $secondArticle = $articles->findOrCreate(['title' => 'Not there'], function ($article) {
  4830. $this->fail('Should not be called for existing entities.');
  4831. });
  4832. $this->assertFalse($secondArticle->isNew());
  4833. $this->assertNotNull($secondArticle->id);
  4834. $this->assertEquals('Not there', $secondArticle->title);
  4835. $this->assertEquals($firstArticle->id, $secondArticle->id);
  4836. }
  4837. /**
  4838. * Test that findOrCreate finds fixture data.
  4839. *
  4840. * @return void
  4841. */
  4842. public function testFindOrCreateExistingEntity()
  4843. {
  4844. $articles = TableRegistry::get('Articles');
  4845. $article = $articles->findOrCreate(['title' => 'First Article'], function ($article) {
  4846. $this->fail('Should not be called for existing entities.');
  4847. });
  4848. $this->assertFalse($article->isNew());
  4849. $this->assertNotNull($article->id);
  4850. $this->assertEquals('First Article', $article->title);
  4851. }
  4852. /**
  4853. * Test that findOrCreate uses the search conditions as defaults for new entity.
  4854. *
  4855. * @return void
  4856. */
  4857. public function testFindOrCreateDefaults()
  4858. {
  4859. $articles = TableRegistry::get('Articles');
  4860. $callbackExecuted = false;
  4861. $article = $articles->findOrCreate(
  4862. ['author_id' => 2, 'title' => 'First Article'],
  4863. function ($article) use (&$callbackExecuted) {
  4864. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  4865. $article->set(['published' => 'N', 'body' => 'New body']);
  4866. $callbackExecuted = true;
  4867. }
  4868. );
  4869. $this->assertTrue($callbackExecuted);
  4870. $this->assertFalse($article->isNew());
  4871. $this->assertNotNull($article->id);
  4872. $this->assertEquals('First Article', $article->title);
  4873. $this->assertEquals('New body', $article->body);
  4874. $this->assertEquals('N', $article->published);
  4875. $this->assertEquals(2, $article->author_id);
  4876. $query = $articles->find()->where(['author_id' => 2, 'title' => 'First Article']);
  4877. $article = $articles->findOrCreate($query);
  4878. $this->assertEquals('First Article', $article->title);
  4879. $this->assertEquals(2, $article->author_id);
  4880. $this->assertFalse($article->isNew());
  4881. }
  4882. /**
  4883. * Test that findOrCreate adds new entity without using a callback.
  4884. *
  4885. * @return void
  4886. */
  4887. public function testFindOrCreateNoCallable()
  4888. {
  4889. $articles = TableRegistry::get('Articles');
  4890. $article = $articles->findOrCreate(['title' => 'Just Something New']);
  4891. $this->assertFalse($article->isNew());
  4892. $this->assertNotNull($article->id);
  4893. $this->assertEquals('Just Something New', $article->title);
  4894. }
  4895. /**
  4896. * Test that findOrCreate executes search conditions as a callable.
  4897. *
  4898. * @return void
  4899. */
  4900. public function testFindOrCreateSearchCallable()
  4901. {
  4902. $articles = TableRegistry::get('Articles');
  4903. $calledOne = false;
  4904. $calledTwo = false;
  4905. $article = $articles->findOrCreate(function ($query) use (&$calledOne) {
  4906. $this->assertInstanceOf('Cake\ORM\Query', $query);
  4907. $query->where(['title' => 'Something Else']);
  4908. $calledOne = true;
  4909. }, function ($article) use (&$calledTwo) {
  4910. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  4911. $article->title = 'Set Defaults Here';
  4912. $calledTwo = true;
  4913. });
  4914. $this->assertTrue($calledOne);
  4915. $this->assertTrue($calledTwo);
  4916. $this->assertFalse($article->isNew());
  4917. $this->assertNotNull($article->id);
  4918. $this->assertEquals('Set Defaults Here', $article->title);
  4919. }
  4920. /**
  4921. * Test that findOrCreate options disable defaults.
  4922. *
  4923. * @return void
  4924. */
  4925. public function testFindOrCreateNoDefaults()
  4926. {
  4927. $articles = TableRegistry::get('Articles');
  4928. $article = $articles->findOrCreate(['title' => 'A New Article', 'published' => 'Y'], function ($article) {
  4929. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  4930. $article->title = 'A Different Title';
  4931. }, ['defaults' => false]);
  4932. $this->assertFalse($article->isNew());
  4933. $this->assertNotNull($article->id);
  4934. $this->assertEquals('A Different Title', $article->title);
  4935. $this->assertNull($article->published, 'Expected Null since defaults are disabled.');
  4936. }
  4937. /**
  4938. * Test that findOrCreate executes callable inside transaction.
  4939. *
  4940. * @return void
  4941. */
  4942. public function testFindOrCreateTransactions()
  4943. {
  4944. $articles = TableRegistry::get('Articles');
  4945. $article = $articles->findOrCreate(function ($query) {
  4946. $this->assertInstanceOf('Cake\ORM\Query', $query);
  4947. $query->where(['title' => 'Find Something New']);
  4948. $this->assertTrue($this->connection->inTransaction());
  4949. }, function ($article) {
  4950. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  4951. $this->assertTrue($this->connection->inTransaction());
  4952. $article->title = 'Success';
  4953. });
  4954. $this->assertFalse($article->isNew());
  4955. $this->assertNotNull($article->id);
  4956. $this->assertEquals('Success', $article->title);
  4957. }
  4958. /**
  4959. * Test that findOrCreate executes callable without transaction.
  4960. *
  4961. * @return void
  4962. */
  4963. public function testFindOrCreateNoTransaction()
  4964. {
  4965. $articles = TableRegistry::get('Articles');
  4966. $article = $articles->findOrCreate(function ($query) {
  4967. $this->assertInstanceOf('Cake\ORM\Query', $query);
  4968. $query->where(['title' => 'Find Something New']);
  4969. $this->assertFalse($this->connection->inTransaction());
  4970. }, function ($article) {
  4971. $this->assertInstanceOf('Cake\Datasource\EntityInterface', $article);
  4972. $this->assertFalse($this->connection->inTransaction());
  4973. $article->title = 'Success';
  4974. }, ['atomic' => false]);
  4975. $this->assertFalse($article->isNew());
  4976. $this->assertNotNull($article->id);
  4977. $this->assertEquals('Success', $article->title);
  4978. }
  4979. /**
  4980. * Test that creating a table fires the initialize event.
  4981. *
  4982. * @return void
  4983. */
  4984. public function testInitializeEvent()
  4985. {
  4986. $count = 0;
  4987. $cb = function ($event) use (&$count) {
  4988. $count++;
  4989. };
  4990. EventManager::instance()->on('Model.initialize', $cb);
  4991. $articles = TableRegistry::get('Articles');
  4992. $this->assertEquals(1, $count, 'Callback should be called');
  4993. EventManager::instance()->detach($cb, 'Model.initialize');
  4994. }
  4995. /**
  4996. * Tests the hasFinder method
  4997. *
  4998. * @return void
  4999. */
  5000. public function testHasFinder()
  5001. {
  5002. $table = TableRegistry::get('articles');
  5003. $table->addBehavior('Sluggable');
  5004. $this->assertTrue($table->hasFinder('list'));
  5005. $this->assertTrue($table->hasFinder('noSlug'));
  5006. $this->assertFalse($table->hasFinder('noFind'));
  5007. }
  5008. /**
  5009. * Tests that calling validator() trigger the buildValidator event
  5010. *
  5011. * @return void
  5012. */
  5013. public function testBuildValidatorEvent()
  5014. {
  5015. $count = 0;
  5016. $cb = function ($event) use (&$count) {
  5017. $count++;
  5018. };
  5019. EventManager::instance()->on('Model.buildValidator', $cb);
  5020. $articles = TableRegistry::get('Articles');
  5021. $articles->validator();
  5022. $this->assertEquals(1, $count, 'Callback should be called');
  5023. $articles->validator();
  5024. $this->assertEquals(1, $count, 'Callback should be called only once');
  5025. }
  5026. /**
  5027. * Tests the validateUnique method with different combinations
  5028. *
  5029. * @return void
  5030. */
  5031. public function testValidateUnique()
  5032. {
  5033. $table = TableRegistry::get('Users');
  5034. $validator = new Validator;
  5035. $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
  5036. $validator->provider('table', $table);
  5037. $data = ['username' => ['larry', 'notthere']];
  5038. $this->assertNotEmpty($validator->errors($data));
  5039. $data = ['username' => 'larry'];
  5040. $this->assertNotEmpty($validator->errors($data));
  5041. $data = ['username' => 'jose'];
  5042. $this->assertEmpty($validator->errors($data));
  5043. $data = ['username' => 'larry', 'id' => 3];
  5044. $this->assertEmpty($validator->errors($data, false));
  5045. $data = ['username' => 'larry', 'id' => 3];
  5046. $this->assertNotEmpty($validator->errors($data));
  5047. $data = ['username' => 'larry'];
  5048. $this->assertNotEmpty($validator->errors($data, false));
  5049. $validator->add('username', 'unique', [
  5050. 'rule' => 'validateUnique', 'provider' => 'table'
  5051. ]);
  5052. $data = ['username' => 'larry'];
  5053. $this->assertNotEmpty($validator->errors($data, false));
  5054. }
  5055. /**
  5056. * Tests the validateUnique method with scope
  5057. *
  5058. * @return void
  5059. */
  5060. public function testValidateUniqueScope()
  5061. {
  5062. $table = TableRegistry::get('Users');
  5063. $validator = new Validator;
  5064. $validator->add('username', 'unique', [
  5065. 'rule' => ['validateUnique', ['derp' => 'erp', 'scope' => 'id']],
  5066. 'provider' => 'table'
  5067. ]);
  5068. $validator->provider('table', $table);
  5069. $data = ['username' => 'larry', 'id' => 3];
  5070. $this->assertNotEmpty($validator->errors($data));
  5071. $data = ['username' => 'larry', 'id' => 1];
  5072. $this->assertEmpty($validator->errors($data));
  5073. $data = ['username' => 'jose'];
  5074. $this->assertEmpty($validator->errors($data));
  5075. }
  5076. /**
  5077. * Tests that the callbacks receive the expected types of arguments.
  5078. *
  5079. * @return void
  5080. */
  5081. public function testCallbackArgumentTypes()
  5082. {
  5083. $table = TableRegistry::get('articles');
  5084. $table->belongsTo('authors');
  5085. $eventManager = $table->eventManager();
  5086. $associationBeforeFindCount = 0;
  5087. $table->association('authors')->target()->eventManager()->on(
  5088. 'Model.beforeFind',
  5089. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) {
  5090. $this->assertTrue(is_bool($primary));
  5091. $associationBeforeFindCount ++;
  5092. }
  5093. );
  5094. $beforeFindCount = 0;
  5095. $eventManager->on(
  5096. 'Model.beforeFind',
  5097. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) {
  5098. $this->assertTrue(is_bool($primary));
  5099. $beforeFindCount ++;
  5100. }
  5101. );
  5102. $table->find()->contain('authors')->first();
  5103. $this->assertEquals(1, $associationBeforeFindCount);
  5104. $this->assertEquals(1, $beforeFindCount);
  5105. $buildValidatorCount = 0;
  5106. $eventManager->on(
  5107. 'Model.buildValidator',
  5108. $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) {
  5109. $this->assertTrue(is_string($name));
  5110. $buildValidatorCount ++;
  5111. }
  5112. );
  5113. $table->validator();
  5114. $this->assertEquals(1, $buildValidatorCount);
  5115. $buildRulesCount =
  5116. $beforeRulesCount =
  5117. $afterRulesCount =
  5118. $beforeSaveCount =
  5119. $afterSaveCount = 0;
  5120. $eventManager->on(
  5121. 'Model.buildRules',
  5122. function (Event $event, RulesChecker $rules) use (&$buildRulesCount) {
  5123. $buildRulesCount ++;
  5124. }
  5125. );
  5126. $eventManager->on(
  5127. 'Model.beforeRules',
  5128. function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) {
  5129. $this->assertTrue(is_string($operation));
  5130. $beforeRulesCount ++;
  5131. }
  5132. );
  5133. $eventManager->on(
  5134. 'Model.afterRules',
  5135. function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) {
  5136. $this->assertTrue(is_bool($result));
  5137. $this->assertTrue(is_string($operation));
  5138. $afterRulesCount ++;
  5139. }
  5140. );
  5141. $eventManager->on(
  5142. 'Model.beforeSave',
  5143. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) {
  5144. $beforeSaveCount ++;
  5145. }
  5146. );
  5147. $eventManager->on(
  5148. 'Model.afterSave',
  5149. $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) {
  5150. $afterSaveCount ++;
  5151. }
  5152. );
  5153. $entity = new Entity(['title' => 'Title']);
  5154. $this->assertNotFalse($table->save($entity));
  5155. $this->assertEquals(1, $buildRulesCount);
  5156. $this->assertEquals(1, $beforeRulesCount);
  5157. $this->assertEquals(1, $afterRulesCount);
  5158. $this->assertEquals(1, $beforeSaveCount);
  5159. $this->assertEquals(1, $afterSaveCount);
  5160. $beforeDeleteCount =
  5161. $afterDeleteCount = 0;
  5162. $eventManager->on(
  5163. 'Model.beforeDelete',
  5164. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) {
  5165. $beforeDeleteCount ++;
  5166. }
  5167. );
  5168. $eventManager->on(
  5169. 'Model.afterDelete',
  5170. function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) {
  5171. $afterDeleteCount ++;
  5172. }
  5173. );
  5174. $this->assertTrue($table->delete($entity, ['checkRules' => false]));
  5175. $this->assertEquals(1, $beforeDeleteCount);
  5176. $this->assertEquals(1, $afterDeleteCount);
  5177. }
  5178. /**
  5179. * Tests that calling newEntity() on a table sets the right source alias
  5180. *
  5181. * @return void
  5182. */
  5183. public function testEntitySource()
  5184. {
  5185. $table = TableRegistry::get('Articles');
  5186. $this->assertEquals('Articles', $table->newEntity()->source());
  5187. Plugin::load('TestPlugin');
  5188. $table = TableRegistry::get('TestPlugin.Comments');
  5189. $this->assertEquals('TestPlugin.Comments', $table->newEntity()->source());
  5190. }
  5191. /**
  5192. * Tests that passing a coned entity that was marked as new to save() will
  5193. * actaully save it as a new entity
  5194. *
  5195. * @group save
  5196. * @return void
  5197. */
  5198. public function testSaveWithClonedEntity()
  5199. {
  5200. $table = TableRegistry::get('Articles');
  5201. $article = $table->get(1);
  5202. $cloned = clone $article;
  5203. $cloned->unsetProperty('id');
  5204. $cloned->isNew(true);
  5205. $this->assertSame($cloned, $table->save($cloned));
  5206. $this->assertEquals(
  5207. $article->extract(['title', 'author_id']),
  5208. $cloned->extract(['title', 'author_id'])
  5209. );
  5210. $this->assertEquals(4, $cloned->id);
  5211. }
  5212. /**
  5213. * Tests that the _ids notation can be used for HasMany
  5214. *
  5215. * @return void
  5216. */
  5217. public function testSaveHasManyWithIds()
  5218. {
  5219. $data = [
  5220. 'username' => 'lux',
  5221. 'password' => 'passphrase',
  5222. 'comments' => [
  5223. '_ids' => [1, 2]
  5224. ]
  5225. ];
  5226. $userTable = TableRegistry::get('Users');
  5227. $userTable->hasMany('Comments');
  5228. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  5229. $retrievedUser = $userTable->find('all')->where(['id' => $savedUser->id])->contain(['Comments'])->first();
  5230. $this->assertEquals($savedUser->comments[0]->user_id, $retrievedUser->comments[0]->user_id);
  5231. $this->assertEquals($savedUser->comments[1]->user_id, $retrievedUser->comments[1]->user_id);
  5232. }
  5233. /**
  5234. * Tests that on second save, entities for the has many relation are not marked
  5235. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  5236. * for a cleaner transaction log
  5237. *
  5238. * @return void
  5239. */
  5240. public function testSaveHasManyNoWasteSave()
  5241. {
  5242. $data = [
  5243. 'username' => 'lux',
  5244. 'password' => 'passphrase',
  5245. 'comments' => [
  5246. '_ids' => [1, 2]
  5247. ]
  5248. ];
  5249. $userTable = TableRegistry::get('Users');
  5250. $userTable->hasMany('Comments');
  5251. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  5252. $counter = 0;
  5253. $userTable->Comments
  5254. ->eventManager()
  5255. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  5256. if ($entity->dirty()) {
  5257. $counter++;
  5258. }
  5259. });
  5260. $savedUser->comments[] = $userTable->Comments->get(5);
  5261. $this->assertCount(3, $savedUser->comments);
  5262. $savedUser->dirty('comments', true);
  5263. $userTable->save($savedUser);
  5264. $this->assertEquals(1, $counter);
  5265. }
  5266. /**
  5267. * Tests that on second save, entities for the belongsToMany relation are not marked
  5268. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  5269. * for a cleaner transaction log
  5270. *
  5271. * @return void
  5272. */
  5273. public function testSaveBelongsToManyNoWasteSave()
  5274. {
  5275. $data = [
  5276. 'title' => 'foo',
  5277. 'body' => 'bar',
  5278. 'tags' => [
  5279. '_ids' => [1, 2]
  5280. ]
  5281. ];
  5282. $table = TableRegistry::get('Articles');
  5283. $table->belongsToMany('Tags');
  5284. $article = $table->save($table->newEntity($data, ['associated' => ['Tags']]));
  5285. $counter = 0;
  5286. $table->Tags->junction()
  5287. ->eventManager()
  5288. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  5289. if ($entity->dirty()) {
  5290. $counter++;
  5291. }
  5292. });
  5293. $article->tags[] = $table->Tags->get(3);
  5294. $this->assertCount(3, $article->tags);
  5295. $article->dirty('tags', true);
  5296. $table->save($article);
  5297. $this->assertEquals(1, $counter);
  5298. }
  5299. /**
  5300. * Tests that after saving then entity contains the right primary
  5301. * key casted to the right type
  5302. *
  5303. * @group save
  5304. * @return void
  5305. */
  5306. public function testSaveCorrectPrimaryKeyType()
  5307. {
  5308. $entity = new Entity([
  5309. 'username' => 'superuser',
  5310. 'created' => new Time('2013-10-10 00:00'),
  5311. 'updated' => new Time('2013-10-10 00:00')
  5312. ], ['markNew' => true]);
  5313. $table = TableRegistry::get('Users');
  5314. $this->assertSame($entity, $table->save($entity));
  5315. $this->assertSame(self::$nextUserId, $entity->id);
  5316. }
  5317. /**
  5318. * Tests the loadInto() method
  5319. *
  5320. * @return void
  5321. */
  5322. public function testLoadIntoEntity()
  5323. {
  5324. $table = TableRegistry::get('Authors');
  5325. $table->hasMany('SiteArticles');
  5326. $articles = $table->hasMany('Articles');
  5327. $articles->belongsToMany('Tags');
  5328. $entity = $table->get(1);
  5329. $result = $table->loadInto($entity, ['SiteArticles', 'Articles.Tags']);
  5330. $this->assertSame($entity, $result);
  5331. $expected = $table->get(1, ['contain' => ['SiteArticles', 'Articles.Tags']]);
  5332. $this->assertEquals($expected, $result);
  5333. }
  5334. /**
  5335. * Tests that it is possible to pass conditions and fields to loadInto()
  5336. *
  5337. * @return void
  5338. */
  5339. public function testLoadIntoWithConditions()
  5340. {
  5341. $table = TableRegistry::get('Authors');
  5342. $table->hasMany('SiteArticles');
  5343. $articles = $table->hasMany('Articles');
  5344. $articles->belongsToMany('Tags');
  5345. $entity = $table->get(1);
  5346. $options = [
  5347. 'SiteArticles' => ['fields' => ['title', 'author_id']],
  5348. 'Articles.Tags' => function ($q) {
  5349. return $q->where(['Tags.name' => 'tag2']);
  5350. }
  5351. ];
  5352. $result = $table->loadInto($entity, $options);
  5353. $this->assertSame($entity, $result);
  5354. $expected = $table->get(1, ['contain' => $options]);
  5355. $this->assertEquals($expected, $result);
  5356. }
  5357. /**
  5358. * Tests loadInto() with a belongsTo association
  5359. *
  5360. * @return void
  5361. */
  5362. public function testLoadBelognsTo()
  5363. {
  5364. $table = TableRegistry::get('Articles');
  5365. $table->belongsTo('Authors');
  5366. $entity = $table->get(2);
  5367. $result = $table->loadInto($entity, ['Authors']);
  5368. $this->assertSame($entity, $result);
  5369. $expected = $table->get(2, ['contain' => ['Authors']]);
  5370. $this->assertEquals($expected, $entity);
  5371. }
  5372. /**
  5373. * Tests that it is possible to post-load associations for many entities at
  5374. * the same time
  5375. *
  5376. * @return void
  5377. */
  5378. public function testLoadIntoMany()
  5379. {
  5380. $table = TableRegistry::get('Authors');
  5381. $table->hasMany('SiteArticles');
  5382. $articles = $table->hasMany('Articles');
  5383. $articles->belongsToMany('Tags');
  5384. $entities = $table->find()->compile();
  5385. $contain = ['SiteArticles', 'Articles.Tags'];
  5386. $result = $table->loadInto($entities, $contain);
  5387. foreach ($entities as $k => $v) {
  5388. $this->assertSame($v, $result[$k]);
  5389. }
  5390. $expected = $table->find()->contain($contain)->toList();
  5391. $this->assertEquals($expected, $result);
  5392. }
  5393. /**
  5394. * Test getting the save options builder.
  5395. *
  5396. * @return void
  5397. */
  5398. public function getSaveOptionsBuilder()
  5399. {
  5400. $table = TableRegistry::get('Authors');
  5401. $result = $table->getSaveOptionsBuilder();
  5402. $this->assertInstanceOf('Cake\ORM\SaveOptionsBuilder', $result);
  5403. }
  5404. /**
  5405. * Helper method to skip tests when connection is SQLServer.
  5406. *
  5407. * @return void
  5408. */
  5409. public function skipIfSqlServer()
  5410. {
  5411. $this->skipIf(
  5412. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  5413. 'SQLServer does not support the requirements of this test.'
  5414. );
  5415. }
  5416. }