Skip to content

Commit

Permalink
Add method for getting associations by type.
Browse files Browse the repository at this point in the history
A similar feature is used in bake & formhelper, I'm guessing we'll need
it again with the new ORM.
  • Loading branch information
markstory committed Dec 19, 2013
1 parent 829d358 commit f3f5bc9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
14 changes: 13 additions & 1 deletion Cake/ORM/Associations.php
Expand Up @@ -77,6 +77,18 @@ public function keys() {
return array_keys($this->_items);
}

/**
* Get an array of associations matching a specific type.
*
* @return array
*/
public function type($class) {
$out = array_filter($this->_items, function ($assoc) use ($class) {
return strpos(get_class($assoc), $class) !== false;
});
return array_values($out);
}

/**
* Drop/remove an association.
*
Expand All @@ -85,7 +97,7 @@ public function keys() {
* @param string The alias name.
* @return void
*/
public function drop($alias) {
public function remove($alias) {
unset($this->_items[strtolower($alias)]);
}

Expand Down
35 changes: 34 additions & 1 deletion Cake/Test/TestCase/ORM/AssociationsTest.php
Expand Up @@ -39,7 +39,7 @@ public function setUp() {
*
* @return void
*/
public function testAddHasAndGet() {
public function testAddHasRemoveAndGet() {
$this->assertFalse($this->associations->has('users'));
$this->assertFalse($this->associations->has('Users'));

Expand All @@ -53,6 +53,39 @@ public function testAddHasAndGet() {

$this->assertSame($belongsTo, $this->associations->get('users'));
$this->assertSame($belongsTo, $this->associations->get('Users'));

$this->assertNull($this->associations->remove('Users'));

$this->assertFalse($this->associations->has('users'));
$this->assertFalse($this->associations->has('Users'));
$this->assertNull($this->associations->get('users'));
$this->assertNull($this->associations->get('Users'));
}

/**
* Test keys()
*
* @return void
*/
public function testKeys() {
$belongsTo = new BelongsTo([]);
$this->associations->add('Users', $belongsTo);
$this->associations->add('Categories', $belongsTo);
$this->assertEquals(['users', 'categories'], $this->associations->keys());

$this->associations->remove('Categories');
$this->assertEquals(['users'], $this->associations->keys());
}

/**
* Test getting association names by type.
*/
public function testType() {
$belongsTo = new BelongsTo([]);
$this->associations->add('Users', $belongsTo);

$this->assertSame([$belongsTo], $this->associations->type('BelongsTo'));
$this->assertSame([], $this->associations->type('HasMany'));
}

/**
Expand Down

0 comments on commit f3f5bc9

Please sign in to comment.