TableTest.php 224 KB

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