TableTest.php 95 KB

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