TableTest.php 212 KB

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