TableTest.php 104 KB

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