TableTest.php 127 KB

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