TableTest.php 215 KB

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