TableTest.php 209 KB

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