TableTest.php 130 KB

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