TableTest.php 194 KB

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