TableTest.php 94 KB

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