TableTest.php 127 KB

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