TableTest.php 92 KB

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