Browse Source

Merge pull request #10161 from robertpustulka/assoc-name-setter

[RFC] Association name setter
José Lorenzo Rodríguez 9 years ago
parent
commit
77155c2fea
2 changed files with 43 additions and 0 deletions
  1. 7 0
      src/ORM/Association.php
  2. 36 0
      tests/TestCase/ORM/AssociationTest.php

+ 7 - 0
src/ORM/Association.php

@@ -245,6 +245,13 @@ abstract class Association
      */
     public function setName($name)
     {
+        if ($this->_targetTable !== null) {
+            $alias = $this->_targetTable->getAlias();
+            if ($alias !== $name) {
+                throw new InvalidArgumentException('Association name does not match target table alias.');
+            }
+        }
+
         $this->_name = $name;
 
         return $this;

+ 36 - 0
tests/TestCase/ORM/AssociationTest.php

@@ -111,6 +111,42 @@ class AssociationTest extends TestCase
     }
 
     /**
+     * Tests that setName() succeeds before the target table is resolved.
+     *
+     * @return void
+     */
+    public function testSetNameBeforeTarget()
+    {
+        $this->association->setName('Bar');
+        $this->assertEquals('Bar', $this->association->getName());
+    }
+
+    /**
+     * Tests that setName() fails after the target table is resolved.
+     *
+     * @expectedException \InvalidArgumentException
+     * @expectedExceptionMessage Association name does not match target table alias.
+     * @return void
+     */
+    public function testSetNameAfterTarger()
+    {
+        $this->association->getTarget();
+        $this->association->setName('Bar');
+    }
+
+    /**
+     * Tests that setName() succeeds if name equals target table alias.
+     *
+     * @return void
+     */
+    public function testSetNameToTargetAlias()
+    {
+        $alias = $this->association->getTarget()->getAlias();
+        $this->association->setName($alias);
+        $this->assertEquals($alias, $this->association->getName());
+    }
+
+    /**
      * Tests that className() returns the correct association className
      *
      * @return void