TableTest.php 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404
  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->eventManager()->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->eventManager()->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->eventManager()->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->eventManager()->attach($listener1, 'Model.beforeSave');
  1137. $table->eventManager()->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->eventManager()->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->eventManager()->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->eventManager()->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->eventManager()->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->eventManager()->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->eventManager()->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->eventManager()->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. * Tests using a custom validation object when saving and saving associations
  1898. *
  1899. * @return void
  1900. */
  1901. public function testSaveWithDifferentValidatorAndAssociations() {
  1902. $entity = new \Cake\ORM\Entity([
  1903. 'title' => 'foo',
  1904. 'body' => 'bar',
  1905. 'author' => new \Cake\ORM\Entity([
  1906. 'name' => 'Susan'
  1907. ])
  1908. ]);
  1909. $table = TableRegistry::get('articles');
  1910. $table->belongsTo('authors');
  1911. $validator = (new Validator)->validatePresence('body');
  1912. $table->validator('custom', $validator);
  1913. $validator2 = (new Validator)->validatePresence('thing');
  1914. $table->authors->validator('default', $validator2);
  1915. $this->assertFalse($table->save($entity, ['validate' => 'custom']), 'default was not used');
  1916. $this->assertNotEmpty($entity->author->errors('thing'));
  1917. }
  1918. /**
  1919. * Test magic findByXX method.
  1920. *
  1921. * @return void
  1922. */
  1923. public function testMagicFindDefaultToAll() {
  1924. $table = TableRegistry::get('Users');
  1925. $result = $table->findByUsername('garrett');
  1926. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1927. $expected = new QueryExpression(['username' => 'garrett'], $this->usersTypeMap);
  1928. $this->assertEquals($expected, $result->clause('where'));
  1929. }
  1930. /**
  1931. * Test magic findByXX errors on missing arguments.
  1932. *
  1933. * @expectedException \Cake\Error\Exception
  1934. * @expectedExceptionMessage Not enough arguments to magic finder. Got 0 required 1
  1935. * @return void
  1936. */
  1937. public function testMagicFindError() {
  1938. $table = TableRegistry::get('Users');
  1939. $table->findByUsername();
  1940. }
  1941. /**
  1942. * Test magic findByXX errors on missing arguments.
  1943. *
  1944. * @expectedException \Cake\Error\Exception
  1945. * @expectedExceptionMessage Not enough arguments to magic finder. Got 1 required 2
  1946. * @return void
  1947. */
  1948. public function testMagicFindErrorMissingField() {
  1949. $table = TableRegistry::get('Users');
  1950. $table->findByUsernameAndId('garrett');
  1951. }
  1952. /**
  1953. * Test magic findByXX errors when there is a mix of or & and.
  1954. *
  1955. * @expectedException \Cake\Error\Exception
  1956. * @expectedExceptionMessage Cannot mix "and" & "or" in a magic finder. Use find() instead.
  1957. * @return void
  1958. */
  1959. public function testMagicFindErrorMixOfOperators() {
  1960. $table = TableRegistry::get('Users');
  1961. $table->findByUsernameAndIdOrPassword('garrett', 1, 'sekret');
  1962. }
  1963. /**
  1964. * Test magic findByXX method.
  1965. *
  1966. * @return void
  1967. */
  1968. public function testMagicFindFirstAnd() {
  1969. $table = TableRegistry::get('Users');
  1970. $result = $table->findByUsernameAndId('garrett', 4);
  1971. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1972. $expected = new QueryExpression(['username' => 'garrett', 'id' => 4], $this->usersTypeMap);
  1973. $this->assertEquals($expected, $result->clause('where'));
  1974. }
  1975. /**
  1976. * Test magic findByXX method.
  1977. *
  1978. * @return void
  1979. */
  1980. public function testMagicFindFirstOr() {
  1981. $table = TableRegistry::get('Users');
  1982. $result = $table->findByUsernameOrId('garrett', 4);
  1983. $this->assertInstanceOf('Cake\ORM\Query', $result);
  1984. $expected = new QueryExpression([], $this->usersTypeMap);
  1985. $expected->add([
  1986. 'OR' => [
  1987. 'username' => 'garrett',
  1988. 'id' => 4
  1989. ]]
  1990. );
  1991. $this->assertEquals($expected, $result->clause('where'));
  1992. }
  1993. /**
  1994. * Test magic findAllByXX method.
  1995. *
  1996. * @return void
  1997. */
  1998. public function testMagicFindAll() {
  1999. $table = TableRegistry::get('Articles');
  2000. $result = $table->findAllByAuthorId(1);
  2001. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2002. $this->assertNull($result->clause('limit'));
  2003. $expected = new QueryExpression(['author_id' => 1], $this->articlesTypeMap);
  2004. $this->assertEquals($expected, $result->clause('where'));
  2005. }
  2006. /**
  2007. * Test magic findAllByXX method.
  2008. *
  2009. * @return void
  2010. */
  2011. public function testMagicFindAllAnd() {
  2012. $table = TableRegistry::get('Users');
  2013. $result = $table->findAllByAuthorIdAndPublished(1, 'Y');
  2014. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2015. $this->assertNull($result->clause('limit'));
  2016. $expected = new QueryExpression(
  2017. ['author_id' => 1, 'published' => 'Y'],
  2018. $this->usersTypeMap
  2019. );
  2020. $this->assertEquals($expected, $result->clause('where'));
  2021. }
  2022. /**
  2023. * Test magic findAllByXX method.
  2024. *
  2025. * @return void
  2026. */
  2027. public function testMagicFindAllOr() {
  2028. $table = TableRegistry::get('Users');
  2029. $result = $table->findAllByAuthorIdOrPublished(1, 'Y');
  2030. $this->assertInstanceOf('Cake\ORM\Query', $result);
  2031. $this->assertNull($result->clause('limit'));
  2032. $expected = new QueryExpression();
  2033. $expected->typeMap()->defaults([
  2034. 'Users.id' => 'integer',
  2035. 'id' => 'integer',
  2036. 'Users.username' => 'string',
  2037. 'username' => 'string',
  2038. 'Users.password' => 'string',
  2039. 'password' => 'string',
  2040. 'Users.created' => 'timestamp',
  2041. 'created' => 'timestamp',
  2042. 'Users.updated' => 'timestamp',
  2043. 'updated' => 'timestamp',
  2044. ]);
  2045. $expected->add(
  2046. ['or' => ['author_id' => 1, 'published' => 'Y']]
  2047. );
  2048. $this->assertEquals($expected, $result->clause('where'));
  2049. $this->assertNull($result->clause('order'));
  2050. }
  2051. /**
  2052. * Test the behavior method.
  2053. *
  2054. * @return void
  2055. */
  2056. public function testBehaviorIntrospection() {
  2057. $table = TableRegistry::get('users');
  2058. $table->addBehavior('Timestamp');
  2059. $this->assertTrue($table->hasBehavior('Timestamp'), 'should be true on loaded behavior');
  2060. $this->assertFalse($table->hasBehavior('Tree'), 'should be false on unloaded behavior');
  2061. }
  2062. /**
  2063. * Tests saving belongsTo association
  2064. *
  2065. * @group save
  2066. * @return void
  2067. */
  2068. public function testSaveBelongsTo() {
  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. $this->assertSame($entity, $table->save($entity));
  2079. $this->assertFalse($entity->isNew());
  2080. $this->assertFalse($entity->author->isNew());
  2081. $this->assertEquals(5, $entity->author->id);
  2082. $this->assertEquals(5, $entity->get('author_id'));
  2083. }
  2084. /**
  2085. * Tests saving belongsTo association and get a validation error
  2086. *
  2087. * @group save
  2088. * @return void
  2089. */
  2090. public function testsSaveBelongsToWithValidationError() {
  2091. $entity = new \Cake\ORM\Entity([
  2092. 'title' => 'A Title',
  2093. 'body' => 'A body'
  2094. ]);
  2095. $entity->author = new \Cake\ORM\Entity([
  2096. 'name' => 'Jose'
  2097. ]);
  2098. $table = TableRegistry::get('articles');
  2099. $table->belongsTo('authors');
  2100. $table->association('authors')
  2101. ->target()
  2102. ->validator()
  2103. ->add('name', 'num', ['rule' => 'numeric']);
  2104. $this->assertFalse($table->save($entity));
  2105. $this->assertTrue($entity->isNew());
  2106. $this->assertTrue($entity->author->isNew());
  2107. $this->assertNull($entity->get('author_id'));
  2108. $this->assertNotEmpty($entity->author->errors('name'));
  2109. }
  2110. /**
  2111. * Tests saving hasOne association
  2112. *
  2113. * @group save
  2114. * @return void
  2115. */
  2116. public function testSaveHasOne() {
  2117. $entity = new \Cake\ORM\Entity([
  2118. 'name' => 'Jose'
  2119. ]);
  2120. $entity->article = new \Cake\ORM\Entity([
  2121. 'title' => 'A Title',
  2122. 'body' => 'A body'
  2123. ]);
  2124. $table = TableRegistry::get('authors');
  2125. $table->hasOne('articles');
  2126. $this->assertSame($entity, $table->save($entity));
  2127. $this->assertFalse($entity->isNew());
  2128. $this->assertFalse($entity->article->isNew());
  2129. $this->assertEquals(4, $entity->article->id);
  2130. $this->assertEquals(5, $entity->article->get('author_id'));
  2131. $this->assertFalse($entity->article->dirty('author_id'));
  2132. }
  2133. /**
  2134. * Tests saving associations only saves associations
  2135. * if they are entities.
  2136. *
  2137. * @group save
  2138. * @return void
  2139. */
  2140. public function testSaveOnlySaveAssociatedEntities() {
  2141. $entity = new \Cake\ORM\Entity([
  2142. 'name' => 'Jose'
  2143. ]);
  2144. // Not an entity.
  2145. $entity->article = [
  2146. 'title' => 'A Title',
  2147. 'body' => 'A body'
  2148. ];
  2149. $table = TableRegistry::get('authors');
  2150. $table->hasOne('articles');
  2151. $this->assertSame($entity, $table->save($entity));
  2152. $this->assertFalse($entity->isNew());
  2153. $this->assertInternalType('array', $entity->article);
  2154. }
  2155. /**
  2156. * Tests saving hasOne association and returning a validation error will
  2157. * abort the saving process
  2158. *
  2159. * @group save
  2160. * @return void
  2161. */
  2162. public function testSaveHasOneWithValidationError() {
  2163. $entity = new \Cake\ORM\Entity([
  2164. 'name' => 'Jose'
  2165. ]);
  2166. $entity->article = new \Cake\ORM\Entity([
  2167. 'title' => 'A Title',
  2168. 'body' => 'A body'
  2169. ]);
  2170. $table = TableRegistry::get('authors');
  2171. $table->hasOne('articles');
  2172. $table->association('articles')
  2173. ->target()
  2174. ->validator()
  2175. ->add('title', 'num', ['rule' => 'numeric']);
  2176. $this->assertFalse($table->save($entity));
  2177. $this->assertTrue($entity->isNew());
  2178. $this->assertTrue($entity->article->isNew());
  2179. $this->assertNull($entity->article->id);
  2180. $this->assertNull($entity->article->get('author_id'));
  2181. $this->assertTrue($entity->article->dirty('author_id'));
  2182. $this->assertNotEmpty($entity->article->errors('title'));
  2183. }
  2184. /**
  2185. * Tests saving multiple entities in a hasMany association
  2186. *
  2187. * @return void
  2188. */
  2189. public function testSaveHasMany() {
  2190. $entity = new \Cake\ORM\Entity([
  2191. 'name' => 'Jose'
  2192. ]);
  2193. $entity->articles = [
  2194. new \Cake\ORM\Entity([
  2195. 'title' => 'A Title',
  2196. 'body' => 'A body'
  2197. ]),
  2198. new \Cake\ORM\Entity([
  2199. 'title' => 'Another Title',
  2200. 'body' => 'Another body'
  2201. ])
  2202. ];
  2203. $table = TableRegistry::get('authors');
  2204. $table->hasMany('articles');
  2205. $this->assertSame($entity, $table->save($entity));
  2206. $this->assertFalse($entity->isNew());
  2207. $this->assertFalse($entity->articles[0]->isNew());
  2208. $this->assertFalse($entity->articles[1]->isNew());
  2209. $this->assertEquals(4, $entity->articles[0]->id);
  2210. $this->assertEquals(5, $entity->articles[1]->id);
  2211. $this->assertEquals(5, $entity->articles[0]->author_id);
  2212. $this->assertEquals(5, $entity->articles[1]->author_id);
  2213. }
  2214. /**
  2215. * Tests saving multiple entities in a hasMany association and getting and
  2216. * error while saving one of them. It should abort all the save operation
  2217. * when options are set to defaults
  2218. *
  2219. * @return void
  2220. */
  2221. public function testSaveHasManyWithErrorsAtomic() {
  2222. $entity = new \Cake\ORM\Entity([
  2223. 'name' => 'Jose'
  2224. ]);
  2225. $entity->articles = [
  2226. new \Cake\ORM\Entity([
  2227. 'title' => '1',
  2228. 'body' => 'A body'
  2229. ]),
  2230. new \Cake\ORM\Entity([
  2231. 'title' => 'Another Title',
  2232. 'body' => 'Another body'
  2233. ])
  2234. ];
  2235. $table = TableRegistry::get('authors');
  2236. $table->hasMany('articles');
  2237. $table->association('articles')
  2238. ->target()
  2239. ->validator()
  2240. ->add('title', 'num', ['rule' => 'numeric']);
  2241. $this->assertFalse($table->save($entity));
  2242. $this->assertTrue($entity->isNew());
  2243. $this->assertNull($entity->articles[0]->isNew());
  2244. $this->assertNull($entity->articles[1]->isNew());
  2245. $this->assertNull($entity->articles[0]->id);
  2246. $this->assertNull($entity->articles[1]->id);
  2247. $this->assertNull($entity->articles[0]->author_id);
  2248. $this->assertNull($entity->articles[1]->author_id);
  2249. $this->assertEmpty($entity->articles[0]->errors());
  2250. $this->assertNotEmpty($entity->articles[1]->errors());
  2251. }
  2252. /**
  2253. * Tests that it is possible to continue saving hasMany associations
  2254. * even if any of the records fail validation when atomic is set
  2255. * to false
  2256. *
  2257. * @return void
  2258. */
  2259. public function testSaveHasManyWithErrorsNonAtomic() {
  2260. $entity = new \Cake\ORM\Entity([
  2261. 'name' => 'Jose'
  2262. ]);
  2263. $entity->articles = [
  2264. new \Cake\ORM\Entity([
  2265. 'title' => 'A title',
  2266. 'body' => 'A body'
  2267. ]),
  2268. new \Cake\ORM\Entity([
  2269. 'title' => '1',
  2270. 'body' => 'Another body'
  2271. ])
  2272. ];
  2273. $table = TableRegistry::get('authors');
  2274. $table->hasMany('articles');
  2275. $table->association('articles')
  2276. ->target()
  2277. ->validator()
  2278. ->add('title', 'num', ['rule' => 'numeric']);
  2279. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2280. $this->assertFalse($entity->isNew());
  2281. $this->assertTrue($entity->articles[0]->isNew());
  2282. $this->assertFalse($entity->articles[1]->isNew());
  2283. $this->assertEquals(4, $entity->articles[1]->id);
  2284. $this->assertNull($entity->articles[0]->id);
  2285. $this->assertEquals(5, $entity->articles[0]->author_id);
  2286. $this->assertEquals(5, $entity->articles[1]->author_id);
  2287. }
  2288. /**
  2289. * Tests saving hasOne association and returning a validation error will
  2290. * not abort the saving process if atomic is set to false
  2291. *
  2292. * @group save
  2293. * @return void
  2294. */
  2295. public function testSaveHasOneWithValidationErrorNonAtomic() {
  2296. $entity = new \Cake\ORM\Entity([
  2297. 'name' => 'Jose'
  2298. ]);
  2299. $entity->article = new \Cake\ORM\Entity([
  2300. 'title' => 'A Title',
  2301. 'body' => 'A body'
  2302. ]);
  2303. $table = TableRegistry::get('authors');
  2304. $table->hasOne('articles');
  2305. $table->association('articles')
  2306. ->target()
  2307. ->validator()
  2308. ->add('title', 'num', ['rule' => 'numeric']);
  2309. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2310. $this->assertFalse($entity->isNew());
  2311. $this->assertTrue($entity->article->isNew());
  2312. $this->assertNull($entity->article->id);
  2313. $this->assertNull($entity->article->get('author_id'));
  2314. $this->assertTrue($entity->article->dirty('author_id'));
  2315. $this->assertNotEmpty($entity->article->errors('title'));
  2316. }
  2317. /**
  2318. * Tests saving belongsTo association and get a validation error won't stop
  2319. * saving if atomic is set to false
  2320. *
  2321. * @group save
  2322. * @return void
  2323. */
  2324. public function testSaveBelongsToWithValidationErrorNotAtomic() {
  2325. $entity = new \Cake\ORM\Entity([
  2326. 'title' => 'A Title',
  2327. 'body' => 'A body'
  2328. ]);
  2329. $entity->author = new \Cake\ORM\Entity([
  2330. 'name' => 'Jose'
  2331. ]);
  2332. $table = TableRegistry::get('articles');
  2333. $table->belongsTo('authors');
  2334. $table->association('authors')
  2335. ->target()
  2336. ->validator()
  2337. ->add('name', 'num', ['rule' => 'numeric']);
  2338. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2339. $this->assertFalse($entity->isNew());
  2340. $this->assertTrue($entity->author->isNew());
  2341. $this->assertNull($entity->get('author_id'));
  2342. $this->assertNotEmpty($entity->author->errors('name'));
  2343. }
  2344. /**
  2345. * Tests saving belongsToMany records
  2346. *
  2347. * @group save
  2348. * @return void
  2349. */
  2350. public function testSaveBelongsToMany() {
  2351. $entity = new \Cake\ORM\Entity([
  2352. 'title' => 'A Title',
  2353. 'body' => 'A body'
  2354. ]);
  2355. $entity->tags = [
  2356. new \Cake\ORM\Entity([
  2357. 'name' => 'Something New'
  2358. ]),
  2359. new \Cake\ORM\Entity([
  2360. 'name' => 'Another Something'
  2361. ])
  2362. ];
  2363. $table = TableRegistry::get('articles');
  2364. $table->belongsToMany('tags');
  2365. $this->assertSame($entity, $table->save($entity));
  2366. $this->assertFalse($entity->isNew());
  2367. $this->assertFalse($entity->tags[0]->isNew());
  2368. $this->assertFalse($entity->tags[1]->isNew());
  2369. $this->assertEquals(4, $entity->tags[0]->id);
  2370. $this->assertEquals(5, $entity->tags[1]->id);
  2371. $this->assertEquals(4, $entity->tags[0]->_joinData->article_id);
  2372. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2373. $this->assertEquals(4, $entity->tags[0]->_joinData->tag_id);
  2374. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2375. }
  2376. /**
  2377. * Tests saving belongsToMany records can delete all links.
  2378. *
  2379. * @group save
  2380. * @return void
  2381. */
  2382. public function testSaveBelongsToManyDeleteAllLinks() {
  2383. $table = TableRegistry::get('articles');
  2384. $table->belongsToMany('tags', [
  2385. 'saveStrategy' => 'replace',
  2386. ]);
  2387. $entity = $table->get(1, ['contain' => 'Tags']);
  2388. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  2389. $entity->tags = [];
  2390. $result = $table->save($entity);
  2391. $this->assertSame($result, $entity);
  2392. $this->assertSame([], $entity->tags, 'No tags on the entity.');
  2393. $entity = $table->get(1, ['contain' => 'Tags']);
  2394. $this->assertSame([], $entity->tags, 'No tags in the db either.');
  2395. }
  2396. /**
  2397. * Tests saving belongsToMany records can delete some links.
  2398. *
  2399. * @group save
  2400. * @return void
  2401. */
  2402. public function testSaveBelongsToManyDeleteSomeLinks() {
  2403. $table = TableRegistry::get('articles');
  2404. $table->belongsToMany('tags', [
  2405. 'saveStrategy' => 'replace',
  2406. ]);
  2407. $entity = $table->get(1, ['contain' => 'Tags']);
  2408. $this->assertCount(2, $entity->tags, 'Fixture data did not change.');
  2409. $tag = new \Cake\ORM\Entity([
  2410. 'id' => 2,
  2411. ]);
  2412. $entity->tags = [$tag];
  2413. $result = $table->save($entity);
  2414. $this->assertSame($result, $entity);
  2415. $this->assertCount(1, $entity->tags, 'Only one tag left.');
  2416. $this->assertEquals($tag, $entity->tags[0]);
  2417. $entity = $table->get(1, ['contain' => 'Tags']);
  2418. $this->assertCount(1, $entity->tags, 'Only one tag in the db.');
  2419. $this->assertEquals($tag->id, $entity->tags[0]->id);
  2420. }
  2421. /**
  2422. * Tests saving belongsToMany records with a validation error and atomic set
  2423. * to true
  2424. *
  2425. * @group save
  2426. * @return void
  2427. */
  2428. public function testSaveBelongsToWithValidationErrorAtomic() {
  2429. $entity = new \Cake\ORM\Entity([
  2430. 'title' => 'A Title',
  2431. 'body' => 'A body'
  2432. ]);
  2433. $entity->tags = [
  2434. new \Cake\ORM\Entity([
  2435. 'name' => '100'
  2436. ]),
  2437. new \Cake\ORM\Entity([
  2438. 'name' => 'Something New'
  2439. ])
  2440. ];
  2441. $table = TableRegistry::get('articles');
  2442. $table->belongsToMany('tags');
  2443. $tags = $table->association('tags')
  2444. ->target()
  2445. ->validator()
  2446. ->add('name', 'num', ['rule' => 'numeric']);
  2447. $this->assertFalse($table->save($entity));
  2448. $this->assertTrue($entity->isNew());
  2449. $this->assertNull($entity->tags[0]->isNew());
  2450. $this->assertNull($entity->tags[1]->isNew());
  2451. $this->assertNull($entity->tags[0]->id);
  2452. $this->assertNull($entity->tags[1]->id);
  2453. $this->assertNull($entity->tags[0]->_joinData);
  2454. $this->assertNull($entity->tags[1]->_joinData);
  2455. $this->assertEmpty($entity->tags[0]->errors('name'));
  2456. $this->assertNotEmpty($entity->tags[1]->errors('name'));
  2457. }
  2458. /**
  2459. * Tests saving belongsToMany records with a validation error and atomic set
  2460. * to false
  2461. *
  2462. * @group save
  2463. * @return void
  2464. */
  2465. public function testSaveBelongsToWithValidationErrorNonAtomic() {
  2466. $entity = new \Cake\ORM\Entity([
  2467. 'title' => 'A Title',
  2468. 'body' => 'A body'
  2469. ]);
  2470. $entity->tags = [
  2471. new \Cake\ORM\Entity([
  2472. 'name' => 'Something New'
  2473. ]),
  2474. new \Cake\ORM\Entity([
  2475. 'name' => '100'
  2476. ])
  2477. ];
  2478. $table = TableRegistry::get('articles');
  2479. $table->belongsToMany('tags');
  2480. $tags = $table->association('tags')
  2481. ->target()
  2482. ->validator()
  2483. ->add('name', 'num', ['rule' => 'numeric']);
  2484. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2485. $this->assertFalse($entity->isNew());
  2486. $this->assertTrue($entity->tags[0]->isNew());
  2487. $this->assertFalse($entity->tags[1]->isNew());
  2488. $this->assertNull($entity->tags[0]->id);
  2489. $this->assertEquals(4, $entity->tags[1]->id);
  2490. $this->assertNull($entity->tags[0]->_joinData);
  2491. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2492. $this->assertEquals(4, $entity->tags[1]->_joinData->tag_id);
  2493. }
  2494. /**
  2495. * Tests saving belongsToMany records with a validation error in a joint entity
  2496. *
  2497. * @group save
  2498. * @return void
  2499. */
  2500. public function testSaveBelongsToWithValidationErrorInJointEntity() {
  2501. $entity = new \Cake\ORM\Entity([
  2502. 'title' => 'A Title',
  2503. 'body' => 'A body'
  2504. ]);
  2505. $entity->tags = [
  2506. new \Cake\ORM\Entity([
  2507. 'name' => 'Something New'
  2508. ]),
  2509. new \Cake\ORM\Entity([
  2510. 'name' => '100'
  2511. ])
  2512. ];
  2513. $table = TableRegistry::get('articles');
  2514. $table->belongsToMany('tags');
  2515. $table->association('tags')
  2516. ->junction()
  2517. ->validator()
  2518. ->add('article_id', 'num', ['rule' => ['comparison', '>', 4]]);
  2519. $this->assertFalse($table->save($entity));
  2520. $this->assertTrue($entity->isNew());
  2521. $this->assertNull($entity->tags[0]->isNew());
  2522. $this->assertNull($entity->tags[1]->isNew());
  2523. $this->assertNull($entity->tags[0]->id);
  2524. $this->assertNull($entity->tags[1]->id);
  2525. $this->assertNull($entity->tags[0]->_joinData);
  2526. $this->assertNull($entity->tags[1]->_joinData);
  2527. }
  2528. /**
  2529. * Tests saving belongsToMany records with a validation error in a joint entity
  2530. * and atomic set to false
  2531. *
  2532. * @group save
  2533. * @return void
  2534. */
  2535. public function testSaveBelongsToWithValidationErrorInJointEntityNonAtomic() {
  2536. $entity = new \Cake\ORM\Entity([
  2537. 'title' => 'A Title',
  2538. 'body' => 'A body'
  2539. ]);
  2540. $entity->tags = [
  2541. new \Cake\ORM\Entity([
  2542. 'name' => 'Something New'
  2543. ]),
  2544. new \Cake\ORM\Entity([
  2545. 'name' => 'New one'
  2546. ])
  2547. ];
  2548. $table = TableRegistry::get('articles');
  2549. $table->belongsToMany('tags');
  2550. $table->association('tags')
  2551. ->junction()
  2552. ->validator()
  2553. ->add('tag_id', 'num', ['rule' => ['comparison', '>', 4]]);
  2554. $this->assertSame($entity, $table->save($entity, ['atomic' => false]));
  2555. $this->assertFalse($entity->isNew());
  2556. $this->assertFalse($entity->tags[0]->isNew());
  2557. $this->assertFalse($entity->tags[1]->isNew());
  2558. $this->assertEquals(4, $entity->tags[0]->id);
  2559. $this->assertEquals(5, $entity->tags[1]->id);
  2560. $this->assertTrue($entity->tags[0]->_joinData->isNew());
  2561. $this->assertNotEmpty($entity->tags[0]->_joinData->errors());
  2562. $this->assertEquals(4, $entity->tags[1]->_joinData->article_id);
  2563. $this->assertEquals(5, $entity->tags[1]->_joinData->tag_id);
  2564. }
  2565. /**
  2566. * Tests that saving a persisted and clean entity will is a no-op
  2567. *
  2568. * @group save
  2569. * @return void
  2570. */
  2571. public function testSaveCleanEntity() {
  2572. $table = $this->getMock('\Cake\ORM\Table', ['_processSave']);
  2573. $entity = new \Cake\ORM\Entity(
  2574. ['id' => 'foo'],
  2575. ['markNew' => false, 'markClean' => true]
  2576. );
  2577. $table->expects($this->never())->method('_processSave');
  2578. $this->assertSame($entity, $table->save($entity));
  2579. }
  2580. /**
  2581. * Integration test to show how to append a new tag to an article
  2582. *
  2583. * @group save
  2584. * @return void
  2585. */
  2586. public function testBelongsToManyIntegration() {
  2587. $table = TableRegistry::get('articles');
  2588. $table->belongsToMany('tags');
  2589. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2590. $tags = $article->tags;
  2591. $this->assertNotEmpty($tags);
  2592. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'Something New']);
  2593. $article->tags = $tags;
  2594. $this->assertSame($article, $table->save($article));
  2595. $tags = $article->tags;
  2596. $this->assertCount(3, $tags);
  2597. $this->assertFalse($tags[2]->isNew());
  2598. $this->assertEquals(4, $tags[2]->id);
  2599. $this->assertEquals(1, $tags[2]->_joinData->article_id);
  2600. $this->assertEquals(4, $tags[2]->_joinData->tag_id);
  2601. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2602. $this->assertEquals($tags, $article->tags);
  2603. }
  2604. /**
  2605. * Tests that it is possible to do a deep save and control what associations get saved,
  2606. * while having control of the options passed to each level of the save
  2607. *
  2608. * @group save
  2609. * @return void
  2610. */
  2611. public function testSaveDeepAssociationOptions() {
  2612. $articles = $this->getMock(
  2613. '\Cake\ORM\Table',
  2614. ['_insert'],
  2615. [['table' => 'articles', 'connection' => $this->connection]]
  2616. );
  2617. $authors = $this->getMock(
  2618. '\Cake\ORM\Table',
  2619. ['_insert', 'validate'],
  2620. [['table' => 'authors', 'connection' => $this->connection]]
  2621. );
  2622. $supervisors = $this->getMock(
  2623. '\Cake\ORM\Table',
  2624. ['_insert', 'validate'],
  2625. [[
  2626. 'table' => 'authors',
  2627. 'alias' => 'supervisors',
  2628. 'connection' => $this->connection
  2629. ]]
  2630. );
  2631. $tags = $this->getMock(
  2632. '\Cake\ORM\Table',
  2633. ['_insert'],
  2634. [['table' => 'tags', 'connection' => $this->connection]]
  2635. );
  2636. $articles->belongsTo('authors', ['targetTable' => $authors]);
  2637. $authors->hasOne('supervisors', ['targetTable' => $supervisors]);
  2638. $supervisors->belongsToMany('tags', ['targetTable' => $tags]);
  2639. $entity = new \Cake\ORM\Entity([
  2640. 'title' => 'bar',
  2641. 'author' => new \Cake\ORM\Entity([
  2642. 'name' => 'Juan',
  2643. 'supervisor' => new \Cake\ORM\Entity(['name' => 'Marc']),
  2644. 'tags' => [
  2645. new \Cake\ORM\Entity(['name' => 'foo'])
  2646. ]
  2647. ]),
  2648. ]);
  2649. $entity->isNew(true);
  2650. $entity->author->isNew(true);
  2651. $entity->author->supervisor->isNew(true);
  2652. $entity->author->tags[0]->isNew(true);
  2653. $articles->expects($this->once())
  2654. ->method('_insert')
  2655. ->with($entity, ['title' => 'bar'])
  2656. ->will($this->returnValue($entity));
  2657. $authors->expects($this->once())
  2658. ->method('_insert')
  2659. ->with($entity->author, ['name' => 'Juan'])
  2660. ->will($this->returnValue($entity->author));
  2661. $authors->expects($this->once())
  2662. ->method('validate')
  2663. ->with($entity->author)
  2664. ->will($this->returnValue(true));
  2665. $supervisors->expects($this->once())
  2666. ->method('_insert')
  2667. ->with($entity->author->supervisor, ['name' => 'Marc'])
  2668. ->will($this->returnValue($entity->author->supervisor));
  2669. $supervisors->expects($this->never())->method('validate');
  2670. $tags->expects($this->never())->method('_insert');
  2671. $this->assertSame($entity, $articles->save($entity, [
  2672. 'associated' => [
  2673. 'authors' => [
  2674. 'validate' => 'special'
  2675. ],
  2676. 'authors.supervisors' => [
  2677. 'atomic' => false,
  2678. 'validate' => false,
  2679. 'associated' => false
  2680. ]
  2681. ]
  2682. ]));
  2683. }
  2684. /**
  2685. * Integration test for linking entities with belongsToMany
  2686. *
  2687. * @return void
  2688. */
  2689. public function testLinkBelongsToMany() {
  2690. $table = TableRegistry::get('articles');
  2691. $table->belongsToMany('tags');
  2692. $tagsTable = TableRegistry::get('tags');
  2693. $source = ['source' => 'tags'];
  2694. $options = ['markNew' => false];
  2695. $article = new \Cake\ORM\Entity([
  2696. 'id' => 1,
  2697. ], $options);
  2698. $newTag = new \TestApp\Model\Entity\Tag([
  2699. 'name' => 'Foo'
  2700. ], $source);
  2701. $tags[] = new \TestApp\Model\Entity\Tag([
  2702. 'id' => 3
  2703. ], $options + $source);
  2704. $tags[] = $newTag;
  2705. $tagsTable->save($newTag);
  2706. $table->association('tags')->link($article, $tags);
  2707. $this->assertEquals($article->tags, $tags);
  2708. foreach ($tags as $tag) {
  2709. $this->assertFalse($tag->isNew());
  2710. }
  2711. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2712. $this->assertEquals($article->tags[2]->id, $tags[0]->id);
  2713. $this->assertEquals($article->tags[3], $tags[1]);
  2714. }
  2715. /**
  2716. * Integration test to show how to unlink a single record from a belongsToMany
  2717. *
  2718. * @return void
  2719. */
  2720. public function testUnlinkBelongsToMany() {
  2721. $table = TableRegistry::get('articles');
  2722. $table->belongsToMany('tags');
  2723. $tagsTable = TableRegistry::get('tags');
  2724. $options = ['markNew' => false];
  2725. $article = $table->find('all')
  2726. ->where(['id' => 1])
  2727. ->contain(['tags'])->first();
  2728. $table->association('tags')->unlink($article, [$article->tags[0]]);
  2729. $this->assertCount(1, $article->tags);
  2730. $this->assertEquals(2, $article->tags[0]->get('id'));
  2731. $this->assertFalse($article->dirty('tags'));
  2732. }
  2733. /**
  2734. * Integration test to show how to unlink multiple records from a belongsToMany
  2735. *
  2736. * @return void
  2737. */
  2738. public function testUnlinkBelongsToManyMultiple() {
  2739. $table = TableRegistry::get('articles');
  2740. $table->belongsToMany('tags');
  2741. $tagsTable = TableRegistry::get('tags');
  2742. $options = ['markNew' => false];
  2743. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2744. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2745. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2746. $table->association('tags')->unlink($article, $tags);
  2747. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2748. $this->assertEmpty($left->tags);
  2749. }
  2750. /**
  2751. * Integration test to show how to unlink multiple records from a belongsToMany
  2752. * providing some of the joint
  2753. *
  2754. * @return void
  2755. */
  2756. public function testUnlinkBelongsToManyPassingJoint() {
  2757. $table = TableRegistry::get('articles');
  2758. $table->belongsToMany('tags');
  2759. $tagsTable = TableRegistry::get('tags');
  2760. $options = ['markNew' => false];
  2761. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2762. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 1], $options);
  2763. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2764. $tags[1]->_joinData = new \Cake\ORM\Entity([
  2765. 'article_id' => 1,
  2766. 'tag_id' => 2
  2767. ]);
  2768. $table->association('tags')->unlink($article, $tags);
  2769. $left = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2770. $this->assertEmpty($left->tags);
  2771. }
  2772. /**
  2773. * Integration test to show how to replace records from a belongsToMany
  2774. *
  2775. * @return void
  2776. */
  2777. public function testReplacelinksBelongsToMany() {
  2778. $table = TableRegistry::get('articles');
  2779. $table->belongsToMany('tags');
  2780. $tagsTable = TableRegistry::get('tags');
  2781. $options = ['markNew' => false];
  2782. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2783. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 2], $options);
  2784. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2785. $tags[] = new \TestApp\Model\Entity\Tag(['name' => 'foo']);
  2786. $table->association('tags')->replaceLinks($article, $tags);
  2787. $this->assertEquals(2, $article->tags[0]->id);
  2788. $this->assertEquals(3, $article->tags[1]->id);
  2789. $this->assertEquals(4, $article->tags[2]->id);
  2790. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2791. $this->assertCount(3, $article->tags);
  2792. $this->assertEquals(2, $article->tags[0]->id);
  2793. $this->assertEquals(3, $article->tags[1]->id);
  2794. $this->assertEquals(4, $article->tags[2]->id);
  2795. $this->assertEquals('foo', $article->tags[2]->name);
  2796. }
  2797. /**
  2798. * Integration test to show how remove all links from a belongsToMany
  2799. *
  2800. * @return void
  2801. */
  2802. public function testReplacelinksBelongsToManyWithEmpty() {
  2803. $table = TableRegistry::get('articles');
  2804. $table->belongsToMany('tags');
  2805. $tagsTable = TableRegistry::get('tags');
  2806. $options = ['markNew' => false];
  2807. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2808. $tags = [];
  2809. $table->association('tags')->replaceLinks($article, $tags);
  2810. $this->assertSame($tags, $article->tags);
  2811. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2812. $this->assertEmpty($article->tags);
  2813. }
  2814. /**
  2815. * Integration test to show how to replace records from a belongsToMany
  2816. * passing the joint property along in the target entity
  2817. *
  2818. * @return void
  2819. */
  2820. public function testReplacelinksBelongsToManyWithJoint() {
  2821. $table = TableRegistry::get('articles');
  2822. $table->belongsToMany('tags');
  2823. $tagsTable = TableRegistry::get('tags');
  2824. $options = ['markNew' => false];
  2825. $article = new \Cake\ORM\Entity(['id' => 1], $options);
  2826. $tags[] = new \TestApp\Model\Entity\Tag([
  2827. 'id' => 2,
  2828. '_joinData' => new \Cake\ORM\Entity([
  2829. 'article_id' => 1,
  2830. 'tag_id' => 2,
  2831. ])
  2832. ], $options);
  2833. $tags[] = new \TestApp\Model\Entity\Tag(['id' => 3], $options);
  2834. $table->association('tags')->replaceLinks($article, $tags);
  2835. $this->assertSame($tags, $article->tags);
  2836. $article = $table->find('all')->where(['id' => 1])->contain(['tags'])->first();
  2837. $this->assertCount(2, $article->tags);
  2838. $this->assertEquals(2, $article->tags[0]->id);
  2839. $this->assertEquals(3, $article->tags[1]->id);
  2840. }
  2841. /**
  2842. * Tests that it is possible to call find with no arguments
  2843. *
  2844. * @return void
  2845. */
  2846. public function testSimplifiedFind() {
  2847. $table = $this->getMock(
  2848. '\Cake\ORM\Table',
  2849. ['callFinder'],
  2850. [[
  2851. 'connection' => $this->connection,
  2852. 'schema' => ['id' => ['type' => 'integer']]
  2853. ]]
  2854. );
  2855. $query = (new \Cake\ORM\Query($this->connection, $table))->select();
  2856. $table->expects($this->once())->method('callFinder')
  2857. ->with('all', $query, []);
  2858. $table->find();
  2859. }
  2860. /**
  2861. * Test that get() will use the primary key for searching and return the first
  2862. * entity found
  2863. *
  2864. * @return void
  2865. */
  2866. public function testGet() {
  2867. $table = $this->getMock(
  2868. '\Cake\ORM\Table',
  2869. ['callFinder', 'query'],
  2870. [[
  2871. 'connection' => $this->connection,
  2872. 'schema' => [
  2873. 'id' => ['type' => 'integer'],
  2874. 'bar' => ['type' => 'integer'],
  2875. '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['bar']]]
  2876. ]
  2877. ]]
  2878. );
  2879. $query = $this->getMock(
  2880. '\Cake\ORM\Query',
  2881. ['addDefaultTypes', 'first', 'where'],
  2882. [$this->connection, $table]
  2883. );
  2884. $entity = new \Cake\ORM\Entity;
  2885. $table->expects($this->once())->method('query')
  2886. ->will($this->returnValue($query));
  2887. $table->expects($this->once())->method('callFinder')
  2888. ->with('all', $query, ['fields' => ['id']])
  2889. ->will($this->returnValue($query));
  2890. $query->expects($this->once())->method('where')
  2891. ->with([$table->alias() . '.bar' => 10])
  2892. ->will($this->returnSelf());
  2893. $query->expects($this->once())->method('first')
  2894. ->will($this->returnValue($entity));
  2895. $result = $table->get(10, ['fields' => ['id']]);
  2896. $this->assertSame($entity, $result);
  2897. }
  2898. /**
  2899. * Tests that get() will throw an exception if the record was not found
  2900. *
  2901. * @expectedException \Cake\ORM\Error\RecordNotFoundException
  2902. * @expectedExceptionMessage Record "10" not found in table "articles"
  2903. * @return void
  2904. */
  2905. public function testGetNotFoundException() {
  2906. $table = new Table([
  2907. 'name' => 'Articles',
  2908. 'connection' => $this->connection,
  2909. 'table' => 'articles',
  2910. ]);
  2911. $table->get(10);
  2912. }
  2913. /**
  2914. * Test that an exception is raised when there are not enough keys.
  2915. *
  2916. * @expectedException \InvalidArgumentException
  2917. * @expectedExceptionMessage Incorrect number of primary key values. Expected 1 got 0.
  2918. * @return void
  2919. */
  2920. public function testGetExceptionOnIncorrectData() {
  2921. $table = new Table([
  2922. 'name' => 'Articles',
  2923. 'connection' => $this->connection,
  2924. 'table' => 'articles',
  2925. ]);
  2926. $table->get(null);
  2927. }
  2928. /**
  2929. * Tests entityValidator
  2930. *
  2931. * @return void
  2932. */
  2933. public function testEntityValidator() {
  2934. $table = new Table;
  2935. $expected = new \Cake\ORM\EntityValidator($table);
  2936. $table->entityValidator();
  2937. $this->assertEquals($expected, $table->entityValidator());
  2938. }
  2939. /**
  2940. * Tests that validate will call the entity validator with the correct
  2941. * options
  2942. *
  2943. * @return void
  2944. */
  2945. public function testValidateDefaultAssociations() {
  2946. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2947. $table->belongsTo('users');
  2948. $table->hasMany('articles');
  2949. $table->schema([]);
  2950. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2951. $entity = $table->newEntity([]);
  2952. $table->expects($this->once())->method('entityValidator')
  2953. ->will($this->returnValue($entityValidator));
  2954. $entityValidator->expects($this->once())->method('one')
  2955. ->with($entity, ['associated' => ['users', 'articles']])
  2956. ->will($this->returnValue(true));
  2957. $this->assertTrue($table->validate($entity));
  2958. }
  2959. /**
  2960. * Tests that validate will call the entity validator with the correct
  2961. * options
  2962. *
  2963. * @return void
  2964. */
  2965. public function testValidateWithCustomOptions() {
  2966. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2967. $table->schema([]);
  2968. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2969. $entity = $table->newEntity([]);
  2970. $options = ['associated' => ['users'], 'validate' => 'foo'];
  2971. $table->expects($this->once())->method('entityValidator')
  2972. ->will($this->returnValue($entityValidator));
  2973. $entityValidator->expects($this->once())->method('one')
  2974. ->with($entity, $options)
  2975. ->will($this->returnValue(false));
  2976. $this->assertFalse($table->validate($entity, $options));
  2977. }
  2978. /**
  2979. * Tests that validateMany will call the entity validator with the correct
  2980. * options
  2981. *
  2982. * @return void
  2983. */
  2984. public function testValidateManyDefaultAssociaion() {
  2985. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  2986. $table->belongsTo('users');
  2987. $table->hasMany('articles');
  2988. $table->schema([]);
  2989. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  2990. $entities = ['a', 'b'];
  2991. $table->expects($this->once())->method('entityValidator')
  2992. ->will($this->returnValue($entityValidator));
  2993. $entityValidator->expects($this->once())->method('many')
  2994. ->with($entities, ['associated' => ['users', 'articles']])
  2995. ->will($this->returnValue(true));
  2996. $this->assertTrue($table->validateMany($entities));
  2997. }
  2998. /**
  2999. * Tests that validateMany will call the entity validator with the correct
  3000. * options
  3001. *
  3002. * @return void
  3003. */
  3004. public function testValidateManyWithCustomOptions() {
  3005. $table = $this->getMock('\Cake\ORM\Table', ['entityValidator']);
  3006. $table->schema([]);
  3007. $entityValidator = $this->getMock('\Cake\ORM\EntityValidator', [], [$table]);
  3008. $entities = ['a', 'b', 'c'];
  3009. $options = ['associated' => ['users'], 'validate' => 'foo'];
  3010. $table->expects($this->once())->method('entityValidator')
  3011. ->will($this->returnValue($entityValidator));
  3012. $entityValidator->expects($this->once())->method('many')
  3013. ->with($entities, $options)
  3014. ->will($this->returnValue(false));
  3015. $this->assertFalse($table->validateMany($entities, $options));
  3016. }
  3017. /**
  3018. * Tests that patchEntity delegates the task to the marshaller and passed
  3019. * all associations
  3020. *
  3021. * @return void
  3022. */
  3023. public function testPatchEntity() {
  3024. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  3025. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  3026. $table->belongsTo('users');
  3027. $table->hasMany('articles');
  3028. $table->expects($this->once())->method('marshaller')
  3029. ->will($this->returnValue($marshaller));
  3030. $entity = new \Cake\ORM\Entity;
  3031. $data = ['foo' => 'bar'];
  3032. $marshaller->expects($this->once())
  3033. ->method('merge')
  3034. ->with($entity, $data, ['users', 'articles'])
  3035. ->will($this->returnValue($entity));
  3036. $table->patchEntity($entity, $data);
  3037. }
  3038. /**
  3039. * Tests that patchEntities delegates the task to the marshaller and passed
  3040. * all associations
  3041. *
  3042. * @return void
  3043. */
  3044. public function testPatchEntities() {
  3045. $table = $this->getMock('Cake\ORM\Table', ['marshaller']);
  3046. $marshaller = $this->getMock('Cake\ORM\Marshaller', [], [$table]);
  3047. $table->belongsTo('users');
  3048. $table->hasMany('articles');
  3049. $table->expects($this->once())->method('marshaller')
  3050. ->will($this->returnValue($marshaller));
  3051. $entities = [new \Cake\ORM\Entity];
  3052. $data = [['foo' => 'bar']];
  3053. $marshaller->expects($this->once())
  3054. ->method('mergeMany')
  3055. ->with($entities, $data, ['users', 'articles'])
  3056. ->will($this->returnValue($entities));
  3057. $table->patchEntities($entities, $data);
  3058. }
  3059. /**
  3060. * Tests __debugInfo
  3061. *
  3062. * @return void
  3063. */
  3064. public function testDebugInfo() {
  3065. $articles = TableRegistry::get('articles');
  3066. $articles->addBehavior('Timestamp');
  3067. $result = $articles->__debugInfo();
  3068. $expected = [
  3069. 'table' => 'articles',
  3070. 'alias' => 'articles',
  3071. 'entityClass' => 'TestApp\Model\Entity\Article',
  3072. 'associations' => ['authors', 'tags', 'articlestags'],
  3073. 'behaviors' => ['Timestamp'],
  3074. 'defaultConnection' => 'default',
  3075. 'connectionName' => 'test'
  3076. ];
  3077. $this->assertEquals($expected, $result);
  3078. }
  3079. }