Merge pull request #8659 from owncloud/get-preference-multiple-user

Add a method to get the values for multiple users to OC\Preferences
This commit is contained in:
Vincent Petry 2014-05-22 09:59:20 +02:00
commit 25ecd2bdda
2 changed files with 74 additions and 0 deletions

View File

@ -205,6 +205,43 @@ class Preferences {
}
}
/**
* Gets the preference for an array of users
* @param string $app
* @param string $key
* @param array $users
* @return array Mapped values: userid => value
*/
public function getValueForUsers($app, $key, $users) {
if (empty($users) || !is_array($users)) {
return array();
}
$chunked_users = array_chunk($users, 50, true);
$placeholders_50 = implode(',', array_fill(0, 50, '?'));
$userValues = array();
foreach ($chunked_users as $chunk) {
$queryParams = $chunk;
array_unshift($queryParams, $key);
array_unshift($queryParams, $app);
$placeholders = (sizeof($chunk) == 50) ? $placeholders_50 : implode(',', array_fill(0, sizeof($chunk), '?'));
$query = 'SELECT `userid`, `configvalue` '
. ' FROM `*PREFIX*preferences` '
. ' WHERE `appid` = ? AND `configkey` = ?'
. ' AND `userid` IN (' . $placeholders . ')';
$result = $this->conn->executeQuery($query, $queryParams);
while ($row = $result->fetch()) {
$userValues[$row['userid']] = $row['configvalue'];
}
}
return $userValues;
}
/**
* Deletes a key
* @param string $user user

View File

@ -184,6 +184,43 @@ class Test_Preferences_Object extends PHPUnit_Framework_TestCase {
$preferences->setValue('grg', 'bar', 'foo', 'v2');
}
public function testGetUserValues()
{
$query = \OC_DB::prepare('INSERT INTO `*PREFIX*preferences` VALUES(?, ?, ?, ?)');
$query->execute(array('SomeUser', 'testGetUserValues', 'somekey', 'somevalue'));
$query->execute(array('AnotherUser', 'testGetUserValues', 'somekey', 'someothervalue'));
$query->execute(array('AUser', 'testGetUserValues', 'somekey', 'somevalue'));
$preferences = new OC\Preferences(\OC_DB::getConnection());
$users = array('SomeUser', 'AnotherUser', 'NoValueSet');
$values = $preferences->getValueForUsers('testGetUserValues', 'somekey', $users);
$this->assertUserValues($values);
// Add a lot of users so the array is chunked
for ($i = 1; $i <= 75; $i++) {
array_unshift($users, 'NoValueBefore#' . $i);
array_push($users, 'NoValueAfter#' . $i);
}
$values = $preferences->getValueForUsers('testGetUserValues', 'somekey', $users);
$this->assertUserValues($values);
// Clean DB after the test
$query = \OC_DB::prepare('DELETE FROM `*PREFIX*preferences` WHERE `appid` = ?');
$query->execute(array('testGetUserValues'));
}
protected function assertUserValues($values) {
$this->assertEquals(2, sizeof($values));
$this->assertArrayHasKey('SomeUser', $values);
$this->assertEquals('somevalue', $values['SomeUser']);
$this->assertArrayHasKey('AnotherUser', $values);
$this->assertEquals('someothervalue', $values['AnotherUser']);
}
public function testDeleteKey()
{
$connectionMock = $this->getMock('\OC\DB\Connection', array(), array(), '', false);