TableTest.php 91 KB

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