TableTest.php 197 KB

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