TableTest.php 101 KB

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