Skip to content

Commit

Permalink
Fixing issues with magic finders in Model, now supports `find<Type>…
Browse files Browse the repository at this point in the history
…By<Field>()` and `findBy<Field>()`, where `type` defaults to `'first'`.
  • Loading branch information
nateabele authored and gwoo committed Mar 30, 2010
1 parent 7287e25 commit 39ade28
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
16 changes: 12 additions & 4 deletions libraries/lithium/data/Model.php
Expand Up @@ -12,6 +12,7 @@
use \lithium\util\Inflector;
use \RuntimeException;
use \UnexpectedValueException;
use \BadMethodCallException;

/**
* Model class
Expand Down Expand Up @@ -193,12 +194,19 @@ public static function __callStatic($method, $params) {
}
return $self::find($method, $params ? $params[0] : array());
}
$pattern = '/^findBy(?P<field>\w+)$|^find(?P<type>\w+)By(?P<fields>\w+)$/';

if (preg_match('/^find(?P<type>\w+)By(?P<fields>\w+)/', $method, $match)) {
$match['type'][0] = strtolower($match['type'][0]);
$type = $match['type'];
$fields = Inflector::underscore($match['fields']);
if (preg_match($pattern, $method, $m)) {
$field = Inflector::underscore($m['field'] ? $m['field'] : $m['fields']);
$type = isset($m['type']) ? $m['type'] : 'first';
$type[0] = strtolower($type[0]);

$conditions = array($field => array_shift($params));
return $self::find($type, compact('conditions') + $params);
}

$message = "Method %s not defined or handled in class %s";
throw new BadMethodCallException(sprintf($message, $method, get_class($self)));
}

/**
Expand Down
16 changes: 15 additions & 1 deletion libraries/lithium/tests/cases/data/ModelTest.php
Expand Up @@ -152,6 +152,20 @@ public function testSimpleFind() {
$this->assertTrue($result['query'] instanceof \lithium\data\model\Query);
}

public function testMagicFinders() {
$result = MockPost::findById(5);
$result2 = MockPost::findFirstById(5);
$this->assertEqual($result2, $result);

$expected = array('id' => 5);
$this->assertEqual($expected, $result['query']->conditions());

$this->assertEqual('read', $result['query']->type());

$this->expectException('/Method findFoo not defined or handled in class/');
MockPost::findFoo();
}

/**
* Tests the find 'first' filter on a simple record set.
*
Expand Down Expand Up @@ -184,7 +198,7 @@ public function testCustomFinder() {
}

public function testCustomFindMethods() {
print_r(MockPost::findFirstById());
// print_r(MockPost::findFirstById());
}

public function testKeyGeneration() {
Expand Down

0 comments on commit 39ade28

Please sign in to comment.