TableTest.php 197 KB

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