| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412 |
- <?php
- declare(strict_types=1);
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 3.0.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Test\TestCase\ORM\Association;
- use Cake\Database\Expression\OrderByExpression;
- use Cake\Database\Expression\QueryExpression;
- use Cake\Database\Expression\TupleComparison;
- use Cake\Database\IdentifierQuoter;
- use Cake\Database\TypeMap;
- use Cake\Datasource\ConnectionManager;
- use Cake\ORM\Association;
- use Cake\ORM\Association\HasMany;
- use Cake\ORM\Entity;
- use Cake\TestSuite\TestCase;
- /**
- * Tests HasMany class
- */
- class HasManyTest extends TestCase
- {
- /**
- * Fixtures
- *
- * @var array
- */
- public $fixtures = [
- 'core.Comments',
- 'core.Articles',
- 'core.Authors',
- 'core.ArticlesTags',
- 'core.Tags',
- ];
- /**
- * Set up
- *
- * @return void
- */
- public function setUp()
- {
- parent::setUp();
- $this->setAppNamespace('TestApp');
- $this->author = $this->getTableLocator()->get('Authors', [
- 'schema' => [
- 'id' => ['type' => 'integer'],
- 'name' => ['type' => 'string'],
- '_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id']],
- ],
- ],
- ]);
- $connection = ConnectionManager::get('test');
- $this->article = $this->getMockBuilder('Cake\ORM\Table')
- ->setMethods(['find', 'deleteAll', 'delete'])
- ->setConstructorArgs([['alias' => 'Articles', 'table' => 'articles', 'connection' => $connection]])
- ->getMock();
- $this->article->setSchema([
- 'id' => ['type' => 'integer'],
- 'title' => ['type' => 'string'],
- 'author_id' => ['type' => 'integer'],
- '_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id']],
- ],
- ]);
- $this->articlesTypeMap = new TypeMap([
- 'Articles.id' => 'integer',
- 'id' => 'integer',
- 'Articles.title' => 'string',
- 'title' => 'string',
- 'Articles.author_id' => 'integer',
- 'author_id' => 'integer',
- 'Articles__id' => 'integer',
- 'Articles__title' => 'string',
- 'Articles__author_id' => 'integer',
- ]);
- $this->autoQuote = $connection->getDriver()->isAutoQuotingEnabled();
- }
- /**
- * Tear down
- *
- * @return void
- */
- public function tearDown()
- {
- parent::tearDown();
- $this->getTableLocator()->clear();
- }
- /**
- * Tests that foreignKey() returns the correct configured value
- *
- * @return void
- */
- public function testSetForeignKey()
- {
- $assoc = new HasMany('Articles', [
- 'sourceTable' => $this->author,
- ]);
- $this->assertEquals('author_id', $assoc->getForeignKey());
- $this->assertSame($assoc, $assoc->setForeignKey('another_key'));
- $this->assertEquals('another_key', $assoc->getForeignKey());
- }
- /**
- * Test that foreignKey generation ignores database names in target table.
- *
- * @return void
- */
- public function testForeignKeyIgnoreDatabaseName()
- {
- $this->author->setTable('schema.authors');
- $assoc = new HasMany('Articles', [
- 'sourceTable' => $this->author,
- ]);
- $this->assertEquals('author_id', $assoc->getForeignKey());
- }
- /**
- * Tests that the association reports it can be joined
- *
- * @return void
- */
- public function testCanBeJoined()
- {
- $assoc = new HasMany('Test');
- $this->assertFalse($assoc->canBeJoined());
- }
- /**
- * Tests setSort() method
- *
- * @return void
- */
- public function testSetSort()
- {
- $assoc = new HasMany('Test');
- $this->assertNull($assoc->getSort());
- $assoc->setSort(['id' => 'ASC']);
- $this->assertEquals(['id' => 'ASC'], $assoc->getSort());
- }
- /**
- * Tests requiresKeys() method
- *
- * @return void
- */
- public function testRequiresKeys()
- {
- $assoc = new HasMany('Test');
- $this->assertTrue($assoc->requiresKeys());
- $assoc->setStrategy(HasMany::STRATEGY_SUBQUERY);
- $this->assertFalse($assoc->requiresKeys());
- $assoc->setStrategy(HasMany::STRATEGY_SELECT);
- $this->assertTrue($assoc->requiresKeys());
- }
- /**
- * Tests that HasMany can't use the join strategy
- *
- * @return void
- */
- public function testStrategyFailure()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Invalid strategy "join" was provided');
- $assoc = new HasMany('Test');
- $assoc->setStrategy(HasMany::STRATEGY_JOIN);
- }
- /**
- * Test the eager loader method with no extra options
- *
- * @return void
- */
- public function testEagerLoader()
- {
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $this->article,
- 'strategy' => 'select',
- ];
- $association = new HasMany('Articles', $config);
- $query = $this->article->query();
- $this->article->method('find')
- ->with('all')
- ->will($this->returnValue($query));
- $keys = [1, 2, 3, 4];
- $callable = $association->eagerLoader(compact('keys', 'query'));
- $row = ['Authors__id' => 1];
- $result = $callable($row);
- $this->assertArrayHasKey('Articles', $result);
- $this->assertEquals($row['Authors__id'], $result['Articles'][0]->author_id);
- $this->assertEquals($row['Authors__id'], $result['Articles'][1]->author_id);
- $row = ['Authors__id' => 2];
- $result = $callable($row);
- $this->assertArrayNotHasKey('Articles', $result);
- $row = ['Authors__id' => 3];
- $result = $callable($row);
- $this->assertArrayHasKey('Articles', $result);
- $this->assertEquals($row['Authors__id'], $result['Articles'][0]->author_id);
- $row = ['Authors__id' => 4];
- $result = $callable($row);
- $this->assertArrayNotHasKey('Articles', $result);
- }
- /**
- * Test the eager loader method with default query clauses
- *
- * @return void
- */
- public function testEagerLoaderWithDefaults()
- {
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $this->article,
- 'conditions' => ['Articles.published' => 'Y'],
- 'sort' => ['id' => 'ASC'],
- 'strategy' => 'select',
- ];
- $association = new HasMany('Articles', $config);
- $keys = [1, 2, 3, 4];
- $query = $this->article->query();
- $this->article->method('find')
- ->with('all')
- ->will($this->returnValue($query));
- $association->eagerLoader(compact('keys', 'query'));
- $expected = new QueryExpression(
- ['Articles.published' => 'Y', 'Articles.author_id IN' => $keys],
- $this->articlesTypeMap
- );
- $this->assertWhereClause($expected, $query);
- $expected = new OrderByExpression(['id' => 'ASC']);
- $this->assertOrderClause($expected, $query);
- }
- /**
- * Test the eager loader method with overridden query clauses
- *
- * @return void
- */
- public function testEagerLoaderWithOverrides()
- {
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $this->article,
- 'conditions' => ['Articles.published' => 'Y'],
- 'sort' => ['id' => 'ASC'],
- 'strategy' => 'select',
- ];
- $this->article->hasMany('Comments');
- $association = new HasMany('Articles', $config);
- $keys = [1, 2, 3, 4];
- /** @var \Cake\ORM\Query $query */
- $query = $this->article->query();
- $query->addDefaultTypes($this->article->Comments->getSource());
- $this->article->method('find')
- ->with('all')
- ->will($this->returnValue($query));
- $association->eagerLoader([
- 'conditions' => ['Articles.id !=' => 3],
- 'sort' => ['title' => 'DESC'],
- 'fields' => ['title', 'author_id'],
- 'contain' => ['Comments' => ['fields' => ['comment', 'article_id']]],
- 'keys' => $keys,
- 'query' => $query,
- ]);
- $expected = [
- 'Articles__title' => 'Articles.title',
- 'Articles__author_id' => 'Articles.author_id',
- ];
- $this->assertSelectClause($expected, $query);
- $expected = new QueryExpression(
- [
- 'Articles.published' => 'Y',
- 'Articles.id !=' => 3,
- 'Articles.author_id IN' => $keys,
- ],
- $query->getTypeMap()
- );
- $this->assertWhereClause($expected, $query);
- $expected = new OrderByExpression(['title' => 'DESC']);
- $this->assertOrderClause($expected, $query);
- $this->assertArrayHasKey('Comments', $query->getContain());
- }
- /**
- * Test that failing to add the foreignKey to the list of fields will throw an
- * exception
- *
- * @return void
- */
- public function testEagerLoaderFieldsException()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('You are required to select the "Articles.author_id"');
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $this->article,
- 'strategy' => 'select',
- ];
- $association = new HasMany('Articles', $config);
- $keys = [1, 2, 3, 4];
- $query = $this->article->query();
- $this->article->method('find')
- ->with('all')
- ->will($this->returnValue($query));
- $association->eagerLoader([
- 'fields' => ['id', 'title'],
- 'keys' => $keys,
- 'query' => $query,
- ]);
- }
- /**
- * Tests that eager loader accepts a queryBuilder option
- *
- * @return void
- */
- public function testEagerLoaderWithQueryBuilder()
- {
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $this->article,
- 'strategy' => 'select',
- ];
- $association = new HasMany('Articles', $config);
- $keys = [1, 2, 3, 4];
- /** @var \Cake\ORM\Query $query */
- $query = $this->article->query();
- $this->article->method('find')
- ->with('all')
- ->will($this->returnValue($query));
- $queryBuilder = function ($query) {
- return $query->select(['author_id'])->join('comments')->where(['comments.id' => 1]);
- };
- $association->eagerLoader(compact('keys', 'query', 'queryBuilder'));
- $expected = [
- 'Articles__author_id' => 'Articles.author_id',
- ];
- $this->assertSelectClause($expected, $query);
- $expected = [
- [
- 'type' => 'INNER',
- 'alias' => null,
- 'table' => 'comments',
- 'conditions' => new QueryExpression([], $query->getTypeMap()),
- ],
- ];
- $this->assertJoin($expected, $query);
- $expected = new QueryExpression(
- [
- 'Articles.author_id IN' => $keys,
- 'comments.id' => 1,
- ],
- $query->getTypeMap()
- );
- $this->assertWhereClause($expected, $query);
- }
- /**
- * Test the eager loader method with no extra options
- *
- * @return void
- */
- public function testEagerLoaderMultipleKeys()
- {
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $this->article,
- 'strategy' => 'select',
- 'foreignKey' => ['author_id', 'site_id'],
- ];
- $this->author->setPrimaryKey(['id', 'site_id']);
- $association = new HasMany('Articles', $config);
- $keys = [[1, 10], [2, 20], [3, 30], [4, 40]];
- $query = $this->getMockBuilder('Cake\ORM\Query')
- ->setMethods(['all', 'andWhere'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->article->method('find')
- ->with('all')
- ->will($this->returnValue($query));
- $results = [
- ['id' => 1, 'title' => 'article 1', 'author_id' => 2, 'site_id' => 10],
- ['id' => 2, 'title' => 'article 2', 'author_id' => 1, 'site_id' => 20],
- ];
- $query->method('all')
- ->will($this->returnValue($results));
- $tuple = new TupleComparison(
- ['Articles.author_id', 'Articles.site_id'],
- $keys,
- [],
- 'IN'
- );
- $query->expects($this->once())->method('andWhere')
- ->with($tuple)
- ->will($this->returnSelf());
- $callable = $association->eagerLoader(compact('keys', 'query'));
- $row = ['Authors__id' => 2, 'Authors__site_id' => 10, 'username' => 'author 1'];
- $result = $callable($row);
- $row['Articles'] = [
- ['id' => 1, 'title' => 'article 1', 'author_id' => 2, 'site_id' => 10],
- ];
- $this->assertEquals($row, $result);
- $row = ['Authors__id' => 1, 'username' => 'author 2', 'Authors__site_id' => 20];
- $result = $callable($row);
- $row['Articles'] = [
- ['id' => 2, 'title' => 'article 2', 'author_id' => 1, 'site_id' => 20],
- ];
- $this->assertEquals($row, $result);
- }
- /**
- * Test cascading deletes.
- *
- * @return void
- */
- public function testCascadeDelete()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $config = [
- 'dependent' => true,
- 'sourceTable' => $this->author,
- 'targetTable' => $articles,
- 'conditions' => ['Articles.published' => 'Y'],
- ];
- $association = new HasMany('Articles', $config);
- $entity = new Entity(['id' => 1, 'name' => 'PHP']);
- $this->assertTrue($association->cascadeDelete($entity));
- $published = $articles
- ->find('published')
- ->where([
- 'published' => 'Y',
- 'author_id' => 1,
- ]);
- $this->assertCount(0, $published->all());
- }
- /**
- * Test cascading deletes with a finder
- *
- * @return void
- */
- public function testCascadeDeleteFinder()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $config = [
- 'dependent' => true,
- 'sourceTable' => $this->author,
- 'targetTable' => $articles,
- 'finder' => 'published',
- ];
- // Exclude one record from the association finder
- $articles->updateAll(
- ['published' => 'N'],
- ['author_id' => 1, 'title' => 'First Article']
- );
- $association = new HasMany('Articles', $config);
- $entity = new Entity(['id' => 1, 'name' => 'PHP']);
- $this->assertTrue($association->cascadeDelete($entity));
- $published = $articles->find('published')->where(['author_id' => 1]);
- $this->assertCount(0, $published->all(), 'Associated records should be removed');
- $all = $articles->find()->where(['author_id' => 1]);
- $this->assertCount(1, $all->all(), 'Record not in association finder should remain');
- }
- /**
- * Test cascading delete with has many.
- *
- * @return void
- */
- public function testCascadeDeleteCallbacks()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $config = [
- 'dependent' => true,
- 'sourceTable' => $this->author,
- 'targetTable' => $articles,
- 'conditions' => ['Articles.published' => 'Y'],
- 'cascadeCallbacks' => true,
- ];
- $association = new HasMany('Articles', $config);
- $author = new Entity(['id' => 1, 'name' => 'mark']);
- $this->assertTrue($association->cascadeDelete($author));
- $query = $articles->query()->where(['author_id' => 1]);
- $this->assertEquals(0, $query->count(), 'Cleared related rows');
- $query = $articles->query()->where(['author_id' => 3]);
- $this->assertEquals(1, $query->count(), 'other records left behind');
- }
- /**
- * Test that saveAssociated() ignores non entity values.
- *
- * @return void
- */
- public function testSaveAssociatedOnlyEntities()
- {
- $mock = $this->getMockBuilder('Cake\ORM\Table')
- ->setMethods(['saveAssociated'])
- ->disableOriginalConstructor()
- ->getMock();
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $mock,
- ];
- $entity = new Entity([
- 'username' => 'Mark',
- 'email' => 'mark@example.com',
- 'articles' => [
- ['title' => 'First Post'],
- new Entity(['title' => 'Second Post']),
- ],
- ]);
- $mock->expects($this->never())
- ->method('saveAssociated');
- $association = new HasMany('Articles', $config);
- $association->saveAssociated($entity);
- }
- /**
- * Tests that property is being set using the constructor options.
- *
- * @return void
- */
- public function testPropertyOption()
- {
- $config = ['propertyName' => 'thing_placeholder'];
- $association = new HasMany('Thing', $config);
- $this->assertEquals('thing_placeholder', $association->getProperty());
- }
- /**
- * Test that plugin names are omitted from property()
- *
- * @return void
- */
- public function testPropertyNoPlugin()
- {
- $mock = $this->getMockBuilder('Cake\ORM\Table')
- ->disableOriginalConstructor()
- ->getMock();
- $config = [
- 'sourceTable' => $this->author,
- 'targetTable' => $mock,
- ];
- $association = new HasMany('Contacts.Addresses', $config);
- $this->assertEquals('addresses', $association->getProperty());
- }
- /**
- * Test that the ValueBinder is reset when using strategy = Association::STRATEGY_SUBQUERY
- *
- * @return void
- */
- public function testValueBinderUpdateOnSubQueryStrategy()
- {
- $Authors = $this->getTableLocator()->get('Authors');
- $Authors->hasMany('Articles', [
- 'strategy' => Association::STRATEGY_SUBQUERY,
- ]);
- $query = $Authors->find();
- $authorsAndArticles = $query
- ->select([
- 'id',
- 'slug' => $query->func()->concat([
- '---',
- 'name' => 'identifier',
- ]),
- ])
- ->contain('Articles')
- ->where(['name' => 'mariano'])
- ->first();
- $this->assertCount(2, $authorsAndArticles->get('articles'));
- }
- /**
- * Assertion method for order by clause contents.
- *
- * @param array $expected The expected join clause.
- * @param \Cake\ORM\Query $query The query to check.
- * @return void
- */
- protected function assertJoin($expected, $query)
- {
- if ($this->autoQuote) {
- $driver = $query->getConnection()->getDriver();
- $quoter = new IdentifierQuoter($driver);
- foreach ($expected as &$join) {
- $join['table'] = $driver->quoteIdentifier($join['table']);
- if ($join['conditions']) {
- $quoter->quoteExpression($join['conditions']);
- }
- }
- }
- $this->assertEquals($expected, array_values($query->clause('join')));
- }
- /**
- * Assertion method for where clause contents.
- *
- * @param \Cake\Database\QueryExpression $expected The expected where clause.
- * @param \Cake\ORM\Query $query The query to check.
- * @return void
- */
- protected function assertWhereClause($expected, $query)
- {
- if ($this->autoQuote) {
- $quoter = new IdentifierQuoter($query->getConnection()->getDriver());
- $expected->traverse([$quoter, 'quoteExpression']);
- }
- $this->assertEquals($expected, $query->clause('where'));
- }
- /**
- * Assertion method for order by clause contents.
- *
- * @param \Cake\Database\QueryExpression $expected The expected where clause.
- * @param \Cake\ORM\Query $query The query to check.
- * @return void
- */
- protected function assertOrderClause($expected, $query)
- {
- if ($this->autoQuote) {
- $quoter = new IdentifierQuoter($query->getConnection()->getDriver());
- $quoter->quoteExpression($expected);
- }
- $this->assertEquals($expected, $query->clause('order'));
- }
- /**
- * Assertion method for select clause contents.
- *
- * @param array $expected Array of expected fields.
- * @param \Cake\ORM\Query $query The query to check.
- * @return void
- */
- protected function assertSelectClause($expected, $query)
- {
- if ($this->autoQuote) {
- $connection = $query->getConnection();
- foreach ($expected as $key => $value) {
- $expected[$connection->quoteIdentifier($key)] = $connection->quoteIdentifier($value);
- unset($expected[$key]);
- }
- }
- $this->assertEquals($expected, $query->clause('select'));
- }
- /**
- * Tests that unlinking calls the right methods
- *
- * @return void
- */
- public function testUnlinkSuccess()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $assoc = $this->author->hasMany('Articles', [
- 'sourceTable' => $this->author,
- 'targetTable' => $articles,
- ]);
- $entity = $this->author->get(1, ['contain' => 'Articles']);
- $initial = $entity->articles;
- $this->assertCount(2, $initial);
- $assoc->unlink($entity, $entity->articles);
- $this->assertEmpty($entity->get('articles'), 'Property should be empty');
- $new = $this->author->get(2, ['contain' => 'Articles']);
- $this->assertCount(0, $new->articles, 'DB should be clean');
- $this->assertSame(4, $this->author->find()->count(), 'Authors should still exist');
- $this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
- }
- /**
- * Tests that unlink with an empty array does nothing
- *
- * @return void
- */
- public function testUnlinkWithEmptyArray()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $assoc = $this->author->hasMany('Articles', [
- 'sourceTable' => $this->author,
- 'targetTable' => $articles,
- ]);
- $entity = $this->author->get(1, ['contain' => 'Articles']);
- $initial = $entity->articles;
- $this->assertCount(2, $initial);
- $assoc->unlink($entity, []);
- $new = $this->author->get(1, ['contain' => 'Articles']);
- $this->assertCount(2, $new->articles, 'Articles should remain linked');
- $this->assertSame(4, $this->author->find()->count(), 'Authors should still exist');
- $this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
- }
- /**
- * Tests that link only uses a single database transaction
- *
- * @return void
- */
- public function testLinkUsesSingleTransaction()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $assoc = $this->author->hasMany('Articles', [
- 'sourceTable' => $this->author,
- 'targetTable' => $articles,
- ]);
- // Ensure author in fixture has zero associated articles
- $entity = $this->author->get(2, ['contain' => 'Articles']);
- $initial = $entity->articles;
- $this->assertCount(0, $initial);
- // Ensure that after each model is saved, we are still within a transaction.
- $listenerAfterSave = function ($e, $entity, $options) use ($articles) {
- $this->assertTrue(
- $articles->getConnection()->inTransaction(),
- 'Multiple transactions used to save associated models.'
- );
- };
- $articles->getEventManager()->on('Model.afterSave', $listenerAfterSave);
- $options = ['atomic' => false];
- $assoc->link($entity, $articles->find('all')->toArray(), $options);
- // Ensure that link was successful.
- $new = $this->author->get(2, ['contain' => 'Articles']);
- $this->assertCount(3, $new->articles);
- }
- /**
- * Test that saveAssociated() fails on non-empty, non-iterable value
- *
- * @return void
- */
- public function testSaveAssociatedNotEmptyNotIterable()
- {
- $this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Could not save comments, it cannot be traversed');
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments', [
- 'saveStrategy' => HasMany::SAVE_APPEND,
- ]);
- $entity = $articles->newEntity();
- $entity->set('comments', 'oh noes');
- $association->saveAssociated($entity);
- }
- /**
- * Data provider for empty values.
- *
- * @return array
- */
- public function emptySetDataProvider()
- {
- return [
- [''],
- [false],
- [null],
- [[]],
- ];
- }
- /**
- * Test that saving empty sets with the `append` strategy does not
- * affect the associated records for not yet persisted parent entities.
- *
- * @dataProvider emptySetDataProvider
- * @param mixed $value Empty value.
- * @return void
- */
- public function testSaveAssociatedEmptySetWithAppendStrategyDoesNotAffectAssociatedRecordsOnCreate($value)
- {
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments', [
- 'saveStrategy' => HasMany::SAVE_APPEND,
- ]);
- $comments = $association->find();
- $this->assertNotEmpty($comments);
- $entity = $articles->newEntity();
- $entity->set('comments', $value);
- $this->assertSame($entity, $association->saveAssociated($entity));
- $this->assertEquals($value, $entity->get('comments'));
- $this->assertEquals($comments, $association->find());
- }
- /**
- * Test that saving empty sets with the `append` strategy does not
- * affect the associated records for already persisted parent entities.
- *
- * @dataProvider emptySetDataProvider
- * @param mixed $value Empty value.
- * @return void
- */
- public function testSaveAssociatedEmptySetWithAppendStrategyDoesNotAffectAssociatedRecordsOnUpdate($value)
- {
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments', [
- 'saveStrategy' => HasMany::SAVE_APPEND,
- ]);
- $entity = $articles->get(1, [
- 'contain' => ['Comments'],
- ]);
- $comments = $entity->get('comments');
- $this->assertNotEmpty($comments);
- $entity->set('comments', $value);
- $this->assertSame($entity, $association->saveAssociated($entity));
- $this->assertEquals($value, $entity->get('comments'));
- $entity = $articles->get(1, [
- 'contain' => ['Comments'],
- ]);
- $this->assertEquals($comments, $entity->get('comments'));
- }
- /**
- * Test that saving empty sets with the `replace` strategy does not
- * affect the associated records for not yet persisted parent entities.
- *
- * @dataProvider emptySetDataProvider
- * @param mixed $value Empty value.
- * @return void
- */
- public function testSaveAssociatedEmptySetWithReplaceStrategyDoesNotAffectAssociatedRecordsOnCreate($value)
- {
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments', [
- 'saveStrategy' => HasMany::SAVE_REPLACE,
- ]);
- $comments = $association->find();
- $this->assertNotEmpty($comments);
- $entity = $articles->newEntity();
- $entity->set('comments', $value);
- $this->assertSame($entity, $association->saveAssociated($entity));
- $this->assertEquals($value, $entity->get('comments'));
- $this->assertEquals($comments, $association->find());
- }
- /**
- * Test that saving empty sets with the `replace` strategy does remove
- * the associated records for already persisted parent entities.
- *
- * @dataProvider emptySetDataProvider
- * @param mixed $value Empty value.
- * @return void
- */
- public function testSaveAssociatedEmptySetWithReplaceStrategyRemovesAssociatedRecordsOnUpdate($value)
- {
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments', [
- 'saveStrategy' => HasMany::SAVE_REPLACE,
- ]);
- $entity = $articles->get(1, [
- 'contain' => ['Comments'],
- ]);
- $comments = $entity->get('comments');
- $this->assertNotEmpty($comments);
- $entity->set('comments', $value);
- $this->assertSame($entity, $association->saveAssociated($entity));
- $this->assertEquals([], $entity->get('comments'));
- $entity = $articles->get(1, [
- 'contain' => ['Comments'],
- ]);
- $this->assertEmpty($entity->get('comments'));
- }
- /**
- * Tests that providing an invalid strategy throws an exception
- *
- * @return void
- */
- public function testInvalidSaveStrategy()
- {
- $this->expectException(\InvalidArgumentException::class);
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments');
- $association->setSaveStrategy('anotherThing');
- }
- /**
- * Tests saveStrategy
- *
- * @return void
- */
- public function testSetSaveStrategy()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $association = $articles->hasMany('Comments');
- $this->assertSame($association, $association->setSaveStrategy(HasMany::SAVE_REPLACE));
- $this->assertSame(HasMany::SAVE_REPLACE, $association->getSaveStrategy());
- }
- /**
- * Test that save works with replace saveStrategy and are not deleted once they are not null
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategy()
- {
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE]);
- $entity = $authors->newEntity([
- 'name' => 'mylux',
- 'articles' => [
- ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
- ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
- ['title' => 'One more random post', 'body' => 'The cake is forever'],
- ],
- ], ['associated' => ['Articles']]);
- $entity = $authors->save($entity, ['associated' => ['Articles']]);
- $sizeArticles = count($entity->articles);
- $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $articleId = $entity->articles[0]->id;
- unset($entity->articles[0]);
- $entity->setDirty('articles', true);
- $authors->save($entity, ['associated' => ['Articles']]);
- $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
- }
- /**
- * Test that save works with replace saveStrategy, replacing the already persisted entities even if no new entities are passed
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategyNotAdding()
- {
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', ['saveStrategy' => 'replace']);
- $entity = $authors->newEntity([
- 'name' => 'mylux',
- 'articles' => [
- ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
- ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
- ['title' => 'One more random post', 'body' => 'The cake is forever'],
- ],
- ], ['associated' => ['Articles']]);
- $entity = $authors->save($entity, ['associated' => ['Articles']]);
- $sizeArticles = count($entity->articles);
- $this->assertCount($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
- $entity->set('articles', []);
- $entity = $authors->save($entity, ['associated' => ['Articles']]);
- $this->assertCount(0, $authors->Articles->find('all')->where(['author_id' => $entity['id']]));
- }
- /**
- * Test that save works with append saveStrategy not deleting or setting null anything
- *
- * @return void
- */
- public function testSaveAppendSaveStrategy()
- {
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', ['saveStrategy' => 'append']);
- $entity = $authors->newEntity([
- 'name' => 'mylux',
- 'articles' => [
- ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
- ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
- ['title' => 'One more random post', 'body' => 'The cake is forever'],
- ],
- ], ['associated' => ['Articles']]);
- $entity = $authors->save($entity, ['associated' => ['Articles']]);
- $sizeArticles = count($entity->articles);
- $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $articleId = $entity->articles[0]->id;
- unset($entity->articles[0]);
- $entity->setDirty('articles', true);
- $authors->save($entity, ['associated' => ['Articles']]);
- $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $this->assertTrue($authors->Articles->exists(['id' => $articleId]));
- }
- /**
- * Test that save has append as the default save strategy
- *
- * @return void
- */
- public function testSaveDefaultSaveStrategy()
- {
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_APPEND]);
- $this->assertEquals(HasMany::SAVE_APPEND, $authors->getAssociation('articles')->getSaveStrategy());
- }
- /**
- * Test that the associated entities are unlinked and deleted when they are dependent
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategyDependent()
- {
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE, 'dependent' => true]);
- $entity = $authors->newEntity([
- 'name' => 'mylux',
- 'articles' => [
- ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
- ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
- ['title' => 'One more random post', 'body' => 'The cake is forever'],
- ],
- ], ['associated' => ['Articles']]);
- $entity = $authors->save($entity, ['associated' => ['Articles']]);
- $sizeArticles = count($entity->articles);
- $this->assertEquals($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $articleId = $entity->articles[0]->id;
- unset($entity->articles[0]);
- $entity->setDirty('articles', true);
- $authors->save($entity, ['associated' => ['Articles']]);
- $this->assertEquals($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
- }
- /**
- * Test that the associated entities are unlinked and deleted when they are dependent
- * when associated entities array is indexed by string keys
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategyDependentWithStringKeys()
- {
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', ['saveStrategy' => HasMany::SAVE_REPLACE, 'dependent' => true]);
- $entity = $authors->newEntity([
- 'name' => 'mylux',
- 'articles' => [
- ['title' => 'One Random Post', 'body' => 'The cake is not a lie'],
- ['title' => 'Another Random Post', 'body' => 'The cake is nice'],
- ['title' => 'One more random post', 'body' => 'The cake is forever'],
- ],
- ], ['associated' => ['Articles']]);
- $entity = $authors->saveOrFail($entity, ['associated' => ['Articles']]);
- $sizeArticles = count($entity->articles);
- $this->assertSame($sizeArticles, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $articleId = $entity->articles[0]->id;
- $entity->articles = [
- 'one' => $entity->articles[1],
- 'two' => $entity->articles[2],
- ];
- $authors->saveOrFail($entity, ['associated' => ['Articles']]);
- $this->assertSame($sizeArticles - 1, $authors->Articles->find('all')->where(['author_id' => $entity['id']])->count());
- $this->assertFalse($authors->Articles->exists(['id' => $articleId]));
- }
- /**
- * Test that the associated entities are unlinked and deleted when they are dependent
- *
- * In the future this should change and apply the finder.
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategyDependentWithConditions()
- {
- $this->getTableLocator()->clear();
- $this->setAppNamespace('TestApp');
- $authors = $this->getTableLocator()->get('Authors');
- $authors->hasMany('Articles', [
- 'finder' => 'published',
- 'saveStrategy' => HasMany::SAVE_REPLACE,
- 'dependent' => true,
- ]);
- $articles = $authors->Articles->getTarget();
- // Remove an article from the association finder scope
- $articles->updateAll(['published' => 'N'], ['author_id' => 1, 'title' => 'Third Article']);
- $entity = $authors->get(1, ['contain' => ['Articles']]);
- $data = [
- 'name' => 'updated',
- 'articles' => [
- ['title' => 'New First', 'body' => 'New First', 'published' => 'Y'],
- ],
- ];
- $entity = $authors->patchEntity($entity, $data, ['associated' => ['Articles']]);
- $entity = $authors->save($entity, ['associated' => ['Articles']]);
- // Should only have one article left as we 'replaced' the others.
- $this->assertCount(1, $entity->articles);
- // No additional records in db.
- $this->assertCount(
- 1,
- $authors->Articles->find()->where(['author_id' => 1])->toArray()
- );
- $others = $articles->find('all')
- ->where(['Articles.author_id' => 1, 'published' => 'N'])
- ->orderAsc('title')
- ->toArray();
- $this->assertCount(
- 1,
- $others,
- 'Record not matching association condition should stay'
- );
- $this->assertSame('Third Article', $others[0]->title);
- }
- /**
- * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategyNotNullable()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $articles->hasMany('Comments', ['saveStrategy' => HasMany::SAVE_REPLACE]);
- $article = $articles->newEntity([
- 'title' => 'Bakeries are sky rocketing',
- 'body' => 'All because of cake',
- 'comments' => [
- [
- 'user_id' => 1,
- 'comment' => 'That is true!',
- ],
- [
- 'user_id' => 2,
- 'comment' => 'Of course',
- ],
- ],
- ], ['associated' => ['Comments']]);
- $article = $articles->save($article, ['associated' => ['Comments']]);
- $commentId = $article->comments[0]->id;
- $sizeComments = count($article->comments);
- $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
- $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
- unset($article->comments[0]);
- $article->setDirty('comments', true);
- $article = $articles->save($article, ['associated' => ['Comments']]);
- $this->assertEquals($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
- $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
- }
- /**
- * Test that the associated entities are unlinked and deleted when they have a not nullable foreign key
- *
- * @return void
- */
- public function testSaveReplaceSaveStrategyAdding()
- {
- $articles = $this->getTableLocator()->get('Articles');
- $articles->hasMany('Comments', ['saveStrategy' => HasMany::SAVE_REPLACE]);
- $article = $articles->newEntity([
- 'title' => 'Bakeries are sky rocketing',
- 'body' => 'All because of cake',
- 'comments' => [
- [
- 'user_id' => 1,
- 'comment' => 'That is true!',
- ],
- [
- 'user_id' => 2,
- 'comment' => 'Of course',
- ],
- ],
- ], ['associated' => ['Comments']]);
- $article = $articles->save($article, ['associated' => ['Comments']]);
- $commentId = $article->comments[0]->id;
- $sizeComments = count($article->comments);
- $articleId = $article->id;
- $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
- $this->assertTrue($articles->Comments->exists(['id' => $commentId]));
- unset($article->comments[0]);
- $article->comments[] = $articles->Comments->newEntity([
- 'user_id' => 1,
- 'comment' => 'new comment',
- ]);
- $article->setDirty('comments', true);
- $article = $articles->save($article, ['associated' => ['Comments']]);
- $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count());
- $this->assertFalse($articles->Comments->exists(['id' => $commentId]));
- $this->assertTrue($articles->Comments->exists(['comment' => 'new comment', 'article_id' => $articleId]));
- }
- /**
- * Tests that dependent, non-cascading deletes are using the association
- * conditions for deleting associated records.
- *
- * @return void
- */
- public function testHasManyNonCascadingUnlinkDeleteUsesAssociationConditions()
- {
- $Articles = $this->getTableLocator()->get('Articles');
- $Comments = $Articles->hasMany('Comments', [
- 'dependent' => true,
- 'cascadeCallbacks' => false,
- 'saveStrategy' => HasMany::SAVE_REPLACE,
- 'conditions' => [
- 'Comments.published' => 'Y',
- ],
- ]);
- $article = $Articles->newEntity([
- 'title' => 'Title',
- 'body' => 'Body',
- 'comments' => [
- [
- 'user_id' => 1,
- 'comment' => 'First comment',
- 'published' => 'Y',
- ],
- [
- 'user_id' => 1,
- 'comment' => 'Second comment',
- 'published' => 'Y',
- ],
- ],
- ]);
- $article = $Articles->save($article);
- $this->assertNotEmpty($article);
- $comment3 = $Comments->getTarget()->newEntity([
- 'article_id' => $article->get('id'),
- 'user_id' => 1,
- 'comment' => 'Third comment',
- 'published' => 'N',
- ]);
- $comment3 = $Comments->getTarget()->save($comment3);
- $this->assertNotEmpty($comment3);
- $this->assertEquals(3, $Comments->getTarget()->find()->where(['Comments.article_id' => $article->get('id')])->count());
- unset($article->comments[1]);
- $article->setDirty('comments', true);
- $article = $Articles->save($article);
- $this->assertNotEmpty($article);
- // Given the association condition of `'Comments.published' => 'Y'`,
- // it is expected that only one of the three linked comments are
- // actually being deleted, as only one of them matches the
- // association condition.
- $this->assertEquals(2, $Comments->getTarget()->find()->where(['Comments.article_id' => $article->get('id')])->count());
- }
- /**
- * Tests that non-dependent, non-cascading deletes are using the association
- * conditions for updating associated records.
- *
- * @return void
- */
- public function testHasManyNonDependentNonCascadingUnlinkUpdateUsesAssociationConditions()
- {
- $Authors = $this->getTableLocator()->get('Authors');
- $Authors->associations()->removeAll();
- $Articles = $Authors->hasMany('Articles', [
- 'dependent' => false,
- 'cascadeCallbacks' => false,
- 'saveStrategy' => HasMany::SAVE_REPLACE,
- 'conditions' => [
- 'Articles.published' => 'Y',
- ],
- ]);
- $author = $Authors->newEntity([
- 'name' => 'Name',
- 'articles' => [
- [
- 'title' => 'First article',
- 'body' => 'First article',
- 'published' => 'Y',
- ],
- [
- 'title' => 'Second article',
- 'body' => 'Second article',
- 'published' => 'Y',
- ],
- ],
- ]);
- $author = $Authors->save($author);
- $this->assertNotEmpty($author);
- $article3 = $Articles->getTarget()->newEntity([
- 'author_id' => $author->get('id'),
- 'title' => 'Third article',
- 'body' => 'Third article',
- 'published' => 'N',
- ]);
- $article3 = $Articles->getTarget()->save($article3);
- $this->assertNotEmpty($article3);
- $this->assertEquals(3, $Articles->getTarget()->find()->where(['Articles.author_id' => $author->get('id')])->count());
- $article2 = $author->articles[1];
- unset($author->articles[1]);
- $author->setDirty('articles', true);
- $author = $Authors->save($author);
- $this->assertNotEmpty($author);
- // Given the association condition of `'Articles.published' => 'Y'`,
- // it is expected that only one of the three linked articles are
- // actually being unlinked (nulled), as only one of them matches the
- // association condition.
- $this->assertEquals(2, $Articles->getTarget()->find()->where(['Articles.author_id' => $author->get('id')])->count());
- $this->assertNull($Articles->get($article2->get('id'))->get('author_id'));
- $this->assertEquals($author->get('id'), $Articles->get($article3->get('id'))->get('author_id'));
- }
- }
|