TableTest.php 210 KB

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