TableTest.php 128 KB

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