TableTest.php 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594
  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\Core\Configure;
  18. use Cake\Core\Plugin;
  19. use Cake\Database\Exception;
  20. use Cake\Database\Expression\QueryExpression;
  21. use Cake\Database\TypeMap;
  22. use Cake\Datasource\ConnectionManager;
  23. use Cake\Event\Event;
  24. use Cake\Event\EventManager;
  25. use Cake\I18n\Time;
  26. use Cake\ORM\Entity;
  27. use Cake\ORM\Query;
  28. use Cake\ORM\RulesChecker;
  29. use Cake\ORM\Table;
  30. use Cake\ORM\TableRegistry;
  31. use Cake\TestSuite\TestCase;
  32. use Cake\Validation\Validator;
  33. /**
  34. * Used to test correct class is instantiated when using TableRegistry::get();
  35. */
  36. class UsersTable extends Table
  37. {
  38. }
  39. /**
  40. * Tests Table class
  41. *
  42. */
  43. class TableTest extends TestCase
  44. {
  45. public $fixtures = [
  46. 'core.articles',
  47. 'core.articles_tags',
  48. 'core.authors',
  49. 'core.categories',
  50. 'core.comments',
  51. 'core.groups',
  52. 'core.groups_members',
  53. 'core.members',
  54. 'core.polymorphic_tagged',
  55. 'core.site_articles',
  56. 'core.tags',
  57. 'core.users'
  58. ];
  59. /**
  60. * Handy variable containing the next primary key that will be inserted in the
  61. * users table
  62. *
  63. * @var int
  64. */
  65. public static $nextUserId = 5;
  66. public function setUp()
  67. {
  68. parent::setUp();
  69. $this->connection = ConnectionManager::get('test');
  70. Configure::write('App.namespace', 'TestApp');
  71. $this->usersTypeMap = new TypeMap([
  72. 'Users.id' => 'integer',
  73. 'id' => 'integer',
  74. 'Users.username' => 'string',
  75. 'username' => 'string',
  76. 'Users.password' => 'string',
  77. 'password' => 'string',
  78. 'Users.created' => 'timestamp',
  79. 'created' => 'timestamp',
  80. 'Users.updated' => 'timestamp',
  81. 'updated' => 'timestamp',
  82. ]);
  83. $this->articlesTypeMap = new TypeMap([
  84. 'Articles.id' => 'integer',
  85. 'id' => 'integer',
  86. 'Articles.title' => 'string',
  87. 'title' => 'string',
  88. 'Articles.author_id' => 'integer',
  89. 'author_id' => 'integer',
  90. 'Articles.body' => 'text',
  91. 'body' => 'text',
  92. 'Articles.published' => 'string',
  93. 'published' => 'string',
  94. ]);
  95. }
  96. /**
  97. * teardown method
  98. *
  99. * @return void
  100. */
  101. public function tearDown()
  102. {
  103. parent::tearDown();
  104. TableRegistry::clear();
  105. }
  106. /**
  107. * Tests the table method
  108. *
  109. * @return void
  110. */
  111. public function testTableMethod()
  112. {
  113. $table = new Table(['table' => 'users']);
  114. $this->assertEquals('users', $table->table());
  115. $table = new UsersTable;
  116. $this->assertEquals('users', $table->table());
  117. $table = $this->getMockBuilder('\Cake\ORM\Table')
  118. ->setMethods(['find'])
  119. ->setMockClassName('SpecialThingsTable')
  120. ->getMock();
  121. $this->assertEquals('special_things', $table->table());
  122. $table = new Table(['alias' => 'LoveBoats']);
  123. $this->assertEquals('love_boats', $table->table());
  124. $table->table('other');
  125. $this->assertEquals('other', $table->table());
  126. $table->table('database.other');
  127. $this->assertEquals('database.other', $table->table());
  128. }
  129. /**
  130. * Tests the alias method
  131. *
  132. * @return void
  133. */
  134. public function testAliasMethod()
  135. {
  136. $table = new Table(['alias' => 'users']);
  137. $this->assertEquals('users', $table->alias());
  138. $table = new Table(['table' => 'stuffs']);
  139. $this->assertEquals('stuffs', $table->alias());
  140. $table = new UsersTable;
  141. $this->assertEquals('Users', $table->alias());
  142. $table = $this->getMockBuilder('\Cake\ORM\Table')
  143. ->setMethods(['find'])
  144. ->setMockClassName('SpecialThingTable')
  145. ->getMock();
  146. $this->assertEquals('SpecialThing', $table->alias());
  147. $table->alias('AnotherOne');
  148. $this->assertEquals('AnotherOne', $table->alias());
  149. }
  150. /**
  151. * Test that aliasField() works.
  152. *
  153. * @return void
  154. */
  155. public function testAliasField()
  156. {
  157. $table = new Table(['alias' => 'Users']);
  158. $this->assertEquals('Users.id', $table->aliasField('id'));
  159. }
  160. /**
  161. * Tests connection method
  162. *
  163. * @return void
  164. */
  165. public function testConnection()
  166. {
  167. $table = new Table(['table' => 'users']);
  168. $this->assertNull($table->connection());
  169. $table->connection($this->connection);
  170. $this->assertSame($this->connection, $table->connection());
  171. }
  172. /**
  173. * Tests primaryKey method
  174. *
  175. * @return void
  176. */
  177. public function testPrimaryKey()
  178. {
  179. $table = new Table([
  180. 'table' => 'users',
  181. 'schema' => [
  182. 'id' => ['type' => 'integer'],
  183. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  184. ]
  185. ]);
  186. $this->assertEquals('id', $table->primaryKey());
  187. $table->primaryKey('thingID');
  188. $this->assertEquals('thingID', $table->primaryKey());
  189. $table->primaryKey(['thingID', 'user_id']);
  190. $this->assertEquals(['thingID', 'user_id'], $table->primaryKey());
  191. }
  192. /**
  193. * Tests that name will be selected as a displayField
  194. *
  195. * @return void
  196. */
  197. public function testDisplayFieldName()
  198. {
  199. $table = new Table([
  200. 'table' => 'users',
  201. 'schema' => [
  202. 'foo' => ['type' => 'string'],
  203. 'name' => ['type' => 'string']
  204. ]
  205. ]);
  206. $this->assertEquals('name', $table->displayField());
  207. }
  208. /**
  209. * Tests that title will be selected as a displayField
  210. *
  211. * @return void
  212. */
  213. public function testDisplayFieldTitle()
  214. {
  215. $table = new Table([
  216. 'table' => 'users',
  217. 'schema' => [
  218. 'foo' => ['type' => 'string'],
  219. 'title' => ['type' => 'string']
  220. ]
  221. ]);
  222. $this->assertEquals('title', $table->displayField());
  223. }
  224. /**
  225. * Tests that no displayField will fallback to primary key
  226. *
  227. * @return void
  228. */
  229. public function testDisplayFallback()
  230. {
  231. $table = new Table([
  232. 'table' => 'users',
  233. 'schema' => [
  234. 'id' => ['type' => 'string'],
  235. 'foo' => ['type' => 'string'],
  236. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  237. ]
  238. ]);
  239. $this->assertEquals('id', $table->displayField());
  240. }
  241. /**
  242. * Tests that displayField can be changed
  243. *
  244. * @return void
  245. */
  246. public function testDisplaySet()
  247. {
  248. $table = new Table([
  249. 'table' => 'users',
  250. 'schema' => [
  251. 'id' => ['type' => 'string'],
  252. 'foo' => ['type' => 'string'],
  253. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
  254. ]
  255. ]);
  256. $this->assertEquals('id', $table->displayField());
  257. $table->displayField('foo');
  258. $this->assertEquals('foo', $table->displayField());
  259. }
  260. /**
  261. * Tests schema method
  262. *
  263. * @return void
  264. */
  265. public function testSchema()
  266. {
  267. $schema = $this->connection->schemaCollection()->describe('users');
  268. $table = new Table([
  269. 'table' => 'users',
  270. 'connection' => $this->connection,
  271. ]);
  272. $this->assertEquals($schema, $table->schema());
  273. $table = new Table(['table' => 'stuff']);
  274. $table->schema($schema);
  275. $this->assertSame($schema, $table->schema());
  276. $table = new Table(['table' => 'another']);
  277. $schema = ['id' => ['type' => 'integer']];
  278. $table->schema($schema);
  279. $this->assertEquals(
  280. new \Cake\Database\Schema\Table('another', $schema),
  281. $table->schema()
  282. );
  283. }
  284. /**
  285. * Tests that _initializeSchema can be used to alter the database schema
  286. *
  287. * @return void
  288. */
  289. public function testSchemaInitialize()
  290. {
  291. $schema = $this->connection->schemaCollection()->describe('users');
  292. $table = $this->getMock('Cake\ORM\Table', ['_initializeSchema'], [
  293. ['table' => 'users', 'connection' => $this->connection]
  294. ]);
  295. $table->expects($this->once())
  296. ->method('_initializeSchema')
  297. ->with($schema)
  298. ->will($this->returnCallback(function ($schema) {
  299. $schema->columnType('username', 'integer');
  300. return $schema;
  301. }));
  302. $result = $table->schema();
  303. $schema->columnType('username', 'integer');
  304. $this->assertEquals($schema, $result);
  305. $this->assertEquals($schema, $table->schema(), '_initializeSchema should be called once');
  306. }
  307. /**
  308. * Tests that all fields for a table are added by default in a find when no
  309. * other fields are specified
  310. *
  311. * @return void
  312. */
  313. public function testFindAllNoFieldsAndNoHydration()
  314. {
  315. $table = new Table([
  316. 'table' => 'users',
  317. 'connection' => $this->connection,
  318. ]);
  319. $results = $table
  320. ->find('all')
  321. ->where(['id IN' => [1, 2]])
  322. ->order('id')
  323. ->hydrate(false)
  324. ->toArray();
  325. $expected = [
  326. [
  327. 'id' => 1,
  328. 'username' => 'mariano',
  329. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  330. 'created' => new Time('2007-03-17 01:16:23'),
  331. 'updated' => new Time('2007-03-17 01:18:31'),
  332. ],
  333. [
  334. 'id' => 2,
  335. 'username' => 'nate',
  336. 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO',
  337. 'created' => new Time('2008-03-17 01:18:23'),
  338. 'updated' => new Time('2008-03-17 01:20:31'),
  339. ],
  340. ];
  341. $this->assertEquals($expected, $results);
  342. }
  343. /**
  344. * Tests that it is possible to select only a few fields when finding over a table
  345. *
  346. * @return void
  347. */
  348. public function testFindAllSomeFieldsNoHydration()
  349. {
  350. $table = new Table([
  351. 'table' => 'users',
  352. 'connection' => $this->connection,
  353. ]);
  354. $results = $table->find('all')
  355. ->select(['username', 'password'])
  356. ->hydrate(false)
  357. ->order('username')->toArray();
  358. $expected = [
  359. ['username' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  360. ['username' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  361. ['username' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  362. ['username' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  363. ];
  364. $this->assertSame($expected, $results);
  365. $results = $table->find('all')
  366. ->select(['foo' => 'username', 'password'])
  367. ->order('username')
  368. ->hydrate(false)
  369. ->toArray();
  370. $expected = [
  371. ['foo' => 'garrett', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  372. ['foo' => 'larry', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  373. ['foo' => 'mariano', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  374. ['foo' => 'nate', 'password' => '$2a$10$u05j8FjsvLBNdfhBhc21LOuVMpzpabVXQ9OpC2wO3pSO0q6t7HHMO'],
  375. ];
  376. $this->assertSame($expected, $results);
  377. }
  378. /**
  379. * Tests that the query will automatically casts complex conditions to the correct
  380. * types when the columns belong to the default table
  381. *
  382. * @return void
  383. */
  384. public function testFindAllConditionAutoTypes()
  385. {
  386. $table = new Table([
  387. 'table' => 'users',
  388. 'connection' => $this->connection,
  389. ]);
  390. $query = $table->find('all')
  391. ->select(['id', 'username'])
  392. ->where(['created >=' => new Time('2010-01-22 00:00')])
  393. ->hydrate(false)
  394. ->order('id');
  395. $expected = [
  396. ['id' => 3, 'username' => 'larry'],
  397. ['id' => 4, 'username' => 'garrett']
  398. ];
  399. $this->assertSame($expected, $query->toArray());
  400. $query->orWhere(['users.created' => new Time('2008-03-17 01:18:23')]);
  401. $expected = [
  402. ['id' => 2, 'username' => 'nate'],
  403. ['id' => 3, 'username' => 'larry'],
  404. ['id' => 4, 'username' => 'garrett']
  405. ];
  406. $this->assertSame($expected, $query->toArray());
  407. }
  408. /**
  409. * Test that beforeFind events can mutate the query.
  410. *
  411. * @return void
  412. */
  413. public function testFindBeforeFindEventMutateQuery()
  414. {
  415. $table = new Table([
  416. 'table' => 'users',
  417. 'connection' => $this->connection,
  418. ]);
  419. $table->eventManager()->on(
  420. 'Model.beforeFind',
  421. function ($event, $query, $options) {
  422. $query->limit(1);
  423. }
  424. );
  425. $result = $table->find('all')->all();
  426. $this->assertCount(1, $result, 'Should only have 1 record, limit 1 applied.');
  427. }
  428. /**
  429. * Test that beforeFind events are fired and can stop the find and
  430. * return custom results.
  431. *
  432. * @return void
  433. */
  434. public function testFindBeforeFindEventOverrideReturn()
  435. {
  436. $table = new Table([
  437. 'table' => 'users',
  438. 'connection' => $this->connection,
  439. ]);
  440. $expected = ['One', 'Two', 'Three'];
  441. $table->eventManager()->on(
  442. 'Model.beforeFind',
  443. function ($event, $query, $options) use ($expected) {
  444. $query->setResult($expected);
  445. $event->stopPropagation();
  446. }
  447. );
  448. $query = $table->find('all');
  449. $query->limit(1);
  450. $this->assertEquals($expected, $query->all()->toArray());
  451. }
  452. /**
  453. * Tests that belongsTo() creates and configures correctly the association
  454. *
  455. * @return void
  456. */
  457. public function testBelongsTo()
  458. {
  459. $options = ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']];
  460. $table = new Table(['table' => 'dates']);
  461. $belongsTo = $table->belongsTo('user', $options);
  462. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  463. $this->assertSame($belongsTo, $table->association('user'));
  464. $this->assertEquals('user', $belongsTo->name());
  465. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  466. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  467. $this->assertSame($table, $belongsTo->source());
  468. }
  469. /**
  470. * Tests that hasOne() creates and configures correctly the association
  471. *
  472. * @return void
  473. */
  474. public function testHasOne()
  475. {
  476. $options = ['foreignKey' => 'user_id', 'conditions' => ['b' => 'c']];
  477. $table = new Table(['table' => 'users']);
  478. $hasOne = $table->hasOne('profile', $options);
  479. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  480. $this->assertSame($hasOne, $table->association('profile'));
  481. $this->assertEquals('profile', $hasOne->name());
  482. $this->assertEquals('user_id', $hasOne->foreignKey());
  483. $this->assertEquals(['b' => 'c'], $hasOne->conditions());
  484. $this->assertSame($table, $hasOne->source());
  485. }
  486. /**
  487. * Test has one with a plugin model
  488. *
  489. * @return void
  490. */
  491. public function testHasOnePlugin()
  492. {
  493. $options = ['className' => 'TestPlugin.Comments'];
  494. $table = new Table(['table' => 'users']);
  495. $hasOne = $table->hasOne('Comments', $options);
  496. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  497. $this->assertSame('Comments', $hasOne->name());
  498. $hasOneTable = $hasOne->target();
  499. $this->assertSame('Comments', $hasOne->alias());
  500. $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias());
  501. $options = ['className' => 'TestPlugin.Comments'];
  502. $table = new Table(['table' => 'users']);
  503. $hasOne = $table->hasOne('TestPlugin.Comments', $options);
  504. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  505. $this->assertSame('Comments', $hasOne->name());
  506. $hasOneTable = $hasOne->target();
  507. $this->assertSame('Comments', $hasOne->alias());
  508. $this->assertSame('TestPlugin.Comments', $hasOne->registryAlias());
  509. }
  510. /**
  511. * testNoneUniqueAssociationsSameClass
  512. *
  513. * @return void
  514. */
  515. public function testNoneUniqueAssociationsSameClass()
  516. {
  517. $Users = new Table(['table' => 'users']);
  518. $options = ['className' => 'Comments'];
  519. $Users->hasMany('Comments', $options);
  520. $Articles = new Table(['table' => 'articles']);
  521. $options = ['className' => 'Comments'];
  522. $Articles->hasMany('Comments', $options);
  523. $Categories = new Table(['table' => 'categories']);
  524. $options = ['className' => 'TestPlugin.Comments'];
  525. $Categories->hasMany('Comments', $options);
  526. $this->assertInstanceOf('Cake\ORM\Table', $Users->Comments->target());
  527. $this->assertInstanceOf('Cake\ORM\Table', $Articles->Comments->target());
  528. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $Categories->Comments->target());
  529. }
  530. /**
  531. * Test associations which refer to the same table multiple times
  532. *
  533. * @return void
  534. */
  535. public function testSelfJoinAssociations()
  536. {
  537. $Categories = TableRegistry::get('Categories');
  538. $options = ['className' => 'Categories'];
  539. $Categories->hasMany('Children', ['foreignKey' => 'parent_id'] + $options);
  540. $Categories->belongsTo('Parent', $options);
  541. $this->assertSame('categories', $Categories->Children->target()->table());
  542. $this->assertSame('categories', $Categories->Parent->target()->table());
  543. $this->assertSame('Children', $Categories->Children->alias());
  544. $this->assertSame('Children', $Categories->Children->target()->alias());
  545. $this->assertSame('Parent', $Categories->Parent->alias());
  546. $this->assertSame('Parent', $Categories->Parent->target()->alias());
  547. $expected = [
  548. 'id' => 2,
  549. 'parent_id' => 1,
  550. 'name' => 'Category 1.1',
  551. 'parent' => [
  552. 'id' => 1,
  553. 'parent_id' => 0,
  554. 'name' => 'Category 1',
  555. ],
  556. 'children' => [
  557. [
  558. 'id' => 7,
  559. 'parent_id' => 2,
  560. 'name' => 'Category 1.1.1',
  561. ],
  562. [
  563. 'id' => 8,
  564. 'parent_id' => 2,
  565. 'name' => 'Category 1.1.2',
  566. ]
  567. ]
  568. ];
  569. $fields = ['id', 'parent_id', 'name'];
  570. $result = $Categories->find('all')
  571. ->select(['Categories.id', 'Categories.parent_id', 'Categories.name'])
  572. ->contain(['Children' => ['fields' => $fields], 'Parent' => ['fields' => $fields]])
  573. ->where(['Categories.id' => 2])
  574. ->first()
  575. ->toArray();
  576. $this->assertSame($expected, $result);
  577. }
  578. /**
  579. * Tests that hasMany() creates and configures correctly the association
  580. *
  581. * @return void
  582. */
  583. public function testHasMany()
  584. {
  585. $options = [
  586. 'foreignKey' => 'author_id',
  587. 'conditions' => ['b' => 'c'],
  588. 'sort' => ['foo' => 'asc']
  589. ];
  590. $table = new Table(['table' => 'authors']);
  591. $hasMany = $table->hasMany('article', $options);
  592. $this->assertInstanceOf('Cake\ORM\Association\HasMany', $hasMany);
  593. $this->assertSame($hasMany, $table->association('article'));
  594. $this->assertEquals('article', $hasMany->name());
  595. $this->assertEquals('author_id', $hasMany->foreignKey());
  596. $this->assertEquals(['b' => 'c'], $hasMany->conditions());
  597. $this->assertEquals(['foo' => 'asc'], $hasMany->sort());
  598. $this->assertSame($table, $hasMany->source());
  599. }
  600. /**
  601. * testHasManyWithClassName
  602. *
  603. * @return void
  604. */
  605. public function testHasManyWithClassName()
  606. {
  607. $table = TableRegistry::get('Articles');
  608. $table->hasMany('Comments', [
  609. 'className' => 'Comments',
  610. 'conditions' => ['published' => 'Y'],
  611. ]);
  612. $table->hasMany('UnapprovedComments', [
  613. 'className' => 'Comments',
  614. 'conditions' => ['published' => 'N'],
  615. 'propertyName' => 'unaproved_comments'
  616. ]);
  617. $expected = [
  618. 'id' => 1,
  619. 'title' => 'First Article',
  620. 'unaproved_comments' => [
  621. [
  622. 'id' => 4,
  623. 'article_id' => 1,
  624. 'comment' => 'Fourth Comment for First Article'
  625. ]
  626. ],
  627. 'comments' => [
  628. [
  629. 'id' => 1,
  630. 'article_id' => 1,
  631. 'comment' => 'First Comment for First Article'
  632. ],
  633. [
  634. 'id' => 2,
  635. 'article_id' => 1,
  636. 'comment' => 'Second Comment for First Article'
  637. ],
  638. [
  639. 'id' => 3,
  640. 'article_id' => 1,
  641. 'comment' => 'Third Comment for First Article'
  642. ]
  643. ]
  644. ];
  645. $result = $table->find()
  646. ->select(['id', 'title'])
  647. ->contain([
  648. 'Comments' => ['fields' => ['id', 'article_id', 'comment']],
  649. 'UnapprovedComments' => ['fields' => ['id', 'article_id', 'comment']]
  650. ])
  651. ->where(['id' => 1])
  652. ->first();
  653. $this->assertSame($expected, $result->toArray());
  654. }
  655. /**
  656. * Ensure associations use the plugin-prefixed model
  657. *
  658. * @return void
  659. */
  660. public function testHasManyPluginOverlap()
  661. {
  662. TableRegistry::get('Comments');
  663. Plugin::load('TestPlugin');
  664. $table = new Table(['table' => 'authors']);
  665. $table->hasMany('TestPlugin.Comments');
  666. $comments = $table->Comments->target();
  667. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  668. }
  669. /**
  670. * Ensure associations use the plugin-prefixed model
  671. * even if specified with config
  672. *
  673. * @return void
  674. */
  675. public function testHasManyPluginOverlapConfig()
  676. {
  677. TableRegistry::get('Comments');
  678. Plugin::load('TestPlugin');
  679. $table = new Table(['table' => 'authors']);
  680. $table->hasMany('Comments', ['className' => 'TestPlugin.Comments']);
  681. $comments = $table->Comments->target();
  682. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $comments);
  683. }
  684. /**
  685. * Tests that BelongsToMany() creates and configures correctly the association
  686. *
  687. * @return void
  688. */
  689. public function testBelongsToMany()
  690. {
  691. $options = [
  692. 'foreignKey' => 'thing_id',
  693. 'joinTable' => 'things_tags',
  694. 'conditions' => ['b' => 'c'],
  695. 'sort' => ['foo' => 'asc']
  696. ];
  697. $table = new Table(['table' => 'authors', 'connection' => $this->connection]);
  698. $belongsToMany = $table->belongsToMany('tag', $options);
  699. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  700. $this->assertSame($belongsToMany, $table->association('tag'));
  701. $this->assertEquals('tag', $belongsToMany->name());
  702. $this->assertEquals('thing_id', $belongsToMany->foreignKey());
  703. $this->assertEquals(['b' => 'c'], $belongsToMany->conditions());
  704. $this->assertEquals(['foo' => 'asc'], $belongsToMany->sort());
  705. $this->assertSame($table, $belongsToMany->source());
  706. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  707. }
  708. /**
  709. * Test addAssociations()
  710. *
  711. * @return void
  712. */
  713. public function testAddAssociations()
  714. {
  715. $params = [
  716. 'belongsTo' => [
  717. 'users' => ['foreignKey' => 'fake_id', 'conditions' => ['a' => 'b']]
  718. ],
  719. 'hasOne' => ['profiles'],
  720. 'hasMany' => ['authors'],
  721. 'belongsToMany' => [
  722. 'tags' => ['joinTable' => 'things_tags']
  723. ]
  724. ];
  725. $table = new Table(['table' => 'dates']);
  726. $table->addAssociations($params);
  727. $associations = $table->associations();
  728. $belongsTo = $associations->get('users');
  729. $this->assertInstanceOf('Cake\ORM\Association\BelongsTo', $belongsTo);
  730. $this->assertEquals('users', $belongsTo->name());
  731. $this->assertEquals('fake_id', $belongsTo->foreignKey());
  732. $this->assertEquals(['a' => 'b'], $belongsTo->conditions());
  733. $this->assertSame($table, $belongsTo->source());
  734. $hasOne = $associations->get('profiles');
  735. $this->assertInstanceOf('Cake\ORM\Association\HasOne', $hasOne);
  736. $this->assertEquals('profiles', $hasOne->name());
  737. $hasMany = $associations->get('authors');
  738. $this->assertInstanceOf('Cake\ORM\Association\hasMany', $hasMany);
  739. $this->assertEquals('authors', $hasMany->name());
  740. $belongsToMany = $associations->get('tags');
  741. $this->assertInstanceOf('Cake\ORM\Association\BelongsToMany', $belongsToMany);
  742. $this->assertEquals('tags', $belongsToMany->name());
  743. $this->assertSame('things_tags', $belongsToMany->junction()->table());
  744. }
  745. /**
  746. * Test basic multi row updates.
  747. *
  748. * @return void
  749. */
  750. public function testUpdateAll()
  751. {
  752. $table = new Table([
  753. 'table' => 'users',
  754. 'connection' => $this->connection,
  755. ]);
  756. $fields = ['username' => 'mark'];
  757. $result = $table->updateAll($fields, ['id <' => 4]);
  758. $this->assertSame(3, $result);
  759. $result = $table->find('all')
  760. ->select(['username'])
  761. ->order(['id' => 'asc'])
  762. ->hydrate(false)
  763. ->toArray();
  764. $expected = array_fill(0, 3, $fields);
  765. $expected[] = ['username' => 'garrett'];
  766. $this->assertEquals($expected, $result);
  767. }
  768. /**
  769. * Test that exceptions from the Query bubble up.
  770. *
  771. * @expectedException \Cake\Database\Exception
  772. */
  773. public function testUpdateAllFailure()
  774. {
  775. $table = $this->getMock(
  776. 'Cake\ORM\Table',
  777. ['query'],
  778. [['table' => 'users', 'connection' => $this->connection]]
  779. );
  780. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  781. $table->expects($this->once())
  782. ->method('query')
  783. ->will($this->returnValue($query));
  784. $query->expects($this->once())
  785. ->method('execute')
  786. ->will($this->throwException(new Exception('Not good')));
  787. $table->updateAll(['username' => 'mark'], []);
  788. }
  789. /**
  790. * Test deleting many records.
  791. *
  792. * @return void
  793. */
  794. public function testDeleteAll()
  795. {
  796. $table = new Table([
  797. 'table' => 'users',
  798. 'connection' => $this->connection,
  799. ]);
  800. $result = $table->deleteAll(['id <' => 4]);
  801. $this->assertSame(3, $result);
  802. $result = $table->find('all')->toArray();
  803. $this->assertCount(1, $result, 'Only one record should remain');
  804. $this->assertEquals(4, $result[0]['id']);
  805. }
  806. /**
  807. * Test deleting many records with conditions using the alias
  808. *
  809. * @return void
  810. */
  811. public function testDeleteAllAliasedConditions()
  812. {
  813. $table = new Table([
  814. 'table' => 'users',
  815. 'alias' => 'Managers',
  816. 'connection' => $this->connection,
  817. ]);
  818. $result = $table->deleteAll(['Managers.id <' => 4]);
  819. $this->assertSame(3, $result);
  820. $result = $table->find('all')->toArray();
  821. $this->assertCount(1, $result, 'Only one record should remain');
  822. $this->assertEquals(4, $result[0]['id']);
  823. }
  824. /**
  825. * Test that exceptions from the Query bubble up.
  826. *
  827. * @expectedException \Cake\Database\Exception
  828. */
  829. public function testDeleteAllFailure()
  830. {
  831. $table = $this->getMock(
  832. 'Cake\ORM\Table',
  833. ['query'],
  834. [['table' => 'users', 'connection' => $this->connection]]
  835. );
  836. $query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection, $table]);
  837. $table->expects($this->once())
  838. ->method('query')
  839. ->will($this->returnValue($query));
  840. $query->expects($this->once())
  841. ->method('execute')
  842. ->will($this->throwException(new Exception('Not good')));
  843. $table->deleteAll(['id >' => 4]);
  844. }
  845. /**
  846. * Tests that array options are passed to the query object using applyOptions
  847. *
  848. * @return void
  849. */
  850. public function testFindApplyOptions()
  851. {
  852. $table = $this->getMock(
  853. 'Cake\ORM\Table',
  854. ['query', 'findAll'],
  855. [['table' => 'users', 'connection' => $this->connection]]
  856. );
  857. $query = $this->getMock('Cake\ORM\Query', [], [$this->connection, $table]);
  858. $table->expects($this->once())
  859. ->method('query')
  860. ->will($this->returnValue($query));
  861. $options = ['fields' => ['a', 'b'], 'connections' => ['a >' => 1]];
  862. $query->expects($this->any())
  863. ->method('select')
  864. ->will($this->returnSelf());
  865. $query->expects($this->once())->method('getOptions')
  866. ->will($this->returnValue(['connections' => ['a >' => 1]]));
  867. $query->expects($this->once())
  868. ->method('applyOptions')
  869. ->with($options);
  870. $table->expects($this->once())->method('findAll')
  871. ->with($query, ['connections' => ['a >' => 1]]);
  872. $table->find('all', $options);
  873. }
  874. /**
  875. * Tests find('list')
  876. *
  877. * @return void
  878. */
  879. public function testFindListNoHydration()
  880. {
  881. $table = new Table([
  882. 'table' => 'users',
  883. 'connection' => $this->connection,
  884. ]);
  885. $table->displayField('username');
  886. $query = $table->find('list')
  887. ->hydrate(false)
  888. ->order('id');
  889. $expected = [
  890. 1 => 'mariano',
  891. 2 => 'nate',
  892. 3 => 'larry',
  893. 4 => 'garrett'
  894. ];
  895. $this->assertSame($expected, $query->toArray());
  896. $query = $table->find('list', ['fields' => ['id', 'username']])
  897. ->hydrate(false)
  898. ->order('id');
  899. $expected = [
  900. 1 => 'mariano',
  901. 2 => 'nate',
  902. 3 => 'larry',
  903. 4 => 'garrett'
  904. ];
  905. $this->assertSame($expected, $query->toArray());
  906. $query = $table->find('list', ['groupField' => 'odd'])
  907. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  908. ->hydrate(false)
  909. ->order('id');
  910. $expected = [
  911. 1 => [
  912. 1 => 'mariano',
  913. 3 => 'larry'
  914. ],
  915. 0 => [
  916. 2 => 'nate',
  917. 4 => 'garrett'
  918. ]
  919. ];
  920. $this->assertSame($expected, $query->toArray());
  921. }
  922. /**
  923. * Tests find('threaded')
  924. *
  925. * @return void
  926. */
  927. public function testFindThreadedNoHydration()
  928. {
  929. $table = new Table([
  930. 'table' => 'categories',
  931. 'connection' => $this->connection,
  932. ]);
  933. $expected = [
  934. [
  935. 'id' => 1,
  936. 'parent_id' => 0,
  937. 'name' => 'Category 1',
  938. 'children' => [
  939. [
  940. 'id' => 2,
  941. 'parent_id' => 1,
  942. 'name' => 'Category 1.1',
  943. 'children' => [
  944. [
  945. 'id' => 7,
  946. 'parent_id' => 2,
  947. 'name' => 'Category 1.1.1',
  948. 'children' => []
  949. ],
  950. [
  951. 'id' => 8,
  952. 'parent_id' => '2',
  953. 'name' => 'Category 1.1.2',
  954. 'children' => []
  955. ]
  956. ],
  957. ],
  958. [
  959. 'id' => 3,
  960. 'parent_id' => '1',
  961. 'name' => 'Category 1.2',
  962. 'children' => []
  963. ],
  964. ]
  965. ],
  966. [
  967. 'id' => 4,
  968. 'parent_id' => 0,
  969. 'name' => 'Category 2',
  970. 'children' => []
  971. ],
  972. [
  973. 'id' => 5,
  974. 'parent_id' => 0,
  975. 'name' => 'Category 3',
  976. 'children' => [
  977. [
  978. 'id' => '6',
  979. 'parent_id' => '5',
  980. 'name' => 'Category 3.1',
  981. 'children' => []
  982. ]
  983. ]
  984. ]
  985. ];
  986. $results = $table->find('all')
  987. ->select(['id', 'parent_id', 'name'])
  988. ->hydrate(false)
  989. ->find('threaded')
  990. ->toArray();
  991. $this->assertEquals($expected, $results);
  992. }
  993. /**
  994. * Tests that finders can be stacked
  995. *
  996. * @return void
  997. */
  998. public function testStackingFinders()
  999. {
  1000. $table = $this->getMock('\Cake\ORM\Table', ['find', 'findList'], [], '', false);
  1001. $params = [$this->connection, $table];
  1002. $query = $this->getMock('\Cake\ORM\Query', ['addDefaultTypes'], $params);
  1003. $table->expects($this->once())
  1004. ->method('find')
  1005. ->with('threaded', ['order' => ['name' => 'ASC']])
  1006. ->will($this->returnValue($query));
  1007. $table->expects($this->once())
  1008. ->method('findList')
  1009. ->with($query, ['keyPath' => 'id'])
  1010. ->will($this->returnValue($query));
  1011. $result = $table
  1012. ->find('threaded', ['order' => ['name' => 'ASC']])
  1013. ->find('list', ['keyPath' => 'id']);
  1014. $this->assertSame($query, $result);
  1015. }
  1016. /**
  1017. * Tests find('threaded') with hydrated results
  1018. *
  1019. * @return void
  1020. */
  1021. public function testFindThreadedHydrated()
  1022. {
  1023. $table = new Table([
  1024. 'table' => 'categories',
  1025. 'connection' => $this->connection,
  1026. ]);
  1027. $results = $table->find('all')
  1028. ->find('threaded')
  1029. ->select(['id', 'parent_id', 'name'])
  1030. ->toArray();
  1031. $this->assertEquals(1, $results[0]->id);
  1032. $expected = [
  1033. 'id' => 8,
  1034. 'parent_id' => 2,
  1035. 'name' => 'Category 1.1.2',
  1036. 'children' => []
  1037. ];
  1038. $this->assertEquals($expected, $results[0]->children[0]->children[1]->toArray());
  1039. }
  1040. /**
  1041. * Tests find('list') with hydrated records
  1042. *
  1043. * @return void
  1044. */
  1045. public function testFindListHydrated()
  1046. {
  1047. $table = new Table([
  1048. 'table' => 'users',
  1049. 'connection' => $this->connection,
  1050. ]);
  1051. $table->displayField('username');
  1052. $query = $table
  1053. ->find('list', ['fields' => ['id', 'username']])
  1054. ->order('id');
  1055. $expected = [
  1056. 1 => 'mariano',
  1057. 2 => 'nate',
  1058. 3 => 'larry',
  1059. 4 => 'garrett'
  1060. ];
  1061. $this->assertSame($expected, $query->toArray());
  1062. $query = $table->find('list', ['groupField' => 'odd'])
  1063. ->select(['id', 'username', 'odd' => new QueryExpression('id % 2')])
  1064. ->hydrate(true)
  1065. ->order('id');
  1066. $expected = [
  1067. 1 => [
  1068. 1 => 'mariano',
  1069. 3 => 'larry'
  1070. ],
  1071. 0 => [
  1072. 2 => 'nate',
  1073. 4 => 'garrett'
  1074. ]
  1075. ];
  1076. $this->assertSame($expected, $query->toArray());
  1077. }
  1078. /**
  1079. * Test that find('list') only selects required fields.
  1080. *
  1081. * @return void
  1082. */
  1083. public function testFindListSelectedFields()
  1084. {
  1085. $table = new Table([
  1086. 'table' => 'users',
  1087. 'connection' => $this->connection,
  1088. ]);
  1089. $table->displayField('username');
  1090. $query = $table->find('list');
  1091. $expected = ['id', 'username'];
  1092. $this->assertSame($expected, $query->clause('select'));
  1093. $query = $table->find('list', ['valueField' => function ($row) {
  1094. return $row->username;
  1095. }]);
  1096. $this->assertEmpty($query->clause('select'));
  1097. $expected = ['odd' => new QueryExpression('id % 2'), 'id', 'username'];
  1098. $query = $table->find('list', [
  1099. 'fields' => $expected,
  1100. 'groupField' => 'odd',
  1101. ]);
  1102. $this->assertSame($expected, $query->clause('select'));
  1103. $articles = new Table([
  1104. 'table' => 'articles',
  1105. 'connection' => $this->connection,
  1106. ]);
  1107. $query = $articles->find('list', ['groupField' => 'author_id']);
  1108. $expected = ['id', 'title', 'author_id'];
  1109. $this->assertSame($expected, $query->clause('select'));
  1110. $query = $articles->find('list', ['valueField' => ['author_id', 'title']])
  1111. ->order('id');
  1112. $expected = ['id', 'author_id', 'title'];
  1113. $this->assertSame($expected, $query->clause('select'));
  1114. $expected = [
  1115. 1 => '1;First Article',
  1116. 2 => '3;Second Article',
  1117. 3 => '1;Third Article',
  1118. ];
  1119. $this->assertSame($expected, $query->toArray());
  1120. }
  1121. /**
  1122. * test that find('list') does not auto add fields to select if using virtual properties
  1123. *
  1124. * @return void
  1125. */
  1126. public function testFindListWithVirtualField()
  1127. {
  1128. $table = new Table([
  1129. 'table' => 'users',
  1130. 'connection' => $this->connection,
  1131. 'entityClass' => '\TestApp\Model\Entity\VirtualUser'
  1132. ]);
  1133. $table->displayField('bonus');
  1134. $query = $table
  1135. ->find('list')
  1136. ->order('id');
  1137. $this->assertEmpty($query->clause('select'));
  1138. $expected = [
  1139. 1 => 'bonus',
  1140. 2 => 'bonus',
  1141. 3 => 'bonus',
  1142. 4 => 'bonus'
  1143. ];
  1144. $this->assertSame($expected, $query->toArray());
  1145. $query = $table->find('list', ['groupField' => 'odd']);
  1146. $this->assertEmpty($query->clause('select'));
  1147. }
  1148. /**
  1149. * Test find('list') with value field from associated table
  1150. *
  1151. * @return void
  1152. */
  1153. public function testFindListWithAssociatedTable()
  1154. {
  1155. $articles = new Table([
  1156. 'table' => 'articles',
  1157. 'connection' => $this->connection,
  1158. ]);
  1159. $articles->belongsTo('Authors');
  1160. $query = $articles->find('list', ['valueField' => 'author.name'])
  1161. ->contain(['Authors'])
  1162. ->order('articles.id');
  1163. $this->assertEmpty($query->clause('select'));
  1164. $expected = [
  1165. 1 => 'mariano',
  1166. 2 => 'larry',
  1167. 3 => 'mariano',
  1168. ];
  1169. $this->assertSame($expected, $query->toArray());
  1170. }
  1171. /**
  1172. * Test the default entityClass.
  1173. *
  1174. * @return void
  1175. */
  1176. public function testEntityClassDefault()
  1177. {
  1178. $table = new Table();
  1179. $this->assertEquals('\Cake\ORM\Entity', $table->entityClass());
  1180. }
  1181. /**
  1182. * Tests that using a simple string for entityClass will try to
  1183. * load the class from the App namespace
  1184. *
  1185. * @return void
  1186. */
  1187. public function testTableClassInApp()
  1188. {
  1189. $class = $this->getMockClass('\Cake\ORM\Entity');
  1190. if (!class_exists('TestApp\Model\Entity\TestUser')) {
  1191. class_alias($class, 'TestApp\Model\Entity\TestUser');
  1192. }
  1193. $table = new Table();
  1194. $this->assertEquals('TestApp\Model\Entity\TestUser', $table->entityClass('TestUser'));
  1195. }
  1196. /**
  1197. * Tests that using a simple string for entityClass will try to
  1198. * load the class from the Plugin namespace when using plugin notation
  1199. *
  1200. * @return void
  1201. */
  1202. public function testTableClassInPlugin()
  1203. {
  1204. $class = $this->getMockClass('\Cake\ORM\Entity');
  1205. if (!class_exists('MyPlugin\Model\Entity\SuperUser')) {
  1206. class_alias($class, 'MyPlugin\Model\Entity\SuperUser');
  1207. }
  1208. $table = new Table();
  1209. $this->assertEquals(
  1210. 'MyPlugin\Model\Entity\SuperUser',
  1211. $table->entityClass('MyPlugin.SuperUser')
  1212. );
  1213. }
  1214. /**
  1215. * Tests that using a simple string for entityClass will throw an exception
  1216. * when the class does not exist in the namespace
  1217. *
  1218. * @expectedException \Cake\ORM\Exception\MissingEntityException
  1219. * @expectedExceptionMessage Entity class FooUser could not be found.
  1220. * @return void
  1221. */
  1222. public function testTableClassNonExisting()
  1223. {
  1224. $table = new Table;
  1225. $this->assertFalse($table->entityClass('FooUser'));
  1226. }
  1227. /**
  1228. * Tests getting the entityClass based on conventions for the entity
  1229. * namespace
  1230. *
  1231. * @return void
  1232. */
  1233. public function testTableClassConventionForAPP()
  1234. {
  1235. $table = new \TestApp\Model\Table\ArticlesTable;
  1236. $this->assertEquals('TestApp\Model\Entity\Article', $table->entityClass());
  1237. }
  1238. /**
  1239. * Tests setting a entity class object using the setter method
  1240. *
  1241. * @return void
  1242. */
  1243. public function testSetEntityClass()
  1244. {
  1245. $table = new Table;
  1246. $class = '\\' . $this->getMockClass('\Cake\ORM\Entity');
  1247. $table->entityClass($class);
  1248. $this->assertEquals($class, $table->entityClass());
  1249. }
  1250. /**
  1251. * Proves that associations, even though they are lazy loaded, will fetch
  1252. * records using the correct table class and hydrate with the correct entity
  1253. *
  1254. * @return void
  1255. */
  1256. public function testReciprocalBelongsToLoading()
  1257. {
  1258. $table = new \TestApp\Model\Table\ArticlesTable([
  1259. 'connection' => $this->connection,
  1260. ]);
  1261. $result = $table->find('all')->contain(['authors'])->first();
  1262. $this->assertInstanceOf('TestApp\Model\Entity\Author', $result->author);
  1263. }
  1264. /**
  1265. * Proves that associations, even though they are lazy loaded, will fetch
  1266. * records using the correct table class and hydrate with the correct entity
  1267. *
  1268. * @return void
  1269. */
  1270. public function testReciprocalHasManyLoading()
  1271. {
  1272. $table = new \TestApp\Model\Table\ArticlesTable([
  1273. 'connection' => $this->connection,
  1274. ]);
  1275. $result = $table->find('all')->contain(['authors' => ['articles']])->first();
  1276. $this->assertCount(2, $result->author->articles);
  1277. foreach ($result->author->articles as $article) {
  1278. $this->assertInstanceOf('TestApp\Model\Entity\Article', $article);
  1279. }
  1280. }
  1281. /**
  1282. * Tests that the correct table and entity are loaded for the join association in
  1283. * a belongsToMany setup
  1284. *
  1285. * @return void
  1286. */
  1287. public function testReciprocalBelongsToMany()
  1288. {
  1289. $table = new \TestApp\Model\Table\ArticlesTable([
  1290. 'connection' => $this->connection,
  1291. ]);
  1292. $result = $table->find('all')->contain(['tags'])->first();
  1293. $this->assertInstanceOf('TestApp\Model\Entity\Tag', $result->tags[0]);
  1294. $this->assertInstanceOf(
  1295. 'TestApp\Model\Entity\ArticlesTag',
  1296. $result->tags[0]->_joinData
  1297. );
  1298. }
  1299. /**
  1300. * Tests that recently fetched entities are always clean
  1301. *
  1302. * @return void
  1303. */
  1304. public function testFindCleanEntities()
  1305. {
  1306. $table = new \TestApp\Model\Table\ArticlesTable([
  1307. 'connection' => $this->connection,
  1308. ]);
  1309. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1310. $this->assertCount(3, $results);
  1311. foreach ($results as $article) {
  1312. $this->assertFalse($article->dirty('id'));
  1313. $this->assertFalse($article->dirty('title'));
  1314. $this->assertFalse($article->dirty('author_id'));
  1315. $this->assertFalse($article->dirty('body'));
  1316. $this->assertFalse($article->dirty('published'));
  1317. $this->assertFalse($article->dirty('author'));
  1318. $this->assertFalse($article->author->dirty('id'));
  1319. $this->assertFalse($article->author->dirty('name'));
  1320. $this->assertFalse($article->dirty('tag'));
  1321. if ($article->tag) {
  1322. $this->assertFalse($article->tag[0]->_joinData->dirty('tag_id'));
  1323. }
  1324. }
  1325. }
  1326. /**
  1327. * Tests that recently fetched entities are marked as not new
  1328. *
  1329. * @return void
  1330. */
  1331. public function testFindPersistedEntities()
  1332. {
  1333. $table = new \TestApp\Model\Table\ArticlesTable([
  1334. 'connection' => $this->connection,
  1335. ]);
  1336. $results = $table->find('all')->contain(['tags', 'authors'])->toArray();
  1337. $this->assertCount(3, $results);
  1338. foreach ($results as $article) {
  1339. $this->assertFalse($article->isNew());
  1340. foreach ((array)$article->tag as $tag) {
  1341. $this->assertFalse($tag->isNew());
  1342. $this->assertFalse($tag->_joinData->isNew());
  1343. }
  1344. }
  1345. }
  1346. /**
  1347. * Tests the exists function
  1348. *
  1349. * @return void
  1350. */
  1351. public function testExists()
  1352. {
  1353. $table = TableRegistry::get('users');
  1354. $this->assertTrue($table->exists(['id' => 1]));
  1355. $this->assertFalse($table->exists(['id' => 501]));
  1356. $this->assertTrue($table->exists(['id' => 3, 'username' => 'larry']));
  1357. }
  1358. /**
  1359. * Test adding a behavior to a table.
  1360. *
  1361. * @return void
  1362. */
  1363. public function testAddBehavior()
  1364. {
  1365. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1366. $mock->expects($this->once())
  1367. ->method('load')
  1368. ->with('Sluggable');
  1369. $table = new Table([
  1370. 'table' => 'articles',
  1371. 'behaviors' => $mock
  1372. ]);
  1373. $table->addBehavior('Sluggable');
  1374. }
  1375. /**
  1376. * Test adding a behavior that is a duplicate.
  1377. *
  1378. * @return void
  1379. */
  1380. public function testAddBehaviorDuplicate()
  1381. {
  1382. $table = new Table(['table' => 'articles']);
  1383. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1384. $this->assertNull($table->addBehavior('Sluggable', ['test' => 'value']));
  1385. try {
  1386. $table->addBehavior('Sluggable', ['thing' => 'thing']);
  1387. $this->fail('No exception raised');
  1388. } catch (\RuntimeException $e) {
  1389. $this->assertContains('The "Sluggable" alias has already been loaded', $e->getMessage());
  1390. }
  1391. }
  1392. /**
  1393. * Test removing a behavior from a table.
  1394. *
  1395. * @return void
  1396. */
  1397. public function testRemoveBehavior()
  1398. {
  1399. $mock = $this->getMock('Cake\ORM\BehaviorRegistry', [], [], '', false);
  1400. $mock->expects($this->once())
  1401. ->method('unload')
  1402. ->with('Sluggable');
  1403. $table = new Table([
  1404. 'table' => 'articles',
  1405. 'behaviors' => $mock
  1406. ]);
  1407. $table->removeBehavior('Sluggable');
  1408. }
  1409. /**
  1410. * Test getting a behavior instance from a table.
  1411. *
  1412. * @return void
  1413. */
  1414. public function testBehaviors()
  1415. {
  1416. $table = TableRegistry::get('article');
  1417. $result = $table->behaviors();
  1418. $this->assertInstanceOf('Cake\ORM\BehaviorRegistry', $result);
  1419. }
  1420. /**
  1421. * Ensure exceptions are raised on missing behaviors.
  1422. *
  1423. * @expectedException \Cake\ORM\Exception\MissingBehaviorException
  1424. */
  1425. public function testAddBehaviorMissing()
  1426. {
  1427. $table = TableRegistry::get('article');
  1428. $this->assertNull($table->addBehavior('NopeNotThere'));
  1429. }
  1430. /**
  1431. * Test mixin methods from behaviors.
  1432. *
  1433. * @return void
  1434. */
  1435. public function testCallBehaviorMethod()
  1436. {
  1437. $table = TableRegistry::get('article');
  1438. $table->addBehavior('Sluggable');
  1439. $this->assertEquals('some-value', $table->slugify('some value'));
  1440. }
  1441. /**
  1442. * Test you can alias a behavior method
  1443. *
  1444. * @return void
  1445. */
  1446. public function testCallBehaviorAliasedMethod()
  1447. {
  1448. $table = TableRegistry::get('article');
  1449. $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
  1450. $this->assertEquals('some-value', $table->wednesday('some value'));
  1451. }
  1452. /**
  1453. * Test finder methods from behaviors.
  1454. *
  1455. * @return void
  1456. */
  1457. public function testCallBehaviorFinder()
  1458. {
  1459. $table = TableRegistry::get('articles');
  1460. $table->addBehavior('Sluggable');
  1461. $query = $table->find('noSlug');
  1462. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1463. $this->assertNotEmpty($query->clause('where'));
  1464. }
  1465. /**
  1466. * testCallBehaviorAliasedFinder
  1467. *
  1468. * @return void
  1469. */
  1470. public function testCallBehaviorAliasedFinder()
  1471. {
  1472. $table = TableRegistry::get('articles');
  1473. $table->addBehavior('Sluggable', ['implementedFinders' => ['special' => 'findNoSlug']]);
  1474. $query = $table->find('special');
  1475. $this->assertInstanceOf('Cake\ORM\Query', $query);
  1476. $this->assertNotEmpty($query->clause('where'));
  1477. }
  1478. /**
  1479. * Test implementedEvents
  1480. *
  1481. * @return void
  1482. */
  1483. public function testImplementedEvents()
  1484. {
  1485. $table = $this->getMock(
  1486. 'Cake\ORM\Table',
  1487. ['beforeFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete']
  1488. );
  1489. $result = $table->implementedEvents();
  1490. $expected = [
  1491. 'Model.beforeFind' => 'beforeFind',
  1492. 'Model.beforeSave' => 'beforeSave',
  1493. 'Model.afterSave' => 'afterSave',
  1494. 'Model.beforeDelete' => 'beforeDelete',
  1495. 'Model.afterDelete' => 'afterDelete',
  1496. ];
  1497. $this->assertEquals($expected, $result, 'Events do not match.');
  1498. }
  1499. /**
  1500. * Tests that it is possible to insert a new row using the save method
  1501. *
  1502. * @group save
  1503. * @return void
  1504. */
  1505. public function testSaveNewEntity()
  1506. {
  1507. $entity = new \Cake\ORM\Entity([
  1508. 'username' => 'superuser',
  1509. 'password' => 'root',
  1510. 'created' => new Time('2013-10-10 00:00'),
  1511. 'updated' => new Time('2013-10-10 00:00')
  1512. ]);
  1513. $table = TableRegistry::get('users');
  1514. $this->assertSame($entity, $table->save($entity));
  1515. $this->assertEquals($entity->id, self::$nextUserId);
  1516. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1517. $this->assertEquals($entity->toArray(), $row->toArray());
  1518. }
  1519. /**
  1520. * Test that saving a new empty entity does nothing.
  1521. *
  1522. * @group save
  1523. * @return void
  1524. */
  1525. public function testSaveNewEmptyEntity()
  1526. {
  1527. $entity = new \Cake\ORM\Entity();
  1528. $table = TableRegistry::get('users');
  1529. $this->assertFalse($table->save($entity));
  1530. }
  1531. /**
  1532. * Test that saving a new empty entity does not call exists.
  1533. *
  1534. * @group save
  1535. * @return void
  1536. */
  1537. public function testSaveNewEntityNoExists()
  1538. {
  1539. $table = $this->getMock(
  1540. 'Cake\ORM\Table',
  1541. ['exists'],
  1542. [[
  1543. 'connection' => $this->connection,
  1544. 'alias' => 'Users',
  1545. 'table' => 'users',
  1546. ]]
  1547. );
  1548. $entity = $table->newEntity(['username' => 'mark']);
  1549. $this->assertTrue($entity->isNew());
  1550. $table->expects($this->never())
  1551. ->method('exists');
  1552. $this->assertSame($entity, $table->save($entity));
  1553. }
  1554. /**
  1555. * Test that saving a new entity with a Primary Key set does call exists.
  1556. *
  1557. * @group save
  1558. * @return void
  1559. */
  1560. public function testSavePrimaryKeyEntityExists()
  1561. {
  1562. $this->skipIfSqlServer();
  1563. $table = $this->getMock(
  1564. 'Cake\ORM\Table',
  1565. ['exists'],
  1566. [
  1567. [
  1568. 'connection' => $this->connection,
  1569. 'alias' => 'Users',
  1570. 'table' => 'users',
  1571. ]
  1572. ]
  1573. );
  1574. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1575. $this->assertTrue($entity->isNew());
  1576. $table->expects($this->once())->method('exists');
  1577. $this->assertSame($entity, $table->save($entity));
  1578. }
  1579. /**
  1580. * Test that saving a new entity with a Primary Key set does not call exists when checkExisting is false.
  1581. *
  1582. * @group save
  1583. * @return void
  1584. */
  1585. public function testSavePrimaryKeyEntityNoExists()
  1586. {
  1587. $this->skipIfSqlServer();
  1588. $table = $this->getMock(
  1589. 'Cake\ORM\Table',
  1590. ['exists'],
  1591. [
  1592. [
  1593. 'connection' => $this->connection,
  1594. 'alias' => 'Users',
  1595. 'table' => 'users',
  1596. ]
  1597. ]
  1598. );
  1599. $entity = $table->newEntity(['id' => 20, 'username' => 'mark']);
  1600. $this->assertTrue($entity->isNew());
  1601. $table->expects($this->never())->method('exists');
  1602. $this->assertSame($entity, $table->save($entity, ['checkExisting' => false]));
  1603. }
  1604. /**
  1605. * Tests that saving an entity will filter out properties that
  1606. * are not present in the table schema when saving
  1607. *
  1608. * @group save
  1609. * @return void
  1610. */
  1611. public function testSaveEntityOnlySchemaFields()
  1612. {
  1613. $entity = new \Cake\ORM\Entity([
  1614. 'username' => 'superuser',
  1615. 'password' => 'root',
  1616. 'crazyness' => 'super crazy value',
  1617. 'created' => new Time('2013-10-10 00:00'),
  1618. 'updated' => new Time('2013-10-10 00:00'),
  1619. ]);
  1620. $table = TableRegistry::get('users');
  1621. $this->assertSame($entity, $table->save($entity));
  1622. $this->assertEquals($entity->id, self::$nextUserId);
  1623. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1624. $entity->unsetProperty('crazyness');
  1625. $this->assertEquals($entity->toArray(), $row->toArray());
  1626. }
  1627. /**
  1628. * Tests that it is possible to modify data from the beforeSave callback
  1629. *
  1630. * @group save
  1631. * @return void
  1632. */
  1633. public function testBeforeSaveModifyData()
  1634. {
  1635. $table = TableRegistry::get('users');
  1636. $data = new \Cake\ORM\Entity([
  1637. 'username' => 'superuser',
  1638. 'created' => new Time('2013-10-10 00:00'),
  1639. 'updated' => new Time('2013-10-10 00:00')
  1640. ]);
  1641. $listener = function ($e, $entity, $options) use ($data) {
  1642. $this->assertSame($data, $entity);
  1643. $entity->set('password', 'foo');
  1644. };
  1645. $table->eventManager()->on('Model.beforeSave', $listener);
  1646. $this->assertSame($data, $table->save($data));
  1647. $this->assertEquals($data->id, self::$nextUserId);
  1648. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1649. $this->assertEquals('foo', $row->get('password'));
  1650. }
  1651. /**
  1652. * Tests that it is possible to modify the options array in beforeSave
  1653. *
  1654. * @group save
  1655. * @return void
  1656. */
  1657. public function testBeforeSaveModifyOptions()
  1658. {
  1659. $table = TableRegistry::get('users');
  1660. $data = new \Cake\ORM\Entity([
  1661. 'username' => 'superuser',
  1662. 'password' => 'foo',
  1663. 'created' => new Time('2013-10-10 00:00'),
  1664. 'updated' => new Time('2013-10-10 00:00')
  1665. ]);
  1666. $listener1 = function ($e, $entity, $options) {
  1667. $options['crazy'] = true;
  1668. };
  1669. $listener2 = function ($e, $entity, $options) {
  1670. $this->assertTrue($options['crazy']);
  1671. };
  1672. $table->eventManager()->on('Model.beforeSave', $listener1);
  1673. $table->eventManager()->on('Model.beforeSave', $listener2);
  1674. $this->assertSame($data, $table->save($data));
  1675. $this->assertEquals($data->id, self::$nextUserId);
  1676. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1677. $this->assertEquals($data->toArray(), $row->toArray());
  1678. }
  1679. /**
  1680. * Tests that it is possible to stop the saving altogether, without implying
  1681. * the save operation failed
  1682. *
  1683. * @group save
  1684. * @return void
  1685. */
  1686. public function testBeforeSaveStopEvent()
  1687. {
  1688. $table = TableRegistry::get('users');
  1689. $data = new \Cake\ORM\Entity([
  1690. 'username' => 'superuser',
  1691. 'created' => new Time('2013-10-10 00:00'),
  1692. 'updated' => new Time('2013-10-10 00:00')
  1693. ]);
  1694. $listener = function ($e, $entity) {
  1695. $e->stopPropagation();
  1696. return $entity;
  1697. };
  1698. $table->eventManager()->on('Model.beforeSave', $listener);
  1699. $this->assertSame($data, $table->save($data));
  1700. $this->assertNull($data->id);
  1701. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  1702. $this->assertNull($row);
  1703. }
  1704. /**
  1705. * Asserts that afterSave callback is called on successful save
  1706. *
  1707. * @group save
  1708. * @return void
  1709. */
  1710. public function testAfterSave()
  1711. {
  1712. $table = TableRegistry::get('users');
  1713. $data = new \Cake\ORM\Entity([
  1714. 'username' => 'superuser',
  1715. 'created' => new Time('2013-10-10 00:00'),
  1716. 'updated' => new Time('2013-10-10 00:00')
  1717. ]);
  1718. $called = false;
  1719. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1720. $this->assertSame($data, $entity);
  1721. $this->assertTrue($entity->dirty());
  1722. $called = true;
  1723. };
  1724. $table->eventManager()->on('Model.afterSave', $listener);
  1725. $calledAfterCommit = false;
  1726. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1727. $this->assertSame($data, $entity);
  1728. $this->assertFalse($entity->dirty());
  1729. $calledAfterCommit = true;
  1730. };
  1731. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1732. $this->assertSame($data, $table->save($data));
  1733. $this->assertEquals($data->id, self::$nextUserId);
  1734. $this->assertTrue($called);
  1735. $this->assertTrue($calledAfterCommit);
  1736. }
  1737. /**
  1738. * Asserts that afterSaveCommit is also triggered for non-atomic saves
  1739. *
  1740. * @return void
  1741. */
  1742. public function testAfterSaveCommitForNonAtomic()
  1743. {
  1744. $table = TableRegistry::get('users');
  1745. $data = new \Cake\ORM\Entity([
  1746. 'username' => 'superuser',
  1747. 'created' => new Time('2013-10-10 00:00'),
  1748. 'updated' => new Time('2013-10-10 00:00')
  1749. ]);
  1750. $called = false;
  1751. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1752. $this->assertSame($data, $entity);
  1753. $called = true;
  1754. };
  1755. $table->eventManager()->on('Model.afterSave', $listener);
  1756. $calledAfterCommit = false;
  1757. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1758. $calledAfterCommit = true;
  1759. };
  1760. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1761. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  1762. $this->assertEquals($data->id, self::$nextUserId);
  1763. $this->assertTrue($called);
  1764. $this->assertTrue($calledAfterCommit);
  1765. }
  1766. /**
  1767. * Asserts the afterSaveCommit is not triggered if transaction is running.
  1768. *
  1769. * @return void
  1770. */
  1771. public function testAfterSaveCommitWithTransactionRunning()
  1772. {
  1773. $table = TableRegistry::get('users');
  1774. $data = new \Cake\ORM\Entity([
  1775. 'username' => 'superuser',
  1776. 'created' => new Time('2013-10-10 00:00'),
  1777. 'updated' => new Time('2013-10-10 00:00')
  1778. ]);
  1779. $called = false;
  1780. $listener = function ($e, $entity, $options) use (&$called) {
  1781. $called = true;
  1782. };
  1783. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  1784. $this->connection->begin();
  1785. $this->assertSame($data, $table->save($data));
  1786. $this->assertFalse($called);
  1787. $this->connection->commit();
  1788. }
  1789. /**
  1790. * Asserts the afterSaveCommit is not triggered if transaction is running.
  1791. *
  1792. * @return void
  1793. */
  1794. public function testAfterSaveCommitWithNonAtomicAndTransactionRunning()
  1795. {
  1796. $table = TableRegistry::get('users');
  1797. $data = new \Cake\ORM\Entity([
  1798. 'username' => 'superuser',
  1799. 'created' => new Time('2013-10-10 00:00'),
  1800. 'updated' => new Time('2013-10-10 00:00')
  1801. ]);
  1802. $called = false;
  1803. $listener = function ($e, $entity, $options) use (&$called) {
  1804. $called = true;
  1805. };
  1806. $table->eventManager()->on('Model.afterSaveCommit', $listener);
  1807. $this->connection->begin();
  1808. $this->assertSame($data, $table->save($data, ['atomic' => false]));
  1809. $this->assertFalse($called);
  1810. $this->connection->commit();
  1811. }
  1812. /**
  1813. * Asserts that afterSave callback not is called on unsuccessful save
  1814. *
  1815. * @group save
  1816. * @return void
  1817. */
  1818. public function testAfterSaveNotCalled()
  1819. {
  1820. $table = $this->getMock(
  1821. '\Cake\ORM\Table',
  1822. ['query'],
  1823. [['table' => 'users', 'connection' => $this->connection]]
  1824. );
  1825. $query = $this->getMock(
  1826. '\Cake\ORM\Query',
  1827. ['execute', 'addDefaultTypes'],
  1828. [null, $table]
  1829. );
  1830. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  1831. $data = new \Cake\ORM\Entity([
  1832. 'username' => 'superuser',
  1833. 'created' => new Time('2013-10-10 00:00'),
  1834. 'updated' => new Time('2013-10-10 00:00')
  1835. ]);
  1836. $table->expects($this->once())->method('query')
  1837. ->will($this->returnValue($query));
  1838. $query->expects($this->once())->method('execute')
  1839. ->will($this->returnValue($statement));
  1840. $statement->expects($this->once())->method('rowCount')
  1841. ->will($this->returnValue(0));
  1842. $called = false;
  1843. $listener = function ($e, $entity, $options) use ($data, &$called) {
  1844. $called = true;
  1845. };
  1846. $table->eventManager()->on('Model.afterSave', $listener);
  1847. $calledAfterCommit = false;
  1848. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  1849. $calledAfterCommit = true;
  1850. };
  1851. $table->eventManager()->on('Model.afterSaveCommit', $listenerAfterCommit);
  1852. $this->assertFalse($table->save($data));
  1853. $this->assertFalse($called);
  1854. $this->assertFalse($calledAfterCommit);
  1855. }
  1856. /**
  1857. * Asserts that afterSaveCommit callback is triggered only for primary table
  1858. *
  1859. * @group save
  1860. * @return void
  1861. */
  1862. public function testAfterSaveCommitTriggeredOnlyForPrimaryTable()
  1863. {
  1864. $entity = new \Cake\ORM\Entity([
  1865. 'title' => 'A Title',
  1866. 'body' => 'A body'
  1867. ]);
  1868. $entity->author = new \Cake\ORM\Entity([
  1869. 'name' => 'Jose'
  1870. ]);
  1871. $table = TableRegistry::get('articles');
  1872. $table->belongsTo('authors');
  1873. $calledForArticle = false;
  1874. $listenerForArticle = function ($e, $entity, $options) use (&$calledForArticle) {
  1875. $calledForArticle = true;
  1876. };
  1877. $table->eventManager()->on('Model.afterSaveCommit', $listenerForArticle);
  1878. $calledForAuthor = false;
  1879. $listenerForAuthor = function ($e, $entity, $options) use (&$calledForAuthor) {
  1880. $calledForAuthor = true;
  1881. };
  1882. $table->authors->eventManager()->on('Model.afterSaveCommit', $listenerForAuthor);
  1883. $this->assertSame($entity, $table->save($entity));
  1884. $this->assertFalse($entity->isNew());
  1885. $this->assertFalse($entity->author->isNew());
  1886. $this->assertTrue($calledForArticle);
  1887. $this->assertFalse($calledForAuthor);
  1888. }
  1889. /**
  1890. * Test that you cannot save rows without a primary key.
  1891. *
  1892. * @group save
  1893. * @expectedException \RuntimeException
  1894. * @expectedExceptionMessage Cannot insert row in "users" table, it has no primary key
  1895. * @return void
  1896. */
  1897. public function testSaveNewErrorOnNoPrimaryKey()
  1898. {
  1899. $entity = new \Cake\ORM\Entity(['username' => 'superuser']);
  1900. $table = TableRegistry::get('users', [
  1901. 'schema' => [
  1902. 'id' => ['type' => 'integer'],
  1903. 'username' => ['type' => 'string'],
  1904. ]
  1905. ]);
  1906. $table->save($entity);
  1907. }
  1908. /**
  1909. * Tests that save is wrapped around a transaction
  1910. *
  1911. * @group save
  1912. * @return void
  1913. */
  1914. public function testAtomicSave()
  1915. {
  1916. $config = ConnectionManager::config('test');
  1917. $connection = $this->getMock(
  1918. '\Cake\Database\Connection',
  1919. ['begin', 'commit'],
  1920. [$config]
  1921. );
  1922. $connection->driver($this->connection->driver());
  1923. $table = $this->getMock('\Cake\ORM\Table', ['connection'], [['table' => 'users']]);
  1924. $table->expects($this->any())->method('connection')
  1925. ->will($this->returnValue($connection));
  1926. $connection->expects($this->once())->method('begin');
  1927. $connection->expects($this->once())->method('commit');
  1928. $data = new \Cake\ORM\Entity([
  1929. 'username' => 'superuser',
  1930. 'created' => new Time('2013-10-10 00:00'),
  1931. 'updated' => new Time('2013-10-10 00:00')
  1932. ]);
  1933. $this->assertSame($data, $table->save($data));
  1934. }
  1935. /**
  1936. * Tests that save will rollback the transaction in the case of an exception
  1937. *
  1938. * @group save
  1939. * @expectedException \PDOException
  1940. * @return void
  1941. */
  1942. public function testAtomicSaveRollback()
  1943. {
  1944. $connection = $this->getMock(
  1945. '\Cake\Database\Connection',
  1946. ['begin', 'rollback'],
  1947. [ConnectionManager::config('test')]
  1948. );
  1949. $connection->driver(ConnectionManager::get('test')->driver());
  1950. $table = $this->getMock(
  1951. '\Cake\ORM\Table',
  1952. ['query', 'connection'],
  1953. [['table' => 'users']]
  1954. );
  1955. $query = $this->getMock(
  1956. '\Cake\ORM\Query',
  1957. ['execute', 'addDefaultTypes'],
  1958. [null, $table]
  1959. );
  1960. $table->expects($this->any())->method('connection')
  1961. ->will($this->returnValue($connection));
  1962. $table->expects($this->once())->method('query')
  1963. ->will($this->returnValue($query));
  1964. $connection->expects($this->once())->method('begin');
  1965. $connection->expects($this->once())->method('rollback');
  1966. $query->expects($this->once())->method('execute')
  1967. ->will($this->throwException(new \PDOException));
  1968. $data = new \Cake\ORM\Entity([
  1969. 'username' => 'superuser',
  1970. 'created' => new Time('2013-10-10 00:00'),
  1971. 'updated' => new Time('2013-10-10 00:00')
  1972. ]);
  1973. $table->save($data);
  1974. }
  1975. /**
  1976. * Tests that save will rollback the transaction in the case of an exception
  1977. *
  1978. * @group save
  1979. * @return void
  1980. */
  1981. public function testAtomicSaveRollbackOnFailure()
  1982. {
  1983. $connection = $this->getMock(
  1984. '\Cake\Database\Connection',
  1985. ['begin', 'rollback'],
  1986. [ConnectionManager::config('test')]
  1987. );
  1988. $connection->driver(ConnectionManager::get('test')->driver());
  1989. $table = $this->getMock(
  1990. '\Cake\ORM\Table',
  1991. ['query', 'connection', 'exists'],
  1992. [['table' => 'users']]
  1993. );
  1994. $query = $this->getMock(
  1995. '\Cake\ORM\Query',
  1996. ['execute', 'addDefaultTypes'],
  1997. [null, $table]
  1998. );
  1999. $table->expects($this->any())->method('connection')
  2000. ->will($this->returnValue($connection));
  2001. $table->expects($this->once())->method('query')
  2002. ->will($this->returnValue($query));
  2003. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2004. $statement->expects($this->once())
  2005. ->method('rowCount')
  2006. ->will($this->returnValue(0));
  2007. $connection->expects($this->once())->method('begin');
  2008. $connection->expects($this->once())->method('rollback');
  2009. $query->expects($this->once())
  2010. ->method('execute')
  2011. ->will($this->returnValue($statement));
  2012. $data = new \Cake\ORM\Entity([
  2013. 'username' => 'superuser',
  2014. 'created' => new Time('2013-10-10 00:00'),
  2015. 'updated' => new Time('2013-10-10 00:00')
  2016. ]);
  2017. $table->save($data);
  2018. }
  2019. /**
  2020. * Tests that only the properties marked as dirty are actually saved
  2021. * to the database
  2022. *
  2023. * @group save
  2024. * @return void
  2025. */
  2026. public function testSaveOnlyDirtyProperties()
  2027. {
  2028. $entity = new \Cake\ORM\Entity([
  2029. 'username' => 'superuser',
  2030. 'password' => 'root',
  2031. 'created' => new Time('2013-10-10 00:00'),
  2032. 'updated' => new Time('2013-10-10 00:00')
  2033. ]);
  2034. $entity->clean();
  2035. $entity->dirty('username', true);
  2036. $entity->dirty('created', true);
  2037. $entity->dirty('updated', true);
  2038. $table = TableRegistry::get('users');
  2039. $this->assertSame($entity, $table->save($entity));
  2040. $this->assertEquals($entity->id, self::$nextUserId);
  2041. $row = $table->find('all')->where(['id' => self::$nextUserId])->first();
  2042. $entity->set('password', null);
  2043. $this->assertEquals($entity->toArray(), $row->toArray());
  2044. }
  2045. /**
  2046. * Tests that a recently saved entity is marked as clean
  2047. *
  2048. * @group save
  2049. * @return void
  2050. */
  2051. public function testASavedEntityIsClean()
  2052. {
  2053. $entity = new \Cake\ORM\Entity([
  2054. 'username' => 'superuser',
  2055. 'password' => 'root',
  2056. 'created' => new Time('2013-10-10 00:00'),
  2057. 'updated' => new Time('2013-10-10 00:00')
  2058. ]);
  2059. $table = TableRegistry::get('users');
  2060. $this->assertSame($entity, $table->save($entity));
  2061. $this->assertFalse($entity->dirty('usermane'));
  2062. $this->assertFalse($entity->dirty('password'));
  2063. $this->assertFalse($entity->dirty('created'));
  2064. $this->assertFalse($entity->dirty('updated'));
  2065. }
  2066. /**
  2067. * Tests that a recently saved entity is marked as not new
  2068. *
  2069. * @group save
  2070. * @return void
  2071. */
  2072. public function testASavedEntityIsNotNew()
  2073. {
  2074. $entity = new \Cake\ORM\Entity([
  2075. 'username' => 'superuser',
  2076. 'password' => 'root',
  2077. 'created' => new Time('2013-10-10 00:00'),
  2078. 'updated' => new Time('2013-10-10 00:00')
  2079. ]);
  2080. $table = TableRegistry::get('users');
  2081. $this->assertSame($entity, $table->save($entity));
  2082. $this->assertFalse($entity->isNew());
  2083. }
  2084. /**
  2085. * Tests that save can detect automatically if it needs to insert
  2086. * or update a row
  2087. *
  2088. * @group save
  2089. * @return void
  2090. */
  2091. public function testSaveUpdateAuto()
  2092. {
  2093. $entity = new \Cake\ORM\Entity([
  2094. 'id' => 2,
  2095. 'username' => 'baggins'
  2096. ]);
  2097. $table = TableRegistry::get('users');
  2098. $original = $table->find('all')->where(['id' => 2])->first();
  2099. $this->assertSame($entity, $table->save($entity));
  2100. $row = $table->find('all')->where(['id' => 2])->first();
  2101. $this->assertEquals('baggins', $row->username);
  2102. $this->assertEquals($original->password, $row->password);
  2103. $this->assertEquals($original->created, $row->created);
  2104. $this->assertEquals($original->updated, $row->updated);
  2105. $this->assertFalse($entity->isNew());
  2106. $this->assertFalse($entity->dirty('id'));
  2107. $this->assertFalse($entity->dirty('username'));
  2108. }
  2109. /**
  2110. * Tests that beforeFind gets the correct isNew() state for the entity
  2111. *
  2112. * @return void
  2113. */
  2114. public function testBeforeSaveGetsCorrectPersistance()
  2115. {
  2116. $entity = new \Cake\ORM\Entity([
  2117. 'id' => 2,
  2118. 'username' => 'baggins'
  2119. ]);
  2120. $table = TableRegistry::get('users');
  2121. $called = false;
  2122. $listener = function ($event, $entity) use (&$called) {
  2123. $this->assertFalse($entity->isNew());
  2124. $called = true;
  2125. };
  2126. $table->eventManager()->on('Model.beforeSave', $listener);
  2127. $this->assertSame($entity, $table->save($entity));
  2128. $this->assertTrue($called);
  2129. }
  2130. /**
  2131. * Tests that marking an entity as already persisted will prevent the save
  2132. * method from trying to infer the entity's actual status.
  2133. *
  2134. * @group save
  2135. * @return void
  2136. */
  2137. public function testSaveUpdateWithHint()
  2138. {
  2139. $table = $this->getMock(
  2140. '\Cake\ORM\Table',
  2141. ['exists'],
  2142. [['table' => 'users', 'connection' => ConnectionManager::get('test')]]
  2143. );
  2144. $entity = new \Cake\ORM\Entity([
  2145. 'id' => 2,
  2146. 'username' => 'baggins'
  2147. ], ['markNew' => false]);
  2148. $this->assertFalse($entity->isNew());
  2149. $table->expects($this->never())->method('exists');
  2150. $this->assertSame($entity, $table->save($entity));
  2151. }
  2152. /**
  2153. * Tests that when updating the primary key is not passed to the list of
  2154. * attributes to change
  2155. *
  2156. * @group save
  2157. * @return void
  2158. */
  2159. public function testSaveUpdatePrimaryKeyNotModified()
  2160. {
  2161. $table = $this->getMock(
  2162. '\Cake\ORM\Table',
  2163. ['query'],
  2164. [['table' => 'users', 'connection' => $this->connection]]
  2165. );
  2166. $query = $this->getMock(
  2167. '\Cake\ORM\Query',
  2168. ['execute', 'addDefaultTypes', 'set'],
  2169. [null, $table]
  2170. );
  2171. $table->expects($this->once())->method('query')
  2172. ->will($this->returnValue($query));
  2173. $statement = $this->getMock('\Cake\Database\Statement\StatementDecorator');
  2174. $statement->expects($this->once())
  2175. ->method('errorCode')
  2176. ->will($this->returnValue('00000'));
  2177. $query->expects($this->once())
  2178. ->method('execute')
  2179. ->will($this->returnValue($statement));
  2180. $query->expects($this->once())->method('set')
  2181. ->with(['username' => 'baggins'])
  2182. ->will($this->returnValue($query));
  2183. $entity = new \Cake\ORM\Entity([
  2184. 'id' => 2,
  2185. 'username' => 'baggins'
  2186. ], ['markNew' => false]);
  2187. $this->assertSame($entity, $table->save($entity));
  2188. }
  2189. /**
  2190. * Tests that passing only the primary key to save will not execute any queries
  2191. * but still return success
  2192. *
  2193. * @group save
  2194. * @return void
  2195. */
  2196. public function testUpdateNoChange()
  2197. {
  2198. $table = $this->getMock(
  2199. '\Cake\ORM\Table',
  2200. ['query'],
  2201. [['table' => 'users', 'connection' => $this->connection]]
  2202. );
  2203. $table->expects($this->never())->method('query');
  2204. $entity = new \Cake\ORM\Entity([
  2205. 'id' => 2,
  2206. ], ['markNew' => false]);
  2207. $this->assertSame($entity, $table->save($entity));
  2208. }
  2209. /**
  2210. * Tests that passing only the primary key to save will not execute any queries
  2211. * but still return success
  2212. *
  2213. * @group save
  2214. * @group integration
  2215. * @return void
  2216. */
  2217. public function testUpdateDirtyNoActualChanges()
  2218. {
  2219. $table = TableRegistry::get('Articles');
  2220. $entity = $table->get(1);
  2221. $entity->accessible('*', true);
  2222. $entity->set($entity->toArray());
  2223. $this->assertSame($entity, $table->save($entity));
  2224. }
  2225. /**
  2226. * Tests that failing to pass a primary key to save will result in exception
  2227. *
  2228. * @group save
  2229. * @expectedException \InvalidArgumentException
  2230. * @return void
  2231. */
  2232. public function testUpdateNoPrimaryButOtherKeys()
  2233. {
  2234. $table = $this->getMock(
  2235. '\Cake\ORM\Table',
  2236. ['query'],
  2237. [['table' => 'users', 'connection' => $this->connection]]
  2238. );
  2239. $table->expects($this->never())->method('query');
  2240. $entity = new \Cake\ORM\Entity([
  2241. 'username' => 'mariano',
  2242. ], ['markNew' => false]);
  2243. $this->assertSame($entity, $table->save($entity));
  2244. }
  2245. /**
  2246. * Test simple delete.
  2247. *
  2248. * @return void
  2249. */
  2250. public function testDelete()
  2251. {
  2252. $table = TableRegistry::get('users');
  2253. $conditions = [
  2254. 'limit' => 1,
  2255. 'conditions' => [
  2256. 'username' => 'nate'
  2257. ]
  2258. ];
  2259. $query = $table->find('all', $conditions);
  2260. $entity = $query->first();
  2261. $result = $table->delete($entity);
  2262. $this->assertTrue($result);
  2263. $query = $table->find('all', $conditions);
  2264. $results = $query->execute();
  2265. $this->assertCount(0, $results, 'Find should fail.');
  2266. }
  2267. /**
  2268. * Test delete with dependent records
  2269. *
  2270. * @return void
  2271. */
  2272. public function testDeleteDependent()
  2273. {
  2274. $table = TableRegistry::get('authors');
  2275. $table->hasOne('articles', [
  2276. 'foreignKey' => 'author_id',
  2277. 'dependent' => true,
  2278. ]);
  2279. $entity = $table->get(1);
  2280. $result = $table->delete($entity);
  2281. $articles = $table->association('articles')->target();
  2282. $query = $articles->find('all', [
  2283. 'conditions' => [
  2284. 'author_id' => $entity->id
  2285. ]
  2286. ]);
  2287. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2288. }
  2289. /**
  2290. * Test delete with dependent records
  2291. *
  2292. * @return void
  2293. */
  2294. public function testDeleteDependentHasMany()
  2295. {
  2296. $table = TableRegistry::get('authors');
  2297. $table->hasMany('articles', [
  2298. 'foreignKey' => 'author_id',
  2299. 'dependent' => true,
  2300. 'cascadeCallbacks' => true,
  2301. ]);
  2302. $entity = $table->get(1);
  2303. $result = $table->delete($entity);
  2304. $this->assertTrue($result);
  2305. }
  2306. /**
  2307. * Test delete with dependent = false does not cascade.
  2308. *
  2309. * @return void
  2310. */
  2311. public function testDeleteNoDependentNoCascade()
  2312. {
  2313. $table = TableRegistry::get('authors');
  2314. $table->hasMany('article', [
  2315. 'foreignKey' => 'author_id',
  2316. 'dependent' => false,
  2317. ]);
  2318. $query = $table->find('all')->where(['id' => 1]);
  2319. $entity = $query->first();
  2320. $result = $table->delete($entity);
  2321. $articles = $table->association('articles')->target();
  2322. $query = $articles->find('all')->where(['author_id' => $entity->id]);
  2323. $this->assertCount(2, $query->execute(), 'Should find rows.');
  2324. }
  2325. /**
  2326. * Test delete with BelongsToMany
  2327. *
  2328. * @return void
  2329. */
  2330. public function testDeleteBelongsToMany()
  2331. {
  2332. $table = TableRegistry::get('articles');
  2333. $table->belongsToMany('tag', [
  2334. 'foreignKey' => 'article_id',
  2335. 'joinTable' => 'articles_tags'
  2336. ]);
  2337. $query = $table->find('all')->where(['id' => 1]);
  2338. $entity = $query->first();
  2339. $table->delete($entity);
  2340. $junction = $table->association('tags')->junction();
  2341. $query = $junction->find('all')->where(['article_id' => 1]);
  2342. $this->assertNull($query->all()->first(), 'Should not find any rows.');
  2343. }
  2344. /**
  2345. * Test delete with dependent records belonging to an aliased
  2346. * belongsToMany association.
  2347. *
  2348. * @return void
  2349. */
  2350. public function testDeleteDependentAliased()
  2351. {
  2352. $Authors = TableRegistry::get('authors');
  2353. $Authors->associations()->removeAll();
  2354. $Articles = TableRegistry::get('articles');
  2355. $Articles->associations()->removeAll();
  2356. $Authors->hasMany('AliasedArticles', [
  2357. 'className' => 'articles',
  2358. 'dependent' => true,
  2359. 'cascadeCallbacks' => true
  2360. ]);
  2361. $Articles->belongsToMany('Tags');
  2362. $author = $Authors->get(1);
  2363. $result = $Authors->delete($author);
  2364. $this->assertTrue($result);
  2365. }
  2366. /**
  2367. * Test that cascading associations are deleted first.
  2368. *
  2369. * @return void
  2370. */
  2371. public function testDeleteAssociationsCascadingCallbacksOrder()
  2372. {
  2373. $groups = TableRegistry::get('Groups');
  2374. $members = TableRegistry::get('Members');
  2375. $groupsMembers = TableRegistry::get('GroupsMembers');
  2376. $groups->belongsToMany('Members');
  2377. $groups->hasMany('GroupsMembers', [
  2378. 'dependent' => true,
  2379. 'cascadeCallbacks' => true,
  2380. ]);
  2381. $groupsMembers->belongsTo('Members');
  2382. $groupsMembers->addBehavior('CounterCache', [
  2383. 'Members' => ['group_count']
  2384. ]);
  2385. $member = $members->get(1);
  2386. $this->assertEquals(2, $member->group_count);
  2387. $group = $groups->get(1);
  2388. $groups->delete($group);
  2389. $member = $members->get(1);
  2390. $this->assertEquals(1, $member->group_count);
  2391. }
  2392. /**
  2393. * Test delete callbacks
  2394. *
  2395. * @return void
  2396. */
  2397. public function testDeleteCallbacks()
  2398. {
  2399. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2400. $options = new \ArrayObject(['atomic' => true, 'checkRules' => false, '_primary' => true]);
  2401. $mock = $this->getMock('Cake\Event\EventManager');
  2402. $mock->expects($this->at(0))
  2403. ->method('on');
  2404. $mock->expects($this->at(1))
  2405. ->method('dispatch');
  2406. $mock->expects($this->at(2))
  2407. ->method('dispatch')
  2408. ->with($this->logicalAnd(
  2409. $this->attributeEqualTo('_name', 'Model.beforeDelete'),
  2410. $this->attributeEqualTo(
  2411. 'data',
  2412. ['entity' => $entity, 'options' => $options]
  2413. )
  2414. ));
  2415. $mock->expects($this->at(3))
  2416. ->method('dispatch')
  2417. ->with($this->logicalAnd(
  2418. $this->attributeEqualTo('_name', 'Model.afterDelete'),
  2419. $this->attributeEqualTo(
  2420. 'data',
  2421. ['entity' => $entity, 'options' => $options]
  2422. )
  2423. ));
  2424. $mock->expects($this->at(4))
  2425. ->method('dispatch')
  2426. ->with($this->logicalAnd(
  2427. $this->attributeEqualTo('_name', 'Model.afterDeleteCommit'),
  2428. $this->attributeEqualTo(
  2429. 'data',
  2430. ['entity' => $entity, 'options' => $options]
  2431. )
  2432. ));
  2433. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2434. $entity->isNew(false);
  2435. $table->delete($entity, ['checkRules' => false]);
  2436. }
  2437. /**
  2438. * Test afterDeleteCommit is also called for non-atomic delete
  2439. *
  2440. * @return void
  2441. */
  2442. public function testDeleteCallbacksNonAtomic()
  2443. {
  2444. $table = TableRegistry::get('users');
  2445. $data = $table->get(1);
  2446. $options = new \ArrayObject(['atomic' => false, 'checkRules' => false]);
  2447. $called = false;
  2448. $listener = function ($e, $entity, $options) use ($data, &$called) {
  2449. $this->assertSame($data, $entity);
  2450. $called = true;
  2451. };
  2452. $table->eventManager()->on('Model.afterDelete', $listener);
  2453. $calledAfterCommit = false;
  2454. $listenerAfterCommit = function ($e, $entity, $options) use ($data, &$calledAfterCommit) {
  2455. $calledAfterCommit = true;
  2456. };
  2457. $table->eventManager()->on('Model.afterDeleteCommit', $listenerAfterCommit);
  2458. $table->delete($data, ['atomic' => false]);
  2459. $this->assertTrue($called);
  2460. $this->assertTrue($calledAfterCommit);
  2461. }
  2462. /**
  2463. * Test that afterDeleteCommit is only triggered for primary table
  2464. *
  2465. * @return void
  2466. */
  2467. public function testAfterDeleteCommitTriggeredOnlyForPrimaryTable()
  2468. {
  2469. $table = TableRegistry::get('authors');
  2470. $table->hasOne('articles', [
  2471. 'foreignKey' => 'author_id',
  2472. 'dependent' => true,
  2473. ]);
  2474. $called = false;
  2475. $listener = function ($e, $entity, $options) use (&$called) {
  2476. $called = true;
  2477. };
  2478. $table->eventManager()->on('Model.afterDeleteCommit', $listener);
  2479. $called2 = false;
  2480. $listener = function ($e, $entity, $options) use (&$called2) {
  2481. $called2 = true;
  2482. };
  2483. $table->articles->eventManager()->on('Model.afterDeleteCommit', $listener);
  2484. $entity = $table->get(1);
  2485. $this->assertTrue($table->delete($entity));
  2486. $this->assertTrue($called);
  2487. $this->assertFalse($called2);
  2488. }
  2489. /**
  2490. * Test delete beforeDelete can abort the delete.
  2491. *
  2492. * @return void
  2493. */
  2494. public function testDeleteBeforeDeleteAbort()
  2495. {
  2496. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2497. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2498. $mock = $this->getMock('Cake\Event\EventManager');
  2499. $mock->expects($this->at(2))
  2500. ->method('dispatch')
  2501. ->will($this->returnCallback(function ($event) {
  2502. $event->stopPropagation();
  2503. }));
  2504. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2505. $entity->isNew(false);
  2506. $result = $table->delete($entity, ['checkRules' => false]);
  2507. $this->assertNull($result);
  2508. }
  2509. /**
  2510. * Test delete beforeDelete return result
  2511. *
  2512. * @return void
  2513. */
  2514. public function testDeleteBeforeDeleteReturnResult()
  2515. {
  2516. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2517. $options = new \ArrayObject(['atomic' => true, 'cascade' => true]);
  2518. $mock = $this->getMock('Cake\Event\EventManager');
  2519. $mock->expects($this->at(2))
  2520. ->method('dispatch')
  2521. ->will($this->returnCallback(function ($event) {
  2522. $event->stopPropagation();
  2523. $event->result = 'got stopped';
  2524. }));
  2525. $table = TableRegistry::get('users', ['eventManager' => $mock]);
  2526. $entity->isNew(false);
  2527. $result = $table->delete($entity, ['checkRules' => false]);
  2528. $this->assertEquals('got stopped', $result);
  2529. }
  2530. /**
  2531. * Test deleting new entities does nothing.
  2532. *
  2533. * @return void
  2534. */
  2535. public function testDeleteIsNew()
  2536. {
  2537. $entity = new \Cake\ORM\Entity(['id' => 1, 'name' => 'mark']);
  2538. $table = $this->getMock(
  2539. 'Cake\ORM\Table',
  2540. ['query'],
  2541. [['connection' => $this->connection]]
  2542. );
  2543. $table->expects($this->never())
  2544. ->method('query');
  2545. $entity->isNew(true);
  2546. $result = $table->delete($entity);
  2547. $this->assertFalse($result);
  2548. }
  2549. /**
  2550. * test hasField()
  2551. *
  2552. * @return void
  2553. */
  2554. public function testHasField()
  2555. {
  2556. $table = TableRegistry::get('articles');
  2557. $this->assertFalse($table->hasField('nope'), 'Should not be there.');
  2558. $this->assertTrue($table->hasField('title'), 'Should be there.');
  2559. $this->assertTrue($table->hasField('body'), 'Should be there.');
  2560. }
  2561. /**
  2562. * Tests that there exists a default validator
  2563. *
  2564. * @return void
  2565. */
  2566. public function testValidatorDefault()
  2567. {
  2568. $table = new Table();
  2569. $validator = $table->validator();
  2570. $this->assertSame($table, $validator->provider('table'));
  2571. $this->assertInstanceOf('Cake\Validation\Validator', $validator);
  2572. $default = $table->validator('default');
  2573. $this->assertSame($validator, $default);
  2574. }
  2575. /**
  2576. * Tests that it is possible to define custom validator methods
  2577. *
  2578. * @return void
  2579. */
  2580. public function functionTestValidationWithDefiner()
  2581. {
  2582. $table = $this->getMock('\Cake\ORM\Table', ['validationForOtherStuff']);
  2583. $table->expects($this->once())->method('validationForOtherStuff')
  2584. ->will($this->returnArgument(0));
  2585. $other = $table->validator('forOtherStuff');
  2586. $this->assertInstanceOf('Cake\Validation\Validator', $other);
  2587. $this->assertNotSame($other, $table->validator());
  2588. $this->assertSame($table, $other->provider('table'));
  2589. }
  2590. /**
  2591. * Tests that it is possible to set a custom validator under a name
  2592. *
  2593. * @return void
  2594. */
  2595. public function testValidatorSetter()
  2596. {
  2597. $table = new Table;
  2598. $validator = new \Cake\Validation\Validator;
  2599. $table->validator('other', $validator);
  2600. $this->assertSame($validator, $table->validator('other'));
  2601. $this->assertSame($table, $validator->provider('table'));
  2602. }
  2603. /**
  2604. * Tests that the source of an existing Entity is the same as a new one
  2605. *
  2606. * @return void
  2607. */
  2608. public function testEntitySourceExistingAndNew()
  2609. {
  2610. Plugin::load('TestPlugin');
  2611. $table = TableRegistry::get('TestPlugin.Authors');
  2612. $existingAuthor = $table->find()->first();
  2613. $newAuthor = $table->newEntity();
  2614. $this->assertEquals('TestPlugin.Authors', $existingAuthor->source());
  2615. $this->assertEquals('TestPlugin.Authors', $newAuthor->source());
  2616. }
  2617. /**
  2618. * Tests that calling an entity with an empty array will run validation
  2619. * whereas calling it with no parameters will not run any validation.
  2620. *
  2621. * @return void
  2622. */
  2623. public function testNewEntityAndValidation()
  2624. {
  2625. $table = TableRegistry::get('Articles');
  2626. $validator = $table->validator()->requirePresence('title');
  2627. $entity = $table->newEntity([]);
  2628. $errors = $entity->errors();
  2629. $this->assertNotEmpty($errors['title']);
  2630. $entity = $table->newEntity();
  2631. $this->assertEmpty($entity->errors());
  2632. }
  2633. /**
  2634. * Test magic findByXX method.
  2635. *
  2636. * @return void
  2637. */
  2638. public function testMagicFindDefaultToAll()
  2639. {
  2640. $table = TableRegistry::get('Users');
  2641. $result = $table->findByUsername('garrett');
  2642. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2643. $expected = new QueryExpression(['Users.username' => 'garrett'], $this->usersTypeMap);
  2644. $this->assertEquals($expected, $result->clause('where'));
  2645. }
  2646. /**
  2647. * Test magic findByXX errors on missing arguments.
  2648. *
  2649. * @expectedException \BadMethodCallException
  2650. * @expectedExceptionMessage Not enough arguments for magic finder. Got 0 required 1
  2651. * @return void
  2652. */
  2653. public function testMagicFindError()
  2654. {
  2655. $table = TableRegistry::get('Users');
  2656. $table->findByUsername();
  2657. }
  2658. /**
  2659. * Test magic findByXX errors on missing arguments.
  2660. *
  2661. * @expectedException \BadMethodCallException
  2662. * @expectedExceptionMessage Not enough arguments for magic finder. Got 1 required 2
  2663. * @return void
  2664. */
  2665. public function testMagicFindErrorMissingField()
  2666. {
  2667. $table = TableRegistry::get('Users');
  2668. $table->findByUsernameAndId('garrett');
  2669. }
  2670. /**
  2671. * Test magic findByXX errors when there is a mix of or & and.
  2672. *
  2673. * @expectedException \BadMethodCallException
  2674. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  2675. * @return void
  2676. */
  2677. public function testMagicFindErrorMixOfOperators()
  2678. {
  2679. $table = TableRegistry::get('Users');
  2680. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  2681. }
  2682. /**
  2683. * Test magic findByXX method.
  2684. *
  2685. * @return void
  2686. */
  2687. public function testMagicFindFirstAnd()
  2688. {
  2689. $table = TableRegistry::get('Users');
  2690. $result = $table->findByUsernameAndId('garrett', 4);
  2691. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2692. $expected = new QueryExpression(['Users.username' => 'garrett', 'Users.id' => 4], $this->usersTypeMap);
  2693. $this->assertEquals($expected, $result->clause('where'));
  2694. }
  2695. /**
  2696. * Test magic findByXX method.
  2697. *
  2698. * @return void
  2699. */
  2700. public function testMagicFindFirstOr()
  2701. {
  2702. $table = TableRegistry::get('Users');
  2703. $result = $table->findByUsernameOrId('garrett', 4);
  2704. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2705. $expected = new QueryExpression([], $this->usersTypeMap);
  2706. $expected->add(
  2707. [
  2708. 'OR' => [
  2709. 'Users.username' => 'garrett',
  2710. 'Users.id' => 4
  2711. ]]
  2712. );
  2713. $this->assertEquals($expected, $result->clause('where'));
  2714. }
  2715. /**
  2716. * Test magic findAllByXX method.
  2717. *
  2718. * @return void
  2719. */
  2720. public function testMagicFindAll()
  2721. {
  2722. $table = TableRegistry::get('Articles');
  2723. $result = $table->findAllByAuthorId(1);
  2724. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2725. $this->assertNull($result->clause('limit'));
  2726. $expected = new QueryExpression(['Articles.author_id' => 1], $this->articlesTypeMap);
  2727. $this->assertEquals($expected, $result->clause('where'));
  2728. }
  2729. /**
  2730. * Test magic findAllByXX method.
  2731. *
  2732. * @return void
  2733. */
  2734. public function testMagicFindAllAnd()
  2735. {
  2736. $table = TableRegistry::get('Users');
  2737. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  2738. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2739. $this->assertNull($result->clause('limit'));
  2740. $expected = new QueryExpression(
  2741. ['Users.author_id' => 1, 'Users.published' => 'Y'],
  2742. $this->usersTypeMap
  2743. );
  2744. $this->assertEquals($expected, $result->clause('where'));
  2745. }
  2746. /**
  2747. * Test magic findAllByXX method.
  2748. *
  2749. * @return void
  2750. */
  2751. public function testMagicFindAllOr()
  2752. {
  2753. $table = TableRegistry::get('Users');
  2754. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  2755. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2756. $this->assertNull($result->clause('limit'));
  2757. $expected = new QueryExpression();
  2758. $expected->typeMap()->defaults([
  2759. 'Users.id' => 'integer',
  2760. 'id' => 'integer',
  2761. 'Users.username' => 'string',
  2762. 'username' => 'string',
  2763. 'Users.password' => 'string',
  2764. 'password' => 'string',
  2765. 'Users.created' => 'timestamp',
  2766. 'created' => 'timestamp',
  2767. 'Users.updated' => 'timestamp',
  2768. 'updated' => 'timestamp',
  2769. ]);
  2770. $expected->add(
  2771. ['or' => ['Users.author_id' => 1, 'Users.published' => 'Y']]
  2772. );
  2773. $this->assertEquals($expected, $result->clause('where'));
  2774. $this->assertNull($result->clause('order'));
  2775. }
  2776. /**
  2777. * Test the behavior method.
  2778. *
  2779. * @return void
  2780. */
  2781. public function testBehaviorIntrospection()
  2782. {
  2783. $table = TableRegistry::get('users');
  2784. $table->addBehavior('Timestamp');
  2785. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  2786. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  2787. }
  2788. /**
  2789. * Tests saving belongsTo association
  2790. *
  2791. * @group save
  2792. * @return void
  2793. */
  2794. public function testSaveBelongsTo()
  2795. {
  2796. $entity = new \Cake\ORM\Entity([
  2797. 'title' => 'A Title',
  2798. 'body' => 'A body'
  2799. ]);
  2800. $entity->author = new \Cake\ORM\Entity([
  2801. 'name' => 'Jose'
  2802. ]);
  2803. $table = TableRegistry::get('articles');
  2804. $table->belongsTo('authors');
  2805. $this->assertSame($entity, $table->save($entity));
  2806. $this->assertFalse($entity->isNew());
  2807. $this->assertFalse($entity->author->isNew());
  2808. $this->assertEquals(5, $entity->author->id);
  2809. $this->assertEquals(5, $entity->get('author_id'));
  2810. }
  2811. /**
  2812. * Tests saving hasOne association
  2813. *
  2814. * @group save
  2815. * @return void
  2816. */
  2817. public function testSaveHasOne()
  2818. {
  2819. $entity = new \Cake\ORM\Entity([
  2820. 'name' => 'Jose'
  2821. ]);
  2822. $entity->article = new \Cake\ORM\Entity([
  2823. 'title' => 'A Title',
  2824. 'body' => 'A body'
  2825. ]);
  2826. $table = TableRegistry::get('authors');
  2827. $table->hasOne('articles');
  2828. $this->assertSame($entity, $table->save($entity));
  2829. $this->assertFalse($entity->isNew());
  2830. $this->assertFalse($entity->article->isNew());
  2831. $this->assertEquals(4, $entity->article->id);
  2832. $this->assertEquals(5, $entity->article->get('author_id'));
  2833. $this->assertFalse($entity->article->dirty('author_id'));
  2834. }
  2835. /**
  2836. * Tests saving associations only saves associations
  2837. * if they are entities.
  2838. *
  2839. * @group save
  2840. * @return void
  2841. */
  2842. public function testSaveOnlySaveAssociatedEntities()
  2843. {
  2844. $entity = new \Cake\ORM\Entity([
  2845. 'name' => 'Jose'
  2846. ]);
  2847. // Not an entity.
  2848. $entity->article = [
  2849. 'title' => 'A Title',
  2850. 'body' => 'A body'
  2851. ];
  2852. $table = TableRegistry::get('authors');
  2853. $table->hasOne('articles');
  2854. $table->save($entity);
  2855. $this->assertFalse($entity->isNew());
  2856. $this->assertInternalType('array', $entity->article);
  2857. }
  2858. /**
  2859. * Tests saving multiple entities in a hasMany association
  2860. *
  2861. * @return void
  2862. */
  2863. public function testSaveHasMany()
  2864. {
  2865. $entity = new \Cake\ORM\Entity([
  2866. 'name' => 'Jose'
  2867. ]);
  2868. $entity->articles = [
  2869. new \Cake\ORM\Entity([
  2870. 'title' => 'A Title',
  2871. 'body' => 'A body'
  2872. ]),
  2873. new \Cake\ORM\Entity([
  2874. 'title' => 'Another Title',
  2875. 'body' => 'Another body'
  2876. ])
  2877. ];
  2878. $table = TableRegistry::get('authors');
  2879. $table->hasMany('articles');
  2880. $this->assertSame($entity, $table->save($entity));
  2881. $this->assertFalse($entity->isNew());
  2882. $this->assertFalse($entity->articles[0]->isNew());
  2883. $this->assertFalse($entity->articles[1]->isNew());
  2884. $this->assertEquals(4, $entity->articles[0]->id);
  2885. $this->assertEquals(5, $entity->articles[1]->id);
  2886. $this->assertEquals(5, $entity->articles[0]->author_id);
  2887. $this->assertEquals(5, $entity->articles[1]->author_id);
  2888. }
  2889. /**
  2890. * Tests saving belongsToMany records
  2891. *
  2892. * @group save
  2893. * @return void
  2894. */
  2895. public function testSaveBelongsToMany()
  2896. {
  2897. $entity = new \Cake\ORM\Entity([
  2898. 'title' => 'A Title',
  2899. 'body' => 'A body'
  2900. ]);
  2901. $entity->tags = [
  2902. new \Cake\ORM\Entity([
  2903. 'name' => 'Something New'
  2904. ]),
  2905. new \Cake\ORM\Entity([
  2906. 'name' => 'Another Something'
  2907. ])
  2908. ];
  2909. $table = TableRegistry::get('articles');
  2910. $table->belongsToMany('tags');
  2911. $this->assertSame($entity, $table->save($entity));
  2912. $this->assertFalse($entity->isNew());
  2913. $this->assertFalse($entity->tags[0]->isNew());
  2914. $this->assertFalse($entity->tags[1]->isNew());
  2915. $this->assertEquals(4, $entity->tags[0]->id);
  2916. $this->assertEquals(5, $entity->tags[1]->id);
  2917. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  2918. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2919. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  2920. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2921. }
  2922. /**
  2923. * Tests saving belongsToMany records when record exists.
  2924. *
  2925. * @group save
  2926. * @return void
  2927. */
  2928. public function testSaveBelongsToManyJoinDataOnExistingRecord()
  2929. {
  2930. $tags = TableRegistry::get('Tags');
  2931. $table = TableRegistry::get('Articles');
  2932. $table->belongsToMany('Tags');
  2933. $entity = $table->find()->contain('Tags')->first();
  2934. // not associated to the article already.
  2935. $entity->tags[] = $tags->get(3);
  2936. $entity->dirty('tags', true);
  2937. $this->assertSame($entity, $table->save($entity));
  2938. $this->assertFalse($entity->isNew());
  2939. $this->assertFalse($entity->tags[0]->isNew());
  2940. $this->assertFalse($entity->tags[1]->isNew());
  2941. $this->assertFalse($entity->tags[2]->isNew());
  2942. $this->assertNotEmpty($entity->tags[0]->_joinData);
  2943. $this->assertNotEmpty($entity->tags[1]->_joinData);
  2944. $this->assertNotEmpty($entity->tags[2]->_joinData);
  2945. }
  2946. /**
  2947. * Test that belongsToMany can be saved with _joinData data.
  2948. *
  2949. * @return void
  2950. */
  2951. public function testSaveBelongsToManyJoinData()
  2952. {
  2953. $articles = TableRegistry::get('Articles');
  2954. $article = $articles->get(1, ['contain' => ['tags']]);
  2955. $data = [
  2956. 'tags' => [
  2957. ['id' => 1, '_joinData' => ['highlighted' => 1]],
  2958. ['id' => 3]
  2959. ]
  2960. ];
  2961. $article = $articles->patchEntity($article, $data);
  2962. $result = $articles->save($article);
  2963. $this->assertSame($result, $article);
  2964. }
  2965. /**
  2966. * Test to check that association condition are used when fetching existing
  2967. * records to decide which records to unlink.
  2968. *
  2969. * @return void
  2970. */
  2971. public function testPolymorphicBelongsToManySave()
  2972. {
  2973. $articles = TableRegistry::get('Articles');
  2974. $articles->belongsToMany('Tags', [
  2975. 'through' => 'PolymorphicTagged',
  2976. 'foreignKey' => 'foreign_key',
  2977. 'conditions' => [
  2978. 'PolymorphicTagged.foreign_model' => 'Articles'
  2979. ],
  2980. 'sort' => ['PolymorphicTagged.position' => 'ASC']
  2981. ]);
  2982. $articles->Tags->junction()->belongsTo('Tags');
  2983. $entity = $articles->get(1, ['contain' => ['Tags']]);
  2984. $data = [
  2985. 'id' => 1,
  2986. 'tags' => [
  2987. [
  2988. 'id' => 1,
  2989. '_joinData' => [
  2990. 'id' => 2,
  2991. 'foreign_model' => 'Articles',
  2992. 'position' => 2
  2993. ]
  2994. ],
  2995. [
  2996. 'id' => 2,
  2997. '_joinData' => [
  2998. 'foreign_model' => 'Articles',
  2999. 'position' => 1
  3000. ]
  3001. ]
  3002. ]
  3003. ];
  3004. $entity = $articles->patchEntity($entity, $data, ['associated' => ['Tags._joinData']]);
  3005. $entity = $articles->save($entity);
  3006. $expected = [
  3007. [
  3008. 'id' => 1,
  3009. 'tag_id' => 1,
  3010. 'foreign_key' => 1,
  3011. 'foreign_model' => 'Posts',
  3012. 'position' => 1
  3013. ],
  3014. [
  3015. 'id' => 2,
  3016. 'tag_id' => 1,
  3017. 'foreign_key' => 1,
  3018. 'foreign_model' => 'Articles',
  3019. 'position' => 2
  3020. ],
  3021. [
  3022. 'id' => 3,
  3023. 'tag_id' => 2,
  3024. 'foreign_key' => 1,
  3025. 'foreign_model' => 'Articles',
  3026. 'position' => 1
  3027. ]
  3028. ];
  3029. $result = TableRegistry::get('PolymorphicTagged')
  3030. ->find('all', ['sort' => ['id' => 'DESC']])
  3031. ->hydrate(false)
  3032. ->toArray();
  3033. $this->assertEquals($expected, $result);
  3034. }
  3035. /**
  3036. * Tests saving belongsToMany records can delete all links.
  3037. *
  3038. * @group save
  3039. * @return void
  3040. */
  3041. public function testSaveBelongsToManyDeleteAllLinks()
  3042. {
  3043. $table = TableRegistry::get('articles');
  3044. $table->belongsToMany('tags', [
  3045. 'saveStrategy' => 'replace',
  3046. ]);
  3047. $entity = $table->get(1, ['contain' => 'tags']);
  3048. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3049. $entity->tags = [];
  3050. $result = $table->save($entity);
  3051. $this->assertSame($result, $entity);
  3052. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  3053. $entity = $table->get(1, ['contain' => 'tags']);
  3054. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  3055. }
  3056. /**
  3057. * Tests saving belongsToMany records can delete some links.
  3058. *
  3059. * @group save
  3060. * @return void
  3061. */
  3062. public function testSaveBelongsToManyDeleteSomeLinks()
  3063. {
  3064. $table = TableRegistry::get('articles');
  3065. $table->belongsToMany('tags', [
  3066. 'saveStrategy' => 'replace',
  3067. ]);
  3068. $entity = $table->get(1, ['contain' => 'tags']);
  3069. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  3070. $tag = new \Cake\ORM\Entity([
  3071. 'id' => 2,
  3072. ]);
  3073. $entity->tags = [$tag];
  3074. $result = $table->save($entity);
  3075. $this->assertSame($result, $entity);
  3076. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  3077. $this->assertEquals($tag, $entity->tags[0]);
  3078. $entity = $table->get(1, ['contain' => 'tags']);
  3079. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  3080. $this->assertEquals($tag->id, $entity->tags[0]->id);
  3081. }
  3082. /**
  3083. * Test that belongsToMany ignores non-entity data.
  3084. *
  3085. * @return void
  3086. */
  3087. public function testSaveBelongsToManyIgnoreNonEntityData()
  3088. {
  3089. $articles = TableRegistry::get('articles');
  3090. $article = $articles->get(1, ['contain' => ['tags']]);
  3091. $article->tags = [
  3092. '_ids' => [2, 1]
  3093. ];
  3094. $result = $articles->save($article);
  3095. $this->assertSame($result, $article);
  3096. }
  3097. /**
  3098. * Tests that saving a persisted and clean entity will is a no-op
  3099. *
  3100. * @group save
  3101. * @return void
  3102. */
  3103. public function testSaveCleanEntity()
  3104. {
  3105. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  3106. $entity = new \Cake\ORM\Entity(
  3107. ['id' => 'foo'],
  3108. ['markNew' => false, 'markClean' => true]
  3109. );
  3110. $table->expects($this->never())->method('_processSave');
  3111. $this->assertSame($entity, $table->save($entity));
  3112. }
  3113. /**
  3114. * Integration test to show how to append a new tag to an article
  3115. *
  3116. * @group save
  3117. * @return void
  3118. */
  3119. public function testBelongsToManyIntegration()
  3120. {
  3121. $table = TableRegistry::get('articles');
  3122. $table->belongsToMany('tags');
  3123. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3124. $tags = $article->tags;
  3125. $this->assertNotEmpty($tags);
  3126. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  3127. $article->tags = $tags;
  3128. $this->assertSame($article, $table->save($article));
  3129. $tags = $article->tags;
  3130. $this->assertCount(3, $tags);
  3131. $this->assertFalse($tags[2]->isNew());
  3132. $this->assertEquals(4, $tags[2]->id);
  3133. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  3134. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  3135. }
  3136. /**
  3137. * Tests that it is possible to do a deep save and control what associations get saved,
  3138. * while having control of the options passed to each level of the save
  3139. *
  3140. * @group save
  3141. * @return void
  3142. */
  3143. public function testSaveDeepAssociationOptions()
  3144. {
  3145. $articles = $this->getMock(
  3146. '\Cake\ORM\Table',
  3147. ['_insert'],
  3148. [['table' => 'articles', 'connection' => $this->connection]]
  3149. );
  3150. $authors = $this->getMock(
  3151. '\Cake\ORM\Table',
  3152. ['_insert'],
  3153. [['table' => 'authors', 'connection' => $this->connection]]
  3154. );
  3155. $supervisors = $this->getMock(
  3156. '\Cake\ORM\Table',
  3157. ['_insert', 'validate'],
  3158. [[
  3159. 'table' => 'authors',
  3160. 'alias' => 'supervisors',
  3161. 'connection' => $this->connection
  3162. ]]
  3163. );
  3164. $tags = $this->getMock(
  3165. '\Cake\ORM\Table',
  3166. ['_insert'],
  3167. [['table' => 'tags', 'connection' => $this->connection]]
  3168. );
  3169. $articles->belongsTo('authors', ['targetTable' => $authors]);
  3170. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  3171. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  3172. $entity = new \Cake\ORM\Entity([
  3173. 'title' => 'bar',
  3174. 'author' => new \Cake\ORM\Entity([
  3175. 'name' => 'Juan',
  3176. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  3177. 'tags' => [
  3178. new \Cake\ORM\Entity(['name' => 'foo'])
  3179. ]
  3180. ]),
  3181. ]);
  3182. $entity->isNew(true);
  3183. $entity->author->isNew(true);
  3184. $entity->author->supervisor->isNew(true);
  3185. $entity->author->tags[0]->isNew(true);
  3186. $articles->expects($this->once())
  3187. ->method('_insert')
  3188. ->with($entity, ['title' => 'bar'])
  3189. ->will($this->returnValue($entity));
  3190. $authors->expects($this->once())
  3191. ->method('_insert')
  3192. ->with($entity->author, ['name' => 'Juan'])
  3193. ->will($this->returnValue($entity->author));
  3194. $supervisors->expects($this->once())
  3195. ->method('_insert')
  3196. ->with($entity->author->supervisor, ['name' => 'Marc'])
  3197. ->will($this->returnValue($entity->author->supervisor));
  3198. $tags->expects($this->never())->method('_insert');
  3199. $this->assertSame($entity, $articles->save($entity, [
  3200. 'associated' => [
  3201. 'authors' => [],
  3202. 'authors.supervisors' => [
  3203. 'atomic' => false,
  3204. 'associated' => false
  3205. ]
  3206. ]
  3207. ]));
  3208. }
  3209. /**
  3210. * Integration test for linking entities with belongsToMany
  3211. *
  3212. * @return void
  3213. */
  3214. public function testLinkBelongsToMany()
  3215. {
  3216. $table = TableRegistry::get('articles');
  3217. $table->belongsToMany('tags');
  3218. $tagsTable = TableRegistry::get('tags');
  3219. $source = ['source' => 'tags'];
  3220. $options = ['markNew' => false];
  3221. $article = new \Cake\ORM\Entity([
  3222. 'id' => 1,
  3223. ], $options);
  3224. $newTag = new \TestApp\Model\Entity\Tag([
  3225. 'name' => 'Foo'
  3226. ], $source);
  3227. $tags[] = new \TestApp\Model\Entity\Tag([
  3228. 'id' => 3
  3229. ], $options + $source);
  3230. $tags[] = $newTag;
  3231. $tagsTable->save($newTag);
  3232. $table->association('tags')->link($article, $tags);
  3233. $this->assertEquals($article->tags, $tags);
  3234. foreach ($tags as $tag) {
  3235. $this->assertFalse($tag->isNew());
  3236. }
  3237. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3238. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  3239. $this->assertEquals($article->tags[3], $tags[1]);
  3240. }
  3241. /**
  3242. * Integration test to show how to unlink a single record from a belongsToMany
  3243. *
  3244. * @return void
  3245. */
  3246. public function testUnlinkBelongsToMany()
  3247. {
  3248. $table = TableRegistry::get('articles');
  3249. $table->belongsToMany('tags');
  3250. $tagsTable = TableRegistry::get('tags');
  3251. $options = ['markNew' => false];
  3252. $article = $table->find('all')
  3253. ->where(['id' => 1])
  3254. ->contain(['tags'])->first();
  3255. $table->association('tags')->unlink($article, [$article->tags[0]]);
  3256. $this->assertCount(1, $article->tags);
  3257. $this->assertEquals(2, $article->tags[0]->get('id'));
  3258. $this->assertFalse($article->dirty('tags'));
  3259. }
  3260. /**
  3261. * Integration test to show how to unlink multiple records from a belongsToMany
  3262. *
  3263. * @return void
  3264. */
  3265. public function testUnlinkBelongsToManyMultiple()
  3266. {
  3267. $table = TableRegistry::get('articles');
  3268. $table->belongsToMany('tags');
  3269. $tagsTable = TableRegistry::get('tags');
  3270. $options = ['markNew' => false];
  3271. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3272. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  3273. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3274. $table->association('tags')->unlink($article, $tags);
  3275. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3276. $this->assertEmpty($left->tags);
  3277. }
  3278. /**
  3279. * Integration test to show how to unlink multiple records from a belongsToMany
  3280. * providing some of the joint
  3281. *
  3282. * @return void
  3283. */
  3284. public function testUnlinkBelongsToManyPassingJoint()
  3285. {
  3286. $table = TableRegistry::get('articles');
  3287. $table->belongsToMany('tags');
  3288. $tagsTable = TableRegistry::get('tags');
  3289. $options = ['markNew' => false];
  3290. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3291. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  3292. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3293. $tags[1]->_joinData = new \Cake\ORM\Entity([
  3294. 'article_id' => 1,
  3295. 'tag_id' => 2
  3296. ], $options);
  3297. $table->association('tags')->unlink($article, $tags);
  3298. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3299. $this->assertEmpty($left->tags);
  3300. }
  3301. /**
  3302. * Integration test to show how to replace records from a belongsToMany
  3303. *
  3304. * @return void
  3305. */
  3306. public function testReplacelinksBelongsToMany()
  3307. {
  3308. $table = TableRegistry::get('articles');
  3309. $table->belongsToMany('tags');
  3310. $tagsTable = TableRegistry::get('tags');
  3311. $options = ['markNew' => false];
  3312. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3313. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  3314. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  3315. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  3316. $table->association('tags')->replaceLinks($article, $tags);
  3317. $this->assertEquals(2, $article->tags[0]->id);
  3318. $this->assertEquals(3, $article->tags[1]->id);
  3319. $this->assertEquals(4, $article->tags[2]->id);
  3320. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3321. $this->assertCount(3, $article->tags);
  3322. $this->assertEquals(2, $article->tags[0]->id);
  3323. $this->assertEquals(3, $article->tags[1]->id);
  3324. $this->assertEquals(4, $article->tags[2]->id);
  3325. $this->assertEquals('foo', $article->tags[2]->name);
  3326. }
  3327. /**
  3328. * Integration test to show how remove all links from a belongsToMany
  3329. *
  3330. * @return void
  3331. */
  3332. public function testReplacelinksBelongsToManyWithEmpty()
  3333. {
  3334. $table = TableRegistry::get('articles');
  3335. $table->belongsToMany('tags');
  3336. $tagsTable = TableRegistry::get('tags');
  3337. $options = ['markNew' => false];
  3338. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3339. $tags = [];
  3340. $table->association('tags')->replaceLinks($article, $tags);
  3341. $this->assertSame($tags, $article->tags);
  3342. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3343. $this->assertEmpty($article->tags);
  3344. }
  3345. /**
  3346. * Integration test to show how to replace records from a belongsToMany
  3347. * passing the joint property along in the target entity
  3348. *
  3349. * @return void
  3350. */
  3351. public function testReplacelinksBelongsToManyWithJoint()
  3352. {
  3353. $table = TableRegistry::get('articles');
  3354. $table->belongsToMany('tags');
  3355. $tagsTable = TableRegistry::get('tags');
  3356. $options = ['markNew' => false];
  3357. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  3358. $tags[] = new \TestApp\Model\Entity\Tag([
  3359. 'id' => 2,
  3360. '_joinData' => new \Cake\ORM\Entity([
  3361. 'article_id' => 1,
  3362. 'tag_id' => 2,
  3363. ])
  3364. ], $options);
  3365. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  3366. $table->association('tags')->replaceLinks($article, $tags);
  3367. $this->assertSame($tags, $article->tags);
  3368. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  3369. $this->assertCount(2, $article->tags);
  3370. $this->assertEquals(2, $article->tags[0]->id);
  3371. $this->assertEquals(3, $article->tags[1]->id);
  3372. }
  3373. /**
  3374. * Tests that it is possible to call find with no arguments
  3375. *
  3376. * @return void
  3377. */
  3378. public function testSimplifiedFind()
  3379. {
  3380. $table = $this->getMock(
  3381. '\Cake\ORM\Table',
  3382. ['callFinder'],
  3383. [[
  3384. 'connection' => $this->connection,
  3385. 'schema' => ['id' => ['type' => 'integer']]
  3386. ]]
  3387. );
  3388. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  3389. $table->expects($this->once())->method('callFinder')
  3390. ->with('all', $query, []);
  3391. $table->find();
  3392. }
  3393. public function providerForTestGet()
  3394. {
  3395. return [
  3396. [ ['fields' => ['id']] ],
  3397. [ ['fields' => ['id'], 'cache' => false] ]
  3398. ];
  3399. }
  3400. /**
  3401. * Test that get() will use the primary key for searching and return the first
  3402. * entity found
  3403. *
  3404. * @dataProvider providerForTestGet
  3405. * @param array $options
  3406. * @return void
  3407. */
  3408. public function testGet($options)
  3409. {
  3410. $table = $this->getMock(
  3411. '\Cake\ORM\Table',
  3412. ['callFinder', 'query'],
  3413. [[
  3414. 'connection' => $this->connection,
  3415. 'schema' => [
  3416. 'id' => ['type' => 'integer'],
  3417. 'bar' => ['type' => 'integer'],
  3418. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  3419. ]
  3420. ]]
  3421. );
  3422. $query = $this->getMock(
  3423. '\Cake\ORM\Query',
  3424. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  3425. [$this->connection, $table]
  3426. );
  3427. $entity = new \Cake\ORM\Entity;
  3428. $table->expects($this->once())->method('query')
  3429. ->will($this->returnValue($query));
  3430. $table->expects($this->once())->method('callFinder')
  3431. ->with('all', $query, ['fields' => ['id']])
  3432. ->will($this->returnValue($query));
  3433. $query->expects($this->once())->method('where')
  3434. ->with([$table->alias() . '.bar' => 10])
  3435. ->will($this->returnSelf());
  3436. $query->expects($this->never())->method('cache');
  3437. $query->expects($this->once())->method('firstOrFail')
  3438. ->will($this->returnValue($entity));
  3439. $result = $table->get(10, $options);
  3440. $this->assertSame($entity, $result);
  3441. }
  3442. public function providerForTestGetWithCustomFinder()
  3443. {
  3444. return [
  3445. [ ['fields' => ['id'], 'finder' => 'custom'] ]
  3446. ];
  3447. }
  3448. /**
  3449. * Test that get() will call a custom finder.
  3450. *
  3451. * @dataProvider providerForTestGetWithCustomFinder
  3452. * @param array $options
  3453. * @return void
  3454. */
  3455. public function testGetWithCustomFinder($options)
  3456. {
  3457. $table = $this->getMock(
  3458. '\Cake\ORM\Table',
  3459. ['callFinder', 'query'],
  3460. [[
  3461. 'connection' => $this->connection,
  3462. 'schema' => [
  3463. 'id' => ['type' => 'integer'],
  3464. 'bar' => ['type' => 'integer'],
  3465. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  3466. ]
  3467. ]]
  3468. );
  3469. $query = $this->getMock(
  3470. '\Cake\ORM\Query',
  3471. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  3472. [$this->connection, $table]
  3473. );
  3474. $entity = new \Cake\ORM\Entity;
  3475. $table->expects($this->once())->method('query')
  3476. ->will($this->returnValue($query));
  3477. $table->expects($this->once())->method('callFinder')
  3478. ->with('custom', $query, ['fields' => ['id']])
  3479. ->will($this->returnValue($query));
  3480. $query->expects($this->once())->method('where')
  3481. ->with([$table->alias() . '.bar' => 10])
  3482. ->will($this->returnSelf());
  3483. $query->expects($this->never())->method('cache');
  3484. $query->expects($this->once())->method('firstOrFail')
  3485. ->will($this->returnValue($entity));
  3486. $result = $table->get(10, $options);
  3487. $this->assertSame($entity, $result);
  3488. }
  3489. public function providerForTestGetWithCache()
  3490. {
  3491. return [
  3492. [
  3493. ['fields' => ['id'], 'cache' => 'default'],
  3494. 'get:test.table_name[10]', 'default'
  3495. ],
  3496. [
  3497. ['fields' => ['id'], 'cache' => 'default', 'key' => 'custom_key'],
  3498. 'custom_key', 'default'
  3499. ]
  3500. ];
  3501. }
  3502. /**
  3503. * Test that get() will use the cache.
  3504. *
  3505. * @dataProvider providerForTestGetWithCache
  3506. * @param array $options
  3507. * @param string $cacheKey
  3508. * @param string $cacheConfig
  3509. * @return void
  3510. */
  3511. public function testGetWithCache($options, $cacheKey, $cacheConfig)
  3512. {
  3513. $table = $this->getMock(
  3514. '\Cake\ORM\Table',
  3515. ['callFinder', 'query'],
  3516. [[
  3517. 'connection' => $this->connection,
  3518. 'schema' => [
  3519. 'id' => ['type' => 'integer'],
  3520. 'bar' => ['type' => 'integer'],
  3521. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  3522. ]
  3523. ]]
  3524. );
  3525. $table->table('table_name');
  3526. $query = $this->getMock(
  3527. '\Cake\ORM\Query',
  3528. ['addDefaultTypes', 'firstOrFail', 'where', 'cache'],
  3529. [$this->connection, $table]
  3530. );
  3531. $entity = new \Cake\ORM\Entity;
  3532. $table->expects($this->once())->method('query')
  3533. ->will($this->returnValue($query));
  3534. $table->expects($this->once())->method('callFinder')
  3535. ->with('all', $query, ['fields' => ['id']])
  3536. ->will($this->returnValue($query));
  3537. $query->expects($this->once())->method('where')
  3538. ->with([$table->alias() . '.bar' => 10])
  3539. ->will($this->returnSelf());
  3540. $query->expects($this->once())->method('cache')
  3541. ->with($cacheKey, $cacheConfig)
  3542. ->will($this->returnSelf());
  3543. $query->expects($this->once())->method('firstOrFail')
  3544. ->will($this->returnValue($entity));
  3545. $result = $table->get(10, $options);
  3546. $this->assertSame($entity, $result);
  3547. }
  3548. /**
  3549. * Tests that get() will throw an exception if the record was not found
  3550. *
  3551. * @expectedException Cake\Datasource\Exception\RecordNotFoundException
  3552. * @expectedExceptionMessage Record not found in table "articles"
  3553. * @return void
  3554. */
  3555. public function testGetNotFoundException()
  3556. {
  3557. $table = new Table([
  3558. 'name' => 'Articles',
  3559. 'connection' => $this->connection,
  3560. 'table' => 'articles',
  3561. ]);
  3562. $table->get(10);
  3563. }
  3564. /**
  3565. * Test that an exception is raised when there are not enough keys.
  3566. *
  3567. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  3568. * @expectedExceptionMessage Record not found in table "articles" with primary key [NULL]
  3569. * @return void
  3570. */
  3571. public function testGetExceptionOnNoData()
  3572. {
  3573. $table = new Table([
  3574. 'name' => 'Articles',
  3575. 'connection' => $this->connection,
  3576. 'table' => 'articles',
  3577. ]);
  3578. $table->get(null);
  3579. }
  3580. /**
  3581. * Test that an exception is raised when there are too many keys.
  3582. *
  3583. * @expectedException Cake\Datasource\Exception\InvalidPrimaryKeyException
  3584. * @expectedExceptionMessage Record not found in table "articles" with primary key [1, 'two']
  3585. * @return void
  3586. */
  3587. public function testGetExceptionOnTooMuchData()
  3588. {
  3589. $table = new Table([
  3590. 'name' => 'Articles',
  3591. 'connection' => $this->connection,
  3592. 'table' => 'articles',
  3593. ]);
  3594. $table->get([1, 'two']);
  3595. }
  3596. /**
  3597. * Tests that patchEntity delegates the task to the marshaller and passed
  3598. * all associations
  3599. *
  3600. * @return void
  3601. */
  3602. public function testPatchEntity()
  3603. {
  3604. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  3605. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  3606. $table->belongsTo('users');
  3607. $table->hasMany('articles');
  3608. $table->expects($this->once())->method('marshaller')
  3609. ->will($this->returnValue($marshaller));
  3610. $entity = new \Cake\ORM\Entity;
  3611. $data = ['foo' => 'bar'];
  3612. $marshaller->expects($this->once())
  3613. ->method('merge')
  3614. ->with($entity, $data, ['associated' => ['users', 'articles']])
  3615. ->will($this->returnValue($entity));
  3616. $table->patchEntity($entity, $data);
  3617. }
  3618. /**
  3619. * Tests that patchEntities delegates the task to the marshaller and passed
  3620. * all associations
  3621. *
  3622. * @return void
  3623. */
  3624. public function testPatchEntities()
  3625. {
  3626. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  3627. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  3628. $table->belongsTo('users');
  3629. $table->hasMany('articles');
  3630. $table->expects($this->once())->method('marshaller')
  3631. ->will($this->returnValue($marshaller));
  3632. $entities = [new \Cake\ORM\Entity];
  3633. $data = [['foo' => 'bar']];
  3634. $marshaller->expects($this->once())
  3635. ->method('mergeMany')
  3636. ->with($entities, $data, ['associated' => ['users', 'articles']])
  3637. ->will($this->returnValue($entities));
  3638. $table->patchEntities($entities, $data);
  3639. }
  3640. /**
  3641. * Tests __debugInfo
  3642. *
  3643. * @return void
  3644. */
  3645. public function testDebugInfo()
  3646. {
  3647. $articles = TableRegistry::get('articles');
  3648. $articles->addBehavior('Timestamp');
  3649. $result = $articles->__debugInfo();
  3650. $expected = [
  3651. 'registryAlias' => 'articles',
  3652. 'table' => 'articles',
  3653. 'alias' => 'articles',
  3654. 'entityClass' => 'TestApp\Model\Entity\Article',
  3655. 'associations' => ['authors', 'tags', 'articlestags'],
  3656. 'behaviors' => ['Timestamp'],
  3657. 'defaultConnection' => 'default',
  3658. 'connectionName' => 'test'
  3659. ];
  3660. $this->assertEquals($expected, $result);
  3661. $articles = TableRegistry::get('Foo.Articles');
  3662. $result = $articles->__debugInfo();
  3663. $expected = [
  3664. 'registryAlias' => 'Foo.Articles',
  3665. 'table' => 'articles',
  3666. 'alias' => 'Articles',
  3667. 'entityClass' => '\Cake\ORM\Entity',
  3668. 'associations' => [],
  3669. 'behaviors' => [],
  3670. 'defaultConnection' => 'default',
  3671. 'connectionName' => 'test'
  3672. ];
  3673. $this->assertEquals($expected, $result);
  3674. }
  3675. /**
  3676. * Test the findOrCreate method.
  3677. *
  3678. * @return void
  3679. */
  3680. public function testFindOrCreate()
  3681. {
  3682. $articles = TableRegistry::get('Articles');
  3683. $article = $articles->findOrCreate(['title' => 'Not there'], function ($article) {
  3684. $article->body = 'New body';
  3685. });
  3686. $this->assertFalse($article->isNew());
  3687. $this->assertNotNull($article->id);
  3688. $this->assertEquals('Not there', $article->title);
  3689. $this->assertEquals('New body', $article->body);
  3690. $article = $articles->findOrCreate(['title' => 'Not there']);
  3691. $this->assertFalse($article->isNew());
  3692. $this->assertNotNull($article->id);
  3693. $this->assertEquals('Not there', $article->title);
  3694. $article = $articles->findOrCreate(['title' => 'First Article'], function ($article) {
  3695. $this->fail('Should not be called for existing entities.');
  3696. });
  3697. $this->assertFalse($article->isNew());
  3698. $this->assertNotNull($article->id);
  3699. $this->assertEquals('First Article', $article->title);
  3700. $article = $articles->findOrCreate(
  3701. ['author_id' => 2, 'title' => 'First Article'],
  3702. function ($article) {
  3703. $article->set(['published' => 'N', 'body' => 'New body']);
  3704. }
  3705. );
  3706. $this->assertFalse($article->isNew());
  3707. $this->assertNotNull($article->id);
  3708. $this->assertEquals('First Article', $article->title);
  3709. $this->assertEquals('New body', $article->body);
  3710. $this->assertEquals('N', $article->published);
  3711. $this->assertEquals(2, $article->author_id);
  3712. }
  3713. /**
  3714. * Test that creating a table fires the initialize event.
  3715. *
  3716. * @return void
  3717. */
  3718. public function testInitializeEvent()
  3719. {
  3720. $count = 0;
  3721. $cb = function ($event) use (&$count) {
  3722. $count++;
  3723. };
  3724. EventManager::instance()->on('Model.initialize', $cb);
  3725. $articles = TableRegistry::get('Articles');
  3726. $this->assertEquals(1, $count, 'Callback should be called');
  3727. EventManager::instance()->detach($cb, 'Model.initialize');
  3728. }
  3729. /**
  3730. * Tests the hasFinder method
  3731. *
  3732. * @return void
  3733. */
  3734. public function testHasFinder()
  3735. {
  3736. $table = TableRegistry::get('articles');
  3737. $table->addBehavior('Sluggable');
  3738. $this->assertTrue($table->hasFinder('list'));
  3739. $this->assertTrue($table->hasFinder('noSlug'));
  3740. $this->assertFalse($table->hasFinder('noFind'));
  3741. }
  3742. /**
  3743. * Tests that calling validator() trigger the buildValidator event
  3744. *
  3745. * @return void
  3746. */
  3747. public function testBuildValidatorEvent()
  3748. {
  3749. $count = 0;
  3750. $cb = function ($event) use (&$count) {
  3751. $count++;
  3752. };
  3753. EventManager::instance()->on('Model.buildValidator', $cb);
  3754. $articles = TableRegistry::get('Articles');
  3755. $articles->validator();
  3756. $this->assertEquals(1, $count, 'Callback should be called');
  3757. $articles->validator();
  3758. $this->assertEquals(1, $count, 'Callback should be called only once');
  3759. }
  3760. /**
  3761. * Tests the validateUnique method with different combinations
  3762. *
  3763. * @return void
  3764. */
  3765. public function testValidateUnique()
  3766. {
  3767. $table = TableRegistry::get('Users');
  3768. $validator = new Validator;
  3769. $validator->add('username', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
  3770. $validator->provider('table', $table);
  3771. $data = ['username' => 'larry'];
  3772. $this->assertNotEmpty($validator->errors($data));
  3773. $data = ['username' => 'jose'];
  3774. $this->assertEmpty($validator->errors($data));
  3775. $data = ['username' => 'larry', 'id' => 3];
  3776. $this->assertEmpty($validator->errors($data, false));
  3777. $data = ['username' => 'larry', 'id' => 3];
  3778. $this->assertNotEmpty($validator->errors($data));
  3779. $data = ['username' => 'larry'];
  3780. $this->assertNotEmpty($validator->errors($data, false));
  3781. $validator->add('username', 'unique', [
  3782. 'rule' => 'validateUnique', 'provider' => 'table'
  3783. ]);
  3784. $data = ['username' => 'larry'];
  3785. $this->assertNotEmpty($validator->errors($data, false));
  3786. }
  3787. /**
  3788. * Tests the validateUnique method with scope
  3789. *
  3790. * @return void
  3791. */
  3792. public function testValidateUniqueScope()
  3793. {
  3794. $table = TableRegistry::get('Users');
  3795. $validator = new Validator;
  3796. $validator->add('username', 'unique', [
  3797. 'rule' => ['validateUnique', ['derp' => 'erp', 'scope' => 'id']],
  3798. 'provider' => 'table'
  3799. ]);
  3800. $validator->provider('table', $table);
  3801. $data = ['username' => 'larry', 'id' => 3];
  3802. $this->assertNotEmpty($validator->errors($data));
  3803. $data = ['username' => 'larry', 'id' => 1];
  3804. $this->assertEmpty($validator->errors($data));
  3805. $data = ['username' => 'jose'];
  3806. $this->assertEmpty($validator->errors($data));
  3807. }
  3808. /**
  3809. * Tests that the callbacks receive the expected types of arguments.
  3810. *
  3811. * @return void
  3812. */
  3813. public function testCallbackArgumentTypes()
  3814. {
  3815. $table = TableRegistry::get('articles');
  3816. $table->belongsTo('authors');
  3817. $eventManager = $table->eventManager();
  3818. $associationBeforeFindCount = 0;
  3819. $table->association('authors')->target()->eventManager()->on(
  3820. 'Model.beforeFind',
  3821. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$associationBeforeFindCount) {
  3822. $this->assertTrue(is_bool($primary));
  3823. $associationBeforeFindCount ++;
  3824. }
  3825. );
  3826. $beforeFindCount = 0;
  3827. $eventManager->on(
  3828. 'Model.beforeFind',
  3829. function (Event $event, Query $query, ArrayObject $options, $primary) use (&$beforeFindCount) {
  3830. $this->assertTrue(is_bool($primary));
  3831. $beforeFindCount ++;
  3832. }
  3833. );
  3834. $table->find()->contain('authors')->first();
  3835. $this->assertEquals(1, $associationBeforeFindCount);
  3836. $this->assertEquals(1, $beforeFindCount);
  3837. $buildValidatorCount = 0;
  3838. $eventManager->on(
  3839. 'Model.buildValidator',
  3840. $callback = function (Event $event, Validator $validator, $name) use (&$buildValidatorCount) {
  3841. $this->assertTrue(is_string($name));
  3842. $buildValidatorCount ++;
  3843. }
  3844. );
  3845. $table->validator();
  3846. $this->assertEquals(1, $buildValidatorCount);
  3847. $buildRulesCount =
  3848. $beforeRulesCount =
  3849. $afterRulesCount =
  3850. $beforeSaveCount =
  3851. $afterSaveCount = 0;
  3852. $eventManager->on(
  3853. 'Model.buildRules',
  3854. function (Event $event, RulesChecker $rules) use (&$buildRulesCount) {
  3855. $buildRulesCount ++;
  3856. }
  3857. );
  3858. $eventManager->on(
  3859. 'Model.beforeRules',
  3860. function (Event $event, Entity $entity, ArrayObject $options, $operation) use (&$beforeRulesCount) {
  3861. $this->assertTrue(is_string($operation));
  3862. $beforeRulesCount ++;
  3863. }
  3864. );
  3865. $eventManager->on(
  3866. 'Model.afterRules',
  3867. function (Event $event, Entity $entity, ArrayObject $options, $result, $operation) use (&$afterRulesCount) {
  3868. $this->assertTrue(is_bool($result));
  3869. $this->assertTrue(is_string($operation));
  3870. $afterRulesCount ++;
  3871. }
  3872. );
  3873. $eventManager->on(
  3874. 'Model.beforeSave',
  3875. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeSaveCount) {
  3876. $beforeSaveCount ++;
  3877. }
  3878. );
  3879. $eventManager->on(
  3880. 'Model.afterSave',
  3881. $afterSaveCallback = function (Event $event, Entity $entity, ArrayObject $options) use (&$afterSaveCount) {
  3882. $afterSaveCount ++;
  3883. }
  3884. );
  3885. $entity = new Entity(['title' => 'Title']);
  3886. $this->assertNotFalse($table->save($entity));
  3887. $this->assertEquals(1, $buildRulesCount);
  3888. $this->assertEquals(1, $beforeRulesCount);
  3889. $this->assertEquals(1, $afterRulesCount);
  3890. $this->assertEquals(1, $beforeSaveCount);
  3891. $this->assertEquals(1, $afterSaveCount);
  3892. $beforeDeleteCount =
  3893. $afterDeleteCount = 0;
  3894. $eventManager->on(
  3895. 'Model.beforeDelete',
  3896. function (Event $event, Entity $entity, ArrayObject $options) use (&$beforeDeleteCount) {
  3897. $beforeDeleteCount ++;
  3898. }
  3899. );
  3900. $eventManager->on(
  3901. 'Model.afterDelete',
  3902. function (Event $event, Entity $entity, ArrayObject $options) use (&$afterDeleteCount) {
  3903. $afterDeleteCount ++;
  3904. }
  3905. );
  3906. $this->assertTrue($table->delete($entity, ['checkRules' => false]));
  3907. $this->assertEquals(1, $beforeDeleteCount);
  3908. $this->assertEquals(1, $afterDeleteCount);
  3909. }
  3910. /**
  3911. * Tests that calling newEntity() on a table sets the right source alias
  3912. *
  3913. * @return void
  3914. */
  3915. public function testEntitySource()
  3916. {
  3917. $table = TableRegistry::get('Articles');
  3918. $this->assertEquals('Articles', $table->newEntity()->source());
  3919. Plugin::load('TestPlugin');
  3920. $table = TableRegistry::get('TestPlugin.Comments');
  3921. $this->assertEquals('TestPlugin.Comments', $table->newEntity()->source());
  3922. }
  3923. /**
  3924. * Tests that passing a coned entity that was marked as new to save() will
  3925. * actaully save it as a new entity
  3926. *
  3927. * @group save
  3928. * @return void
  3929. */
  3930. public function testSaveWithClonedEntity()
  3931. {
  3932. $table = TableRegistry::get('Articles');
  3933. $article = $table->get(1);
  3934. $cloned = clone $article;
  3935. $cloned->unsetProperty('id');
  3936. $cloned->isNew(true);
  3937. $this->assertSame($cloned, $table->save($cloned));
  3938. $this->assertEquals(
  3939. $article->extract(['title', 'author_id']),
  3940. $cloned->extract(['title', 'author_id'])
  3941. );
  3942. $this->assertEquals(4, $cloned->id);
  3943. }
  3944. /**
  3945. * Tests that the _ids notation can be used for HasMany
  3946. *
  3947. * @return void
  3948. */
  3949. public function testSaveHasManyWithIds()
  3950. {
  3951. $data = [
  3952. 'username' => 'lux',
  3953. 'password' => 'passphrase',
  3954. 'comments' => [
  3955. '_ids' => [1, 2]
  3956. ]
  3957. ];
  3958. $userTable = TableRegistry::get('Users');
  3959. $userTable->hasMany('Comments');
  3960. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  3961. $retrievedUser = $userTable->find('all')->where(['id' => $savedUser->id])->contain(['Comments'])->first();
  3962. $this->assertEquals($savedUser->comments[0]->user_id, $retrievedUser->comments[0]->user_id);
  3963. $this->assertEquals($savedUser->comments[1]->user_id, $retrievedUser->comments[1]->user_id);
  3964. }
  3965. /**
  3966. * Tests that on second save, entities for the has many relation are not marked
  3967. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  3968. * for a cleaner transaction log
  3969. *
  3970. * @return void
  3971. */
  3972. public function testSaveHasManyNoWasteSave()
  3973. {
  3974. $data = [
  3975. 'username' => 'lux',
  3976. 'password' => 'passphrase',
  3977. 'comments' => [
  3978. '_ids' => [1, 2]
  3979. ]
  3980. ];
  3981. $userTable = TableRegistry::get('Users');
  3982. $userTable->hasMany('Comments');
  3983. $savedUser = $userTable->save($userTable->newEntity($data, ['associated' => ['Comments']]));
  3984. $counter = 0;
  3985. $userTable->Comments
  3986. ->eventManager()
  3987. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  3988. if ($entity->dirty()) {
  3989. $counter++;
  3990. }
  3991. });
  3992. $savedUser->comments[] = $userTable->Comments->get(5);
  3993. $this->assertCount(3, $savedUser->comments);
  3994. $savedUser->dirty('comments', true);
  3995. $userTable->save($savedUser);
  3996. $this->assertEquals(1, $counter);
  3997. }
  3998. /**
  3999. * Tests that on second save, entities for the belongsToMany relation are not marked
  4000. * as dirty unnecessarily. This helps avoid wasteful database statements and makes
  4001. * for a cleaner transaction log
  4002. *
  4003. * @return void
  4004. */
  4005. public function testSaveBelongsToManyNoWasteSave()
  4006. {
  4007. $data = [
  4008. 'title' => 'foo',
  4009. 'body' => 'bar',
  4010. 'tags' => [
  4011. '_ids' => [1, 2]
  4012. ]
  4013. ];
  4014. $table = TableRegistry::get('Articles');
  4015. $table->belongsToMany('Tags');
  4016. $article = $table->save($table->newEntity($data, ['associated' => ['Tags']]));
  4017. $counter = 0;
  4018. $table->Tags->junction()
  4019. ->eventManager()
  4020. ->on('Model.afterSave', function ($event, $entity) use (&$counter) {
  4021. if ($entity->dirty()) {
  4022. $counter++;
  4023. }
  4024. });
  4025. $article->tags[] = $table->Tags->get(3);
  4026. $this->assertCount(3, $article->tags);
  4027. $article->dirty('tags', true);
  4028. $table->save($article);
  4029. $this->assertEquals(1, $counter);
  4030. }
  4031. /**
  4032. * Tests that after saving then entity contains the right primary
  4033. * key casted to the right type
  4034. *
  4035. * @group save
  4036. * @return void
  4037. */
  4038. public function testSaveCorrectPrimaryKeyType()
  4039. {
  4040. $entity = new Entity([
  4041. 'username' => 'superuser',
  4042. 'created' => new Time('2013-10-10 00:00'),
  4043. 'updated' => new Time('2013-10-10 00:00')
  4044. ], ['markNew' => true]);
  4045. $table = TableRegistry::get('Users');
  4046. $this->assertSame($entity, $table->save($entity));
  4047. $this->assertSame(self::$nextUserId, $entity->id);
  4048. }
  4049. /**
  4050. * Tests the loadInto() method
  4051. *
  4052. * @return void
  4053. */
  4054. public function testLoadIntoEntity()
  4055. {
  4056. $table = TableRegistry::get('Authors');
  4057. $table->hasMany('SiteArticles');
  4058. $articles = $table->hasMany('Articles');
  4059. $articles->belongsToMany('Tags');
  4060. $entity = $table->get(1);
  4061. $result = $table->loadInto($entity, ['SiteArticles', 'Articles.Tags']);
  4062. $this->assertSame($entity, $result);
  4063. $expected = $table->get(1, ['contain' => ['SiteArticles', 'Articles.Tags']]);
  4064. $this->assertEquals($expected, $result);
  4065. }
  4066. /**
  4067. * Tests that it is possible to pass conditions and fields to loadInto()
  4068. *
  4069. * @return void
  4070. */
  4071. public function testLoadIntoWithConditions()
  4072. {
  4073. $table = TableRegistry::get('Authors');
  4074. $table->hasMany('SiteArticles');
  4075. $articles = $table->hasMany('Articles');
  4076. $articles->belongsToMany('Tags');
  4077. $entity = $table->get(1);
  4078. $options = [
  4079. 'SiteArticles' => ['fields' => ['title', 'author_id']],
  4080. 'Articles.Tags' => function ($q) {
  4081. return $q->where(['Tags.name' => 'tag2']);
  4082. }
  4083. ];
  4084. $result = $table->loadInto($entity, $options);
  4085. $this->assertSame($entity, $result);
  4086. $expected = $table->get(1, ['contain' => $options]);
  4087. $this->assertEquals($expected, $result);
  4088. }
  4089. /**
  4090. * Tests loadInto() with a belongsTo association
  4091. *
  4092. * @return void
  4093. */
  4094. public function testLoadBelognsTo()
  4095. {
  4096. $table = TableRegistry::get('Articles');
  4097. $table->belongsTo('Authors');
  4098. $entity = $table->get(2);
  4099. $result = $table->loadInto($entity, ['Authors']);
  4100. $this->assertSame($entity, $result);
  4101. $expected = $table->get(2, ['contain' => ['Authors']]);
  4102. $this->assertEquals($expected, $entity);
  4103. }
  4104. /**
  4105. * Tests that it is possible to post-load associations for many entities at
  4106. * the same time
  4107. *
  4108. * @return void
  4109. */
  4110. public function testLoadIntoMany()
  4111. {
  4112. $table = TableRegistry::get('Authors');
  4113. $table->hasMany('SiteArticles');
  4114. $articles = $table->hasMany('Articles');
  4115. $articles->belongsToMany('Tags');
  4116. $entities = $table->find()->compile();
  4117. $contain = ['SiteArticles', 'Articles.Tags'];
  4118. $result = $table->loadInto($entities, $contain);
  4119. foreach ($entities as $k => $v) {
  4120. $this->assertSame($v, $result[$k]);
  4121. }
  4122. $expected = $table->find()->contain($contain)->toList();
  4123. $this->assertEquals($expected, $result);
  4124. }
  4125. /**
  4126. * Helper method to skip tests when connection is SQLServer.
  4127. *
  4128. * @return void
  4129. */
  4130. public function skipIfSqlServer()
  4131. {
  4132. $this->skipIf(
  4133. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  4134. 'SQLServer does not support the requirements of this test.'
  4135. );
  4136. }
  4137. }