TableTest.php 110 KB

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