TableTest.php 219 KB

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