HasOneTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM\Association;
  16. use Cake\Database\Expression\IdentifierExpression;
  17. use Cake\Database\Expression\QueryExpression;
  18. use Cake\Database\TypeMap;
  19. use Cake\ORM\Association\HasOne;
  20. use Cake\ORM\Entity;
  21. use Cake\TestSuite\TestCase;
  22. /**
  23. * Tests HasOne class
  24. */
  25. class HasOneTest extends TestCase
  26. {
  27. /**
  28. * Fixtures to load
  29. *
  30. * @var array
  31. */
  32. public $fixtures = ['core.Articles', 'core.NullableAuthors', 'core.Users', 'core.Profiles'];
  33. /**
  34. * @var bool
  35. */
  36. protected $listenerCalled = false;
  37. /**
  38. * Set up
  39. *
  40. * @return void
  41. */
  42. public function setUp()
  43. {
  44. parent::setUp();
  45. $this->user = $this->getTableLocator()->get('Users');
  46. $this->profile = $this->getTableLocator()->get('Profiles');
  47. $this->listenerCalled = false;
  48. }
  49. /**
  50. * Tests that foreignKey() returns the correct configured value
  51. *
  52. * @group deprecated
  53. * @return void
  54. */
  55. public function testForeignKey()
  56. {
  57. $this->deprecated(function () {
  58. $assoc = new HasOne('Profiles', [
  59. 'sourceTable' => $this->user,
  60. ]);
  61. $this->assertEquals('user_id', $assoc->foreignKey());
  62. $this->assertEquals('another_key', $assoc->foreignKey('another_key'));
  63. $this->assertEquals('another_key', $assoc->foreignKey());
  64. });
  65. }
  66. /**
  67. * Tests that setForeignKey() returns the correct configured value
  68. *
  69. * @return void
  70. */
  71. public function testSetForeignKey()
  72. {
  73. $assoc = new HasOne('Profiles', [
  74. 'sourceTable' => $this->user,
  75. ]);
  76. $this->assertEquals('user_id', $assoc->getForeignKey());
  77. $this->assertEquals($assoc, $assoc->setForeignKey('another_key'));
  78. $this->assertEquals('another_key', $assoc->getForeignKey());
  79. }
  80. /**
  81. * Tests that the association reports it can be joined
  82. *
  83. * @return void
  84. */
  85. public function testCanBeJoined()
  86. {
  87. $assoc = new HasOne('Test');
  88. $this->assertTrue($assoc->canBeJoined());
  89. }
  90. /**
  91. * Tests that the correct join and fields are attached to a query depending on
  92. * the association config
  93. *
  94. * @return void
  95. */
  96. public function testAttachTo()
  97. {
  98. $config = [
  99. 'foreignKey' => 'user_id',
  100. 'sourceTable' => $this->user,
  101. 'targetTable' => $this->profile,
  102. 'property' => 'profile',
  103. 'joinType' => 'INNER',
  104. 'conditions' => ['Profiles.is_active' => true],
  105. ];
  106. $association = new HasOne('Profiles', $config);
  107. $query = $this->user->find();
  108. $association->attachTo($query);
  109. $results = $query->order('Users.id')->toArray();
  110. $this->assertCount(1, $results, 'Only one record because of conditions & join type');
  111. $this->assertSame('masters', $results[0]->Profiles['last_name']);
  112. }
  113. /**
  114. * Tests that it is possible to avoid fields inclusion for the associated table
  115. *
  116. * @return void
  117. */
  118. public function testAttachToNoFields()
  119. {
  120. $config = [
  121. 'sourceTable' => $this->user,
  122. 'targetTable' => $this->profile,
  123. 'conditions' => ['Profiles.is_active' => true],
  124. ];
  125. $association = new HasOne('Profiles', $config);
  126. $query = $this->user->query();
  127. $association->attachTo($query, ['includeFields' => false]);
  128. $this->assertEmpty($query->clause('select'));
  129. }
  130. /**
  131. * Tests that using hasOne with a table having a multi column primary
  132. * key will work if the foreign key is passed
  133. *
  134. * @return void
  135. */
  136. public function testAttachToMultiPrimaryKey()
  137. {
  138. $selectTypeMap = new TypeMap([
  139. 'Profiles.id' => 'integer',
  140. 'id' => 'integer',
  141. 'Profiles.first_name' => 'string',
  142. 'first_name' => 'string',
  143. 'Profiles.user_id' => 'integer',
  144. 'user_id' => 'integer',
  145. 'Profiles__first_name' => 'string',
  146. 'Profiles__user_id' => 'integer',
  147. 'Profiles__id' => 'integer',
  148. 'Profiles__last_name' => 'string',
  149. 'Profiles.last_name' => 'string',
  150. 'last_name' => 'string',
  151. 'Profiles__is_active' => 'boolean',
  152. 'Profiles.is_active' => 'boolean',
  153. 'is_active' => 'boolean',
  154. ]);
  155. $config = [
  156. 'sourceTable' => $this->user,
  157. 'targetTable' => $this->profile,
  158. 'conditions' => ['Profiles.is_active' => true],
  159. 'foreignKey' => ['user_id', 'user_site_id'],
  160. ];
  161. $this->user->setPrimaryKey(['id', 'site_id']);
  162. $association = new HasOne('Profiles', $config);
  163. $query = $this->getMockBuilder('\Cake\ORM\Query')
  164. ->setMethods(['join', 'select'])
  165. ->disableOriginalConstructor()
  166. ->getMock();
  167. $field1 = new IdentifierExpression('Profiles.user_id');
  168. $field2 = new IdentifierExpression('Profiles.user_site_id');
  169. $query->expects($this->once())->method('join')->with([
  170. 'Profiles' => [
  171. 'conditions' => new QueryExpression([
  172. 'Profiles.is_active' => true,
  173. ['Users.id' => $field1, 'Users.site_id' => $field2],
  174. ], $selectTypeMap),
  175. 'type' => 'LEFT',
  176. 'table' => 'profiles',
  177. ],
  178. ]);
  179. $query->expects($this->never())->method('select');
  180. $association->attachTo($query, ['includeFields' => false]);
  181. }
  182. /**
  183. * Tests that using hasOne with a table having a multi column primary
  184. * key will work if the foreign key is passed
  185. *
  186. * @return void
  187. */
  188. public function testAttachToMultiPrimaryKeyMismatch()
  189. {
  190. $this->expectException(\RuntimeException::class);
  191. $this->expectExceptionMessage('Cannot match provided foreignKey for "Profiles", got "(user_id)" but expected foreign key for "(id, site_id)"');
  192. $query = $this->getMockBuilder('\Cake\ORM\Query')
  193. ->setMethods(['join', 'select'])
  194. ->disableOriginalConstructor()
  195. ->getMock();
  196. $config = [
  197. 'sourceTable' => $this->user,
  198. 'targetTable' => $this->profile,
  199. 'conditions' => ['Profiles.is_active' => true],
  200. ];
  201. $this->user->setPrimaryKey(['id', 'site_id']);
  202. $association = new HasOne('Profiles', $config);
  203. $association->attachTo($query, ['includeFields' => false]);
  204. }
  205. /**
  206. * Test that saveAssociated() ignores non entity values.
  207. *
  208. * @return void
  209. */
  210. public function testSaveAssociatedOnlyEntities()
  211. {
  212. $mock = $this->getMockBuilder('Cake\ORM\Table')
  213. ->setMethods(['saveAssociated'])
  214. ->disableOriginalConstructor()
  215. ->getMock();
  216. $config = [
  217. 'sourceTable' => $this->user,
  218. 'targetTable' => $mock,
  219. ];
  220. $mock->expects($this->never())
  221. ->method('saveAssociated');
  222. $entity = new Entity([
  223. 'username' => 'Mark',
  224. 'email' => 'mark@example.com',
  225. 'profile' => ['twitter' => '@cakephp'],
  226. ]);
  227. $association = new HasOne('Profiles', $config);
  228. $result = $association->saveAssociated($entity);
  229. $this->assertSame($result, $entity);
  230. }
  231. /**
  232. * Tests that property is being set using the constructor options.
  233. *
  234. * @return void
  235. */
  236. public function testPropertyOption()
  237. {
  238. $config = ['propertyName' => 'thing_placeholder'];
  239. $association = new hasOne('Thing', $config);
  240. $this->assertEquals('thing_placeholder', $association->getProperty());
  241. }
  242. /**
  243. * Test that plugin names are omitted from property()
  244. *
  245. * @return void
  246. */
  247. public function testPropertyNoPlugin()
  248. {
  249. $config = [
  250. 'sourceTable' => $this->user,
  251. 'targetTable' => $this->profile,
  252. ];
  253. $association = new HasOne('Contacts.Profiles', $config);
  254. $this->assertEquals('profile', $association->getProperty());
  255. }
  256. /**
  257. * Tests that attaching an association to a query will trigger beforeFind
  258. * for the target table
  259. *
  260. * @return void
  261. */
  262. public function testAttachToBeforeFind()
  263. {
  264. $config = [
  265. 'foreignKey' => 'user_id',
  266. 'sourceTable' => $this->user,
  267. 'targetTable' => $this->profile,
  268. ];
  269. $query = $this->user->query();
  270. $this->listenerCalled = false;
  271. $this->profile->getEventManager()->on('Model.beforeFind', function ($event, $query, $options, $primary) {
  272. $this->listenerCalled = true;
  273. $this->assertInstanceOf('\Cake\Event\Event', $event);
  274. $this->assertInstanceOf('\Cake\ORM\Query', $query);
  275. $this->assertInstanceOf('\ArrayObject', $options);
  276. $this->assertFalse($primary);
  277. });
  278. $association = new HasOne('Profiles', $config);
  279. $association->attachTo($query);
  280. $this->assertTrue($this->listenerCalled, 'beforeFind event not fired.');
  281. }
  282. /**
  283. * Tests that attaching an association to a query will trigger beforeFind
  284. * for the target table
  285. *
  286. * @return void
  287. */
  288. public function testAttachToBeforeFindExtraOptions()
  289. {
  290. $config = [
  291. 'foreignKey' => 'user_id',
  292. 'sourceTable' => $this->user,
  293. 'targetTable' => $this->profile,
  294. ];
  295. $this->listenerCalled = false;
  296. $opts = new \ArrayObject(['something' => 'more']);
  297. $this->profile->getEventManager()->on(
  298. 'Model.beforeFind',
  299. function ($event, $query, $options, $primary) use ($opts) {
  300. $this->listenerCalled = true;
  301. $this->assertInstanceOf('\Cake\Event\Event', $event);
  302. $this->assertInstanceOf('\Cake\ORM\Query', $query);
  303. $this->assertEquals($options, $opts);
  304. $this->assertFalse($primary);
  305. }
  306. );
  307. $association = new HasOne('Profiles', $config);
  308. $query = $this->user->find();
  309. $association->attachTo($query, ['queryBuilder' => function ($q) {
  310. return $q->applyOptions(['something' => 'more']);
  311. }]);
  312. $this->assertTrue($this->listenerCalled, 'Event not fired');
  313. }
  314. /**
  315. * Test cascading deletes.
  316. *
  317. * @return void
  318. */
  319. public function testCascadeDelete()
  320. {
  321. $config = [
  322. 'dependent' => true,
  323. 'sourceTable' => $this->user,
  324. 'targetTable' => $this->profile,
  325. 'conditions' => ['Profiles.is_active' => true],
  326. 'cascadeCallbacks' => false,
  327. ];
  328. $association = new HasOne('Profiles', $config);
  329. $this->profile->getEventManager()->on('Model.beforeDelete', function () {
  330. $this->fail('Callbacks should not be triggered when callbacks do not cascade.');
  331. });
  332. $entity = new Entity(['id' => 1]);
  333. $association->cascadeDelete($entity);
  334. $query = $this->profile->query()->where(['user_id' => 1]);
  335. $this->assertEquals(1, $query->count(), 'Left non-matching row behind');
  336. $query = $this->profile->query()->where(['user_id' => 3]);
  337. $this->assertEquals(1, $query->count(), 'other records left behind');
  338. $user = new Entity(['id' => 3]);
  339. $this->assertTrue($association->cascadeDelete($user));
  340. $query = $this->profile->query()->where(['user_id' => 3]);
  341. $this->assertEquals(0, $query->count(), 'Matching record was deleted.');
  342. }
  343. /**
  344. * Tests cascading deletes on entities with null binding and foreign key.
  345. */
  346. public function testCascadeDeleteNullBindingNullForeign()
  347. {
  348. $Articles = $this->getTableLocator()->get('Articles');
  349. $Authors = $this->getTableLocator()->get('NullableAuthors');
  350. $config = [
  351. 'dependent' => true,
  352. 'sourceTable' => $Authors,
  353. 'targetTable' => $Articles,
  354. 'bindingKey' => 'author_id',
  355. 'foreignKey' => 'author_id',
  356. 'cascadeCallbacks' => false,
  357. ];
  358. $association = $Authors->hasOne('Articles', $config);
  359. // create article with null foreign key
  360. $entity = new Entity(['author_id' => null, 'title' => 'this has no author', 'body' => 'I am abandoned', 'published' => 'N']);
  361. $Articles->save($entity);
  362. // get author with null binding key
  363. $entity = $Authors->get(2, ['contain' => 'Articles']);
  364. $this->assertNull($entity->article);
  365. $this->assertTrue($association->cascadeDelete($entity));
  366. $query = $Articles->query();
  367. $this->assertSame(4, $query->count(), 'No articles should be deleted');
  368. }
  369. /**
  370. * Test cascading delete with has one.
  371. *
  372. * @return void
  373. */
  374. public function testCascadeDeleteCallbacks()
  375. {
  376. $config = [
  377. 'dependent' => true,
  378. 'sourceTable' => $this->user,
  379. 'targetTable' => $this->profile,
  380. 'conditions' => ['Profiles.is_active' => true],
  381. 'cascadeCallbacks' => true,
  382. ];
  383. $association = new HasOne('Profiles', $config);
  384. $user = new Entity(['id' => 1]);
  385. $this->assertTrue($association->cascadeDelete($user));
  386. $query = $this->profile->query()->where(['user_id' => 1]);
  387. $this->assertEquals(1, $query->count(), 'Left non-matching row behind');
  388. $query = $this->profile->query()->where(['user_id' => 3]);
  389. $this->assertEquals(1, $query->count(), 'other records left behind');
  390. $user = new Entity(['id' => 3]);
  391. $this->assertTrue($association->cascadeDelete($user));
  392. $query = $this->profile->query()->where(['user_id' => 3]);
  393. $this->assertEquals(0, $query->count(), 'Matching record was deleted.');
  394. }
  395. }