TableTest.php 101 KB

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