Cleaning up PR and adding tests

This commit is contained in:
Daniel Hensby 2018-02-28 13:25:28 +00:00
parent 559254407f
commit 9006daf20b
No known key found for this signature in database
GPG Key ID: B00D1E9767F0B06E
2 changed files with 25 additions and 9 deletions

View File

@ -3175,22 +3175,24 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
/** /**
* Return the given element, searching by ID * Return the given element, searching by ID
* *
* @param string $callerClass The class of the object to be returned (optional if called from extending class) * @param string|int $callerClassOrID The class of the object to be returned (optional if called from extending class)
* @param int $id The id of the element * @param int|bool $id The id of the element or bool to represent cache if ID is passed as fist argument
* @param boolean $cache See {@link get_one()} * @param bool $cache See {@link get_one()}
* *
* @return DataObject The element * @return static The element
*/ */
public static function get_by_id($callerClass, $id = null, $cache = true) public static function get_by_id($callerClassOrID, $id = null, $cache = true)
{ {
if(is_numeric($callerClass)) { if (is_numeric($callerClassOrID)) {
// Alternate signature to allow calling as MyDataObject::get_by_id($id) // Alternate signature to allow calling as MyDataObject::get_by_id($id)
$cache = is_null($id) ? true : !!$id; $cache = is_null($id) ? true : (bool)$id;
$id = $callerClass; $id = $callerClassOrID;
$callerClass = get_called_class(); $callerClass = get_called_class();
if (__CLASS__ === $callerClass) { if (__CLASS__ === $callerClassOrID) {
user_error("DataObject::get_by_id called without providing object class", E_USER_WARNING); user_error("DataObject::get_by_id called without providing object class", E_USER_WARNING);
} }
} else {
$callerClass = $callerClassOrID;
} }
if (!is_numeric($id)) { if (!is_numeric($id)) {

View File

@ -324,6 +324,20 @@ class DataObjectTest extends SapphireTest
$this->assertEquals('Phil', $comment->Name); $this->assertEquals('Phil', $comment->Name);
} }
public function testGetByIDCallerClass()
{
$captain1ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
$captain1 = DataObjectTest\Player::get_by_id($captain1ID);
$this->assertInstanceOf(DataObjectTest\Player::class, $captain1);
$this->assertEquals('Captain', $captain1->FirstName);
$captain2ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain2');
// make sure we can call from any class but get the one passed as an argument
$captain2 = DataObjectTest\TeamComment::get_by_id(DataObjectTest\Player::class, $captain2ID);
$this->assertInstanceOf(DataObjectTest\Player::class, $captain2);
$this->assertEquals('Captain 2', $captain2->FirstName);
}
public function testGetCaseInsensitive() public function testGetCaseInsensitive()
{ {
// Test get_one() with bad case on the classname // Test get_one() with bad case on the classname