AssociationCollectionTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\ORM;
  17. use Cake\ORM\Association\BelongsTo;
  18. use Cake\ORM\Association\BelongsToMany;
  19. use Cake\ORM\AssociationCollection;
  20. use Cake\ORM\Entity;
  21. use Cake\ORM\Locator\LocatorInterface;
  22. use Cake\TestSuite\TestCase;
  23. use InvalidArgumentException;
  24. /**
  25. * AssociationCollection test case.
  26. */
  27. class AssociationCollectionTest extends TestCase
  28. {
  29. /**
  30. * @var AssociationCollection
  31. */
  32. protected $associations;
  33. /**
  34. * setup
  35. */
  36. public function setUp(): void
  37. {
  38. parent::setUp();
  39. $this->associations = new AssociationCollection();
  40. }
  41. /**
  42. * Test the constructor.
  43. */
  44. public function testConstructor(): void
  45. {
  46. $this->assertSame($this->getTableLocator(), $this->associations->getTableLocator());
  47. $tableLocator = $this->createMock(LocatorInterface::class);
  48. $associations = new AssociationCollection($tableLocator);
  49. $this->assertSame($tableLocator, $associations->getTableLocator());
  50. }
  51. /**
  52. * Test the simple add/has and get methods.
  53. */
  54. public function testAddHasRemoveAndGet(): void
  55. {
  56. $this->assertFalse($this->associations->has('users'));
  57. $this->assertFalse($this->associations->has('Users'));
  58. $this->assertNull($this->associations->get('users'));
  59. $this->assertNull($this->associations->get('Users'));
  60. $belongsTo = new BelongsTo('');
  61. $this->assertSame($belongsTo, $this->associations->add('Users', $belongsTo));
  62. $this->assertFalse($this->associations->has('users'));
  63. $this->assertTrue($this->associations->has('Users'));
  64. $this->assertSame($belongsTo, $this->associations->get('Users'));
  65. $this->associations->remove('Users');
  66. $this->assertFalse($this->associations->has('Users'));
  67. $this->assertNull($this->associations->get('Users'));
  68. }
  69. /**
  70. * Test the load method.
  71. */
  72. public function testLoad(): void
  73. {
  74. $this->associations->load(BelongsTo::class, 'Users');
  75. $this->assertTrue($this->associations->has('Users'));
  76. $this->assertInstanceOf(BelongsTo::class, $this->associations->get('Users'));
  77. $this->assertSame($this->associations->getTableLocator(), $this->associations->get('Users')->getTableLocator());
  78. }
  79. /**
  80. * Test the load method with custom locator.
  81. */
  82. public function testLoadCustomLocator(): void
  83. {
  84. $locator = $this->createMock(LocatorInterface::class);
  85. $this->associations->load(BelongsTo::class, 'Users', [
  86. 'tableLocator' => $locator,
  87. ]);
  88. $this->assertTrue($this->associations->has('Users'));
  89. $this->assertInstanceOf(BelongsTo::class, $this->associations->get('Users'));
  90. $this->assertSame($locator, $this->associations->get('Users')->getTableLocator());
  91. }
  92. /**
  93. * Test load invalid class.
  94. */
  95. public function testLoadInvalid(): void
  96. {
  97. $this->expectException(InvalidArgumentException::class);
  98. $this->expectExceptionMessage('The association must extend `Cake\ORM\Association` class, `stdClass` given.');
  99. $this->associations->load('stdClass', 'Users');
  100. }
  101. /**
  102. * Test removeAll method
  103. */
  104. public function testRemoveAll(): void
  105. {
  106. $this->assertEmpty($this->associations->keys());
  107. $belongsTo = new BelongsTo('');
  108. $this->assertSame($belongsTo, $this->associations->add('Users', $belongsTo));
  109. $belongsToMany = new BelongsToMany('');
  110. $this->assertSame($belongsToMany, $this->associations->add('Cart', $belongsToMany));
  111. $this->associations->removeAll();
  112. $this->assertEmpty($this->associations->keys());
  113. }
  114. /**
  115. * Test getting associations by property.
  116. */
  117. public function testGetByProperty(): void
  118. {
  119. $table = $this->getMockBuilder('Cake\ORM\Table')
  120. ->addMethods(['table'])
  121. ->getMock();
  122. $table->setSchema([]);
  123. $belongsTo = new BelongsTo('Users', [
  124. 'sourceTable' => $table,
  125. ]);
  126. $this->assertSame('user', $belongsTo->getProperty());
  127. $this->associations->add('Users', $belongsTo);
  128. $this->assertNull($this->associations->get('user'));
  129. $this->assertSame($belongsTo, $this->associations->getByProperty('user'));
  130. }
  131. /**
  132. * Test associations with plugin names.
  133. */
  134. public function testAddHasRemoveGetWithPlugin(): void
  135. {
  136. $this->assertFalse($this->associations->has('Photos.Photos'));
  137. $this->assertFalse($this->associations->has('Photos'));
  138. $belongsTo = new BelongsTo('');
  139. $this->assertSame($belongsTo, $this->associations->add('Photos.Photos', $belongsTo));
  140. $this->assertTrue($this->associations->has('Photos'));
  141. $this->assertFalse($this->associations->has('Photos.Photos'));
  142. }
  143. /**
  144. * Test keys()
  145. */
  146. public function testKeys(): void
  147. {
  148. $belongsTo = new BelongsTo('');
  149. $this->associations->add('Users', $belongsTo);
  150. $this->associations->add('Categories', $belongsTo);
  151. $this->assertEquals(['Users', 'Categories'], $this->associations->keys());
  152. $this->associations->remove('Categories');
  153. $this->assertEquals(['Users'], $this->associations->keys());
  154. }
  155. /**
  156. * Data provider for AssociationCollection::getByType
  157. */
  158. public function associationCollectionType(): array
  159. {
  160. return [
  161. ['BelongsTo', 'BelongsToMany'],
  162. ['belongsTo', 'belongsToMany'],
  163. ['belongsto', 'belongstomany'],
  164. ];
  165. }
  166. /**
  167. * Test getting association names by getByType.
  168. *
  169. * @param string $belongsToStr
  170. * @param string $belongsToManyStr
  171. * @dataProvider associationCollectionType
  172. */
  173. public function testGetByType($belongsToStr, $belongsToManyStr): void
  174. {
  175. $belongsTo = new BelongsTo('');
  176. $this->associations->add('Users', $belongsTo);
  177. $belongsToMany = new BelongsToMany('');
  178. $this->associations->add('Tags', $belongsToMany);
  179. $this->assertSame([$belongsTo], $this->associations->getByType($belongsToStr));
  180. $this->assertSame([$belongsToMany], $this->associations->getByType($belongsToManyStr));
  181. $this->assertSame([$belongsTo, $belongsToMany], $this->associations->getByType([$belongsToStr, $belongsToManyStr]));
  182. }
  183. /**
  184. * Type should return empty array.
  185. */
  186. public function hasTypeReturnsEmptyArray(): void
  187. {
  188. foreach (['HasMany', 'hasMany', 'FooBar', 'DoesNotExist'] as $value) {
  189. $this->assertSame([], $this->associations->getByType($value));
  190. }
  191. }
  192. /**
  193. * test cascading deletes.
  194. */
  195. public function testCascadeDelete(): void
  196. {
  197. $mockOne = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
  198. ->setConstructorArgs([''])
  199. ->getMock();
  200. $mockTwo = $this->getMockBuilder('Cake\ORM\Association\HasMany')
  201. ->setConstructorArgs([''])
  202. ->getMock();
  203. $entity = new Entity();
  204. $options = ['option' => 'value'];
  205. $this->associations->add('One', $mockOne);
  206. $this->associations->add('Two', $mockTwo);
  207. $mockOne->expects($this->once())
  208. ->method('cascadeDelete')
  209. ->with($entity, $options)
  210. ->willReturn(true);
  211. $mockTwo->expects($this->once())
  212. ->method('cascadeDelete')
  213. ->with($entity, $options)
  214. ->willReturn(true);
  215. $result = $this->associations->cascadeDelete($entity, $options);
  216. $this->assertTrue($result);
  217. }
  218. /**
  219. * Test saving parent associations
  220. */
  221. public function testSaveParents(): void
  222. {
  223. $table = $this->getMockBuilder('Cake\ORM\Table')
  224. ->addMethods(['table'])
  225. ->getMock();
  226. $table->setSchema([]);
  227. $mockOne = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
  228. ->onlyMethods(['saveAssociated'])
  229. ->setConstructorArgs(['Parent', [
  230. 'sourceTable' => $table,
  231. ]])
  232. ->getMock();
  233. $mockTwo = $this->getMockBuilder('Cake\ORM\Association\HasMany')
  234. ->onlyMethods(['saveAssociated'])
  235. ->setConstructorArgs(['Child', [
  236. 'sourceTable' => $table,
  237. ]])
  238. ->getMock();
  239. $this->associations->add('Parent', $mockOne);
  240. $this->associations->add('Child', $mockTwo);
  241. $entity = new Entity();
  242. $entity->set('parent', ['key' => 'value']);
  243. $entity->set('child', ['key' => 'value']);
  244. $options = ['option' => 'value'];
  245. $mockOne->expects($this->once())
  246. ->method('saveAssociated')
  247. ->with($entity, $options)
  248. ->will($this->returnValue($entity));
  249. $mockTwo->expects($this->never())
  250. ->method('saveAssociated');
  251. $result = $this->associations->saveParents(
  252. $table,
  253. $entity,
  254. ['Parent', 'Child'],
  255. $options
  256. );
  257. $this->assertTrue($result, 'Save should work.');
  258. }
  259. /**
  260. * Test saving filtered parent associations.
  261. */
  262. public function testSaveParentsFiltered(): void
  263. {
  264. $table = $this->getMockBuilder('Cake\ORM\Table')
  265. ->addMethods(['table'])
  266. ->getMock();
  267. $table->setSchema([]);
  268. $mockOne = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
  269. ->onlyMethods(['saveAssociated'])
  270. ->setConstructorArgs(['Parents', [
  271. 'sourceTable' => $table,
  272. ]])
  273. ->getMock();
  274. $mockTwo = $this->getMockBuilder('Cake\ORM\Association\BelongsTo')
  275. ->onlyMethods(['saveAssociated'])
  276. ->setConstructorArgs(['Categories', [
  277. 'sourceTable' => $table,
  278. ]])
  279. ->getMock();
  280. $this->associations->add('Parents', $mockOne);
  281. $this->associations->add('Categories', $mockTwo);
  282. $entity = new Entity();
  283. $entity->set('parent', ['key' => 'value']);
  284. $entity->set('category', ['key' => 'value']);
  285. $options = ['atomic' => true];
  286. $mockOne->expects($this->once())
  287. ->method('saveAssociated')
  288. ->with($entity, ['atomic' => true, 'associated' => ['Others']])
  289. ->will($this->returnValue($entity));
  290. $mockTwo->expects($this->never())
  291. ->method('saveAssociated');
  292. $result = $this->associations->saveParents(
  293. $table,
  294. $entity,
  295. ['Parents' => ['associated' => ['Others']]],
  296. $options
  297. );
  298. $this->assertTrue($result, 'Save should work.');
  299. }
  300. /**
  301. * Test saving filtered child associations.
  302. */
  303. public function testSaveChildrenFiltered(): void
  304. {
  305. $table = $this->getMockBuilder('Cake\ORM\Table')
  306. ->addMethods(['table'])
  307. ->getMock();
  308. $table->setSchema([]);
  309. $mockOne = $this->getMockBuilder('Cake\ORM\Association\HasMany')
  310. ->onlyMethods(['saveAssociated'])
  311. ->setConstructorArgs(['Comments', [
  312. 'sourceTable' => $table,
  313. ]])
  314. ->getMock();
  315. $mockTwo = $this->getMockBuilder('Cake\ORM\Association\HasOne')
  316. ->onlyMethods(['saveAssociated'])
  317. ->setConstructorArgs(['Profiles', [
  318. 'sourceTable' => $table,
  319. ]])
  320. ->getMock();
  321. $this->associations->add('Comments', $mockOne);
  322. $this->associations->add('Profiles', $mockTwo);
  323. $entity = new Entity();
  324. $entity->set('comments', ['key' => 'value']);
  325. $entity->set('profile', ['key' => 'value']);
  326. $options = ['atomic' => true];
  327. $mockOne->expects($this->once())
  328. ->method('saveAssociated')
  329. ->with($entity, $options + ['associated' => ['Other']])
  330. ->will($this->returnValue($entity));
  331. $mockTwo->expects($this->never())
  332. ->method('saveAssociated');
  333. $result = $this->associations->saveChildren(
  334. $table,
  335. $entity,
  336. ['Comments' => ['associated' => ['Other']]],
  337. $options
  338. );
  339. $this->assertTrue($result, 'Should succeed.');
  340. }
  341. /**
  342. * Test exceptional case.
  343. */
  344. public function testErrorOnUnknownAlias(): void
  345. {
  346. $this->expectException(InvalidArgumentException::class);
  347. $this->expectExceptionMessage('Cannot save Profiles, it is not associated to Users');
  348. $table = $this->getMockBuilder('Cake\ORM\Table')
  349. ->onlyMethods(['save'])
  350. ->setConstructorArgs([['alias' => 'Users']])
  351. ->getMock();
  352. $entity = new Entity();
  353. $entity->set('profile', ['key' => 'value']);
  354. $this->associations->saveChildren(
  355. $table,
  356. $entity,
  357. ['Profiles'],
  358. ['atomic' => true]
  359. );
  360. }
  361. /**
  362. * Tests the normalizeKeys method
  363. */
  364. public function testNormalizeKeys(): void
  365. {
  366. $this->assertSame([], $this->associations->normalizeKeys([]));
  367. $this->assertSame([], $this->associations->normalizeKeys(false));
  368. $assocs = ['a', 'b', 'd' => ['something']];
  369. $expected = ['a' => [], 'b' => [], 'd' => ['something']];
  370. $this->assertSame($expected, $this->associations->normalizeKeys($assocs));
  371. $belongsTo = new BelongsTo('');
  372. $this->associations->add('users', $belongsTo);
  373. $this->associations->add('categories', $belongsTo);
  374. $expected = ['users' => [], 'categories' => []];
  375. $this->assertSame($expected, $this->associations->normalizeKeys(true));
  376. }
  377. /**
  378. * Ensure that the association collection can be iterated.
  379. */
  380. public function testAssociationsCanBeIterated(): void
  381. {
  382. $belongsTo = new BelongsTo('');
  383. $this->associations->add('Users', $belongsTo);
  384. $belongsToMany = new BelongsToMany('');
  385. $this->associations->add('Cart', $belongsToMany);
  386. $expected = ['Users' => $belongsTo, 'Cart' => $belongsToMany];
  387. $result = iterator_to_array($this->associations, true);
  388. $this->assertSame($expected, $result);
  389. }
  390. }