TableTest.php 183 KB

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