TableTest.php 102 KB

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