TableTest.php 201 KB

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