TableTest.php 137 KB

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