ResultSetTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM;
  16. use Cake\Core\Configure;
  17. use Cake\Core\Plugin;
  18. use Cake\Datasource\ConnectionManager;
  19. use Cake\ORM\Entity;
  20. use Cake\ORM\Query;
  21. use Cake\ORM\ResultSet;
  22. use Cake\ORM\Table;
  23. use Cake\ORM\TableRegistry;
  24. use Cake\TestSuite\TestCase;
  25. /**
  26. * ResultSet test case.
  27. */
  28. class ResultSetTest extends TestCase
  29. {
  30. public $fixtures = ['core.articles', 'core.authors', 'core.comments'];
  31. /**
  32. * setup
  33. *
  34. * @return void
  35. */
  36. public function setUp()
  37. {
  38. parent::setUp();
  39. $this->connection = ConnectionManager::get('test');
  40. $this->table = new Table([
  41. 'table' => 'articles',
  42. 'connection' => $this->connection,
  43. ]);
  44. $this->fixtureData = [
  45. ['id' => 1, 'author_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y'],
  46. ['id' => 2, 'author_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', 'published' => 'Y'],
  47. ['id' => 3, 'author_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y']
  48. ];
  49. }
  50. /**
  51. * Test that result sets can be rewound and re-used.
  52. *
  53. * @return void
  54. */
  55. public function testRewind()
  56. {
  57. $query = $this->table->find('all');
  58. $results = $query->all();
  59. $first = $second = [];
  60. foreach ($results as $result) {
  61. $first[] = $result;
  62. }
  63. foreach ($results as $result) {
  64. $second[] = $result;
  65. }
  66. $this->assertEquals($first, $second);
  67. }
  68. /**
  69. * Test that streaming results cannot be rewound
  70. *
  71. * @return void
  72. */
  73. public function testRewindStreaming()
  74. {
  75. $query = $this->table->find('all')->bufferResults(false);
  76. $results = $query->all();
  77. $first = $second = [];
  78. foreach ($results as $result) {
  79. $first[] = $result;
  80. }
  81. $this->setExpectedException('Cake\Database\Exception');
  82. foreach ($results as $result) {
  83. $second[] = $result;
  84. }
  85. }
  86. /**
  87. * An integration test for testing serialize and unserialize features.
  88. *
  89. * Compare the results of a query with the results iterated, with
  90. * those of a different query that have been serialized/unserialized.
  91. *
  92. * @return void
  93. */
  94. public function testSerialization()
  95. {
  96. $query = $this->table->find('all');
  97. $results = $query->all();
  98. $expected = $results->toArray();
  99. $query2 = $this->table->find('all');
  100. $results2 = $query2->all();
  101. $serialized = serialize($results2);
  102. $outcome = unserialize($serialized);
  103. $this->assertEquals($expected, $outcome->toArray());
  104. }
  105. /**
  106. * Test iteration after serialization
  107. *
  108. * @return void
  109. */
  110. public function testIteratorAfterSerializationNoHydration()
  111. {
  112. $query = $this->table->find('all')->hydrate(false);
  113. $results = unserialize(serialize($query->all()));
  114. // Use a loop to test Iterator implementation
  115. foreach ($results as $i => $row) {
  116. $this->assertEquals($this->fixtureData[$i], $row, "Row $i does not match");
  117. }
  118. }
  119. /**
  120. * Test iteration after serialization
  121. *
  122. * @return void
  123. */
  124. public function testIteratorAfterSerializationHydrated()
  125. {
  126. $query = $this->table->find('all');
  127. $results = unserialize(serialize($query->all()));
  128. // Use a loop to test Iterator implementation
  129. foreach ($results as $i => $row) {
  130. $expected = new \Cake\ORM\Entity($this->fixtureData[$i]);
  131. $expected->isNew(false);
  132. $expected->source($this->table->alias());
  133. $expected->clean();
  134. $this->assertEquals($expected, $row, "Row $i does not match");
  135. }
  136. }
  137. /**
  138. * Test converting resultsets into json
  139. *
  140. * @return void
  141. */
  142. public function testJsonSerialize()
  143. {
  144. $query = $this->table->find('all');
  145. $results = $query->all();
  146. $expected = json_encode($this->fixtureData);
  147. $this->assertEquals($expected, json_encode($results));
  148. }
  149. /**
  150. * Test first() method with a statement backed result set.
  151. *
  152. * @return void
  153. */
  154. public function testFirst()
  155. {
  156. $query = $this->table->find('all');
  157. $results = $query->hydrate(false)->all();
  158. $row = $results->first();
  159. $this->assertEquals($this->fixtureData[0], $row);
  160. $row = $results->first();
  161. $this->assertEquals($this->fixtureData[0], $row);
  162. }
  163. /**
  164. * Test first() method with a result set that has been unserialized
  165. *
  166. * @return void
  167. */
  168. public function testFirstAfterSerialize()
  169. {
  170. $query = $this->table->find('all');
  171. $results = $query->hydrate(false)->all();
  172. $results = unserialize(serialize($results));
  173. $row = $results->first();
  174. $this->assertEquals($this->fixtureData[0], $row);
  175. $this->assertSame($row, $results->first());
  176. $this->assertSame($row, $results->first());
  177. }
  178. /**
  179. * Test the countable interface.
  180. *
  181. * @return void
  182. */
  183. public function testCount()
  184. {
  185. $query = $this->table->find('all');
  186. $results = $query->all();
  187. $this->assertCount(3, $results, 'Should be countable and 3');
  188. }
  189. /**
  190. * Test the countable interface after unserialize
  191. *
  192. * @return void
  193. */
  194. public function testCountAfterSerialize()
  195. {
  196. $query = $this->table->find('all');
  197. $results = $query->all();
  198. $results = unserialize(serialize($results));
  199. $this->assertCount(3, $results, 'Should be countable and 3');
  200. }
  201. /**
  202. * Integration test to show methods from CollectionTrait work
  203. *
  204. * @return void
  205. */
  206. public function testGroupBy()
  207. {
  208. $query = $this->table->find('all');
  209. $results = $query->all()->groupBy('author_id')->toArray();
  210. $options = [
  211. 'markNew' => false,
  212. 'markClean' => true,
  213. 'source' => $this->table->alias()
  214. ];
  215. $expected = [
  216. 1 => [
  217. new Entity($this->fixtureData[0], $options),
  218. new Entity($this->fixtureData[2], $options)
  219. ],
  220. 3 => [
  221. new Entity($this->fixtureData[1], $options),
  222. ]
  223. ];
  224. $this->assertEquals($expected, $results);
  225. }
  226. /**
  227. * Tests __debugInfo
  228. *
  229. * @return void
  230. */
  231. public function testDebugInfo()
  232. {
  233. $query = $this->table->find('all');
  234. $results = $query->all();
  235. $expected = [
  236. 'items' => $results->toArray()
  237. ];
  238. $this->assertSame($expected, $results->__debugInfo());
  239. }
  240. /**
  241. * Test that eagerLoader leaves empty associations unpopulated.
  242. *
  243. * @return void
  244. */
  245. public function testBelongsToEagerLoaderLeavesEmptyAssocation()
  246. {
  247. $comments = TableRegistry::get('Comments');
  248. $comments->belongsTo('Articles');
  249. // Clear the articles table so we can trigger an empty belongsTo
  250. $this->table->deleteAll([]);
  251. $comment = $comments->find()->where(['Comments.id' => 1])
  252. ->contain(['Articles'])
  253. ->hydrate(false)
  254. ->first();
  255. $this->assertEquals(1, $comment['id']);
  256. $this->assertNotEmpty($comment['comment']);
  257. $this->assertNull($comment['article']);
  258. $comment = $comments->get(1, ['contain' => ['Articles']]);
  259. $this->assertNull($comment->article);
  260. $this->assertEquals(1, $comment->id);
  261. $this->assertNotEmpty($comment->comment);
  262. }
  263. /**
  264. * Test that eagerLoader leaves empty associations unpopulated.
  265. *
  266. * @return void
  267. */
  268. public function testHasOneEagerLoaderLeavesEmptyAssocation()
  269. {
  270. $this->table->hasOne('Comments');
  271. // Clear the comments table so we can trigger an empty hasOne.
  272. $comments = TableRegistry::get('Comments');
  273. $comments->deleteAll([]);
  274. $article = $this->table->get(1, ['contain' => ['Comments']]);
  275. $this->assertNull($article->comment);
  276. $this->assertEquals(1, $article->id);
  277. $this->assertNotEmpty($article->title);
  278. $article = $this->table->find()->where(['articles.id' => 1])
  279. ->contain(['Comments'])
  280. ->hydrate(false)
  281. ->first();
  282. $this->assertNull($article['comment']);
  283. $this->assertEquals(1, $article['id']);
  284. $this->assertNotEmpty($article['title']);
  285. }
  286. /**
  287. * Test that fetching rows does not fail when no fields were selected
  288. * on the default alias.
  289. *
  290. * @return void
  291. */
  292. public function testFetchMissingDefaultAlias()
  293. {
  294. $comments = TableRegistry::get('Comments');
  295. $query = $comments->find()->select(['Other__field' => 'test']);
  296. $query->autoFields(false);
  297. $row = ['Other__field' => 'test'];
  298. $statement = $this->getMock('Cake\Database\StatementInterface');
  299. $statement->method('fetch')
  300. ->will($this->onConsecutiveCalls($row, $row));
  301. $statement->method('rowCount')
  302. ->will($this->returnValue(1));
  303. $result = new ResultSet($query, $statement);
  304. $result->valid();
  305. $data = $result->current();
  306. }
  307. /**
  308. * Test that associations have source() correctly set.
  309. *
  310. * @return void
  311. */
  312. public function testSourceOnContainAssociations()
  313. {
  314. Plugin::load('TestPlugin');
  315. $comments = TableRegistry::get('TestPlugin.Comments');
  316. $comments->belongsTo('Authors', [
  317. 'className' => 'TestPlugin.Authors',
  318. 'foreignKey' => 'user_id'
  319. ]);
  320. $result = $comments->find()->contain(['Authors'])->first();
  321. $this->assertEquals('TestPlugin.Comments', $result->source());
  322. $this->assertEquals('TestPlugin.Authors', $result->author->source());
  323. $result = $comments->find()->matching('Authors', function ($q) {
  324. return $q->where(['Authors.id' => 1]);
  325. })->first();
  326. $this->assertEquals('TestPlugin.Comments', $result->source());
  327. $this->assertEquals('TestPlugin.Authors', $result->_matchingData['Authors']->source());
  328. }
  329. /**
  330. * Ensure that isEmpty() on a ResultSet doesn't result in loss
  331. * of records. This behavior is provided by CollectionTrait.
  332. *
  333. * @return void
  334. */
  335. public function testIsEmptyDoesNotConsumeData()
  336. {
  337. $table = TableRegistry::get('Comments');
  338. $query = $table->find()
  339. ->formatResults(function ($results) {
  340. return $results;
  341. });
  342. $res = $query->all();
  343. $res->isEmpty();
  344. $this->assertCount(6, $res->toArray());
  345. }
  346. }