TableTest.php 193 KB

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