TableTest.php 210 KB

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