TableTest.php 93 KB

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