From bfa3b9c58c2e749e69f919e8428002f9dd48bf2d Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Sun, 23 Mar 2014 00:01:49 +0100 Subject: [PATCH] Associations can now be fetched as properties in a table --- src/ORM/Table.php | 31 +++++++++++++++++++++++++++++++ tests/TestCase/ORM/TableTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/ORM/Table.php b/src/ORM/Table.php index acf62113922..ab60e1e5d98 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -1500,6 +1500,37 @@ public function __call($method, $args) { ); } +/** + * Returns the association named after the passed value if exists, otherwise + * throws an exception. + * + * @param string $property the association name + * @return \Cake\ORM\Association + * @throws \RuntimeException if no association with such name exists + */ + public function __get($property) { + $association = $this->_associations->get($property); + if (!$association) { + throw new \RuntimeException(sprintf( + 'Table "%s" is not associated with "%s"', + get_class($this), + $property + )); + } + return $association; + } + +/** + * Returns whether an association named after the passed value + * exists for this table. + * + * @param string $property the association name + * @return boolean + */ + public function __isset($property) { + return $this->_associations->has($property); + } + /** * Get the object used to marshal/convert array data into objects. * diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index ffb237e29ac..9b953ea4fde 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -3274,4 +3274,31 @@ public function testDebugInfo() { $this->assertEquals($expected, $result); } +/** + * Tests that it is possible to get associations as a property + * + * @return void + */ + public function testAssociationAsProperty() { + $articles = TableRegistry::get('articles'); + $articles->hasMany('comments'); + $articles->belongsTo('authors'); + $this->assertTrue(isset($articles->authors)); + $this->assertTrue(isset($articles->comments)); + $this->assertFalse(isset($articles->posts)); + $this->assertSame($articles->association('authors'), $articles->authors); + $this->assertSame($articles->association('comments'), $articles->comments); + } + +/** + * Tests that getting a bad property throws exception + * + * @expectedException \RuntimeException + * @expectedExceptionMessage Table "TestApp\Model\Table\ArticlesTable" is not associated with "posts" + * @return void + */ + public function testGetBadAssociation() { + $articles = TableRegistry::get('articles'); + $articles->posts; + } }