10 changed files with 1360 additions and 0 deletions
-
57lib/private/appframework/db/db.php
-
8lib/private/appframework/dependencyinjection/dicontainer.php
-
42lib/public/appframework/db/doesnotexistexception.php
-
229lib/public/appframework/db/entity.php
-
51lib/public/appframework/db/idb.php
-
284lib/public/appframework/db/mapper.php
-
42lib/public/appframework/db/multipleobjectsreturnedexception.php
-
204tests/lib/appframework/db/EntityTest.php
-
264tests/lib/appframework/db/MapperTest.php
-
179tests/lib/appframework/db/MapperTestUtility.php
@ -0,0 +1,57 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
namespace OC\AppFramework\Db; |
|||
|
|||
use \OCP\AppFramework\Db\IDb; |
|||
|
|||
|
|||
/** |
|||
* Small Facade for being able to inject the database connection for tests |
|||
*/ |
|||
class Db implements IDb { |
|||
|
|||
|
|||
/** |
|||
* Used to abstract the owncloud database access away |
|||
* @param string $sql the sql query with ? placeholder for params |
|||
* @param int $limit the maximum number of rows |
|||
* @param int $offset from which row we want to start |
|||
* @return \OCP\DB a query object |
|||
*/ |
|||
public function prepareQuery($sql, $limit=null, $offset=null){ |
|||
return \OCP\DB::prepare($sql, $limit, $offset); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Used to get the id of the just inserted element |
|||
* @param string $tableName the name of the table where we inserted the item |
|||
* @return int the id of the inserted element |
|||
*/ |
|||
public function getInsertId($tableName){ |
|||
return \OCP\DB::insertid($tableName); |
|||
} |
|||
|
|||
|
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
/** |
|||
* This is returned or should be returned when a find request does not find an |
|||
* entry in the database |
|||
*/ |
|||
class DoesNotExistException extends \Exception { |
|||
|
|||
/** |
|||
* Constructor |
|||
* @param string $msg the error message |
|||
*/ |
|||
public function __construct($msg){ |
|||
parent::__construct($msg); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,229 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
abstract class Entity { |
|||
|
|||
public $id; |
|||
|
|||
private $_updatedFields = array(); |
|||
private $_fieldTypes = array('id' => 'integer'); |
|||
|
|||
|
|||
/** |
|||
* Simple alternative constructor for building entities from a request |
|||
* @param array $params the array which was obtained via $this->params('key') |
|||
* in the controller |
|||
* @return Entity |
|||
*/ |
|||
public static function fromParams(array $params) { |
|||
$instance = new static(); |
|||
|
|||
foreach($params as $key => $value) { |
|||
$method = 'set' . ucfirst($key); |
|||
$instance->$method($value); |
|||
} |
|||
|
|||
return $instance; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Maps the keys of the row array to the attributes |
|||
* @param array $row the row to map onto the entity |
|||
*/ |
|||
public static function fromRow(array $row){ |
|||
$instance = new static(); |
|||
|
|||
foreach($row as $key => $value){ |
|||
$prop = ucfirst($instance->columnToProperty($key)); |
|||
$setter = 'set' . $prop; |
|||
$instance->$setter($value); |
|||
} |
|||
|
|||
$instance->resetUpdatedFields(); |
|||
|
|||
return $instance; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* @return an array with attribute and type |
|||
*/ |
|||
public function getFieldTypes() { |
|||
return $this->_fieldTypes; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Marks the entity as clean needed for setting the id after the insertion |
|||
*/ |
|||
public function resetUpdatedFields(){ |
|||
$this->_updatedFields = array(); |
|||
} |
|||
|
|||
|
|||
protected function setter($name, $args) { |
|||
// setters should only work for existing attributes
|
|||
if(property_exists($this, $name)){ |
|||
$this->markFieldUpdated($name); |
|||
|
|||
// if type definition exists, cast to correct type
|
|||
if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) { |
|||
settype($args[0], $this->_fieldTypes[$name]); |
|||
} |
|||
$this->$name = $args[0]; |
|||
|
|||
} else { |
|||
throw new \BadFunctionCallException($name . |
|||
' is not a valid attribute'); |
|||
} |
|||
} |
|||
|
|||
|
|||
protected function getter($name) { |
|||
// getters should only work for existing attributes
|
|||
if(property_exists($this, $name)){ |
|||
return $this->$name; |
|||
} else { |
|||
throw new \BadFunctionCallException($name . |
|||
' is not a valid attribute'); |
|||
} |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Each time a setter is called, push the part after set |
|||
* into an array: for instance setId will save Id in the |
|||
* updated fields array so it can be easily used to create the |
|||
* getter method |
|||
*/ |
|||
public function __call($methodName, $args){ |
|||
$attr = lcfirst( substr($methodName, 3) ); |
|||
|
|||
if(strpos($methodName, 'set') === 0){ |
|||
$this->setter($attr, $args); |
|||
} elseif(strpos($methodName, 'get') === 0) { |
|||
return $this->getter($attr); |
|||
} else { |
|||
throw new \BadFunctionCallException($methodName . |
|||
' does not exist'); |
|||
} |
|||
|
|||
} |
|||
|
|||
|
|||
/** |
|||
* Mark am attribute as updated |
|||
* @param string $attribute the name of the attribute |
|||
*/ |
|||
protected function markFieldUpdated($attribute){ |
|||
$this->_updatedFields[$attribute] = true; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Transform a database columnname to a property |
|||
* @param string $columnName the name of the column |
|||
* @return string the property name |
|||
*/ |
|||
public function columnToProperty($columnName){ |
|||
$parts = explode('_', $columnName); |
|||
$property = null; |
|||
|
|||
foreach($parts as $part){ |
|||
if($property === null){ |
|||
$property = $part; |
|||
} else { |
|||
$property .= ucfirst($part); |
|||
} |
|||
} |
|||
|
|||
return $property; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Transform a property to a database column name |
|||
* @param string $property the name of the property |
|||
* @return string the column name |
|||
*/ |
|||
public function propertyToColumn($property){ |
|||
$parts = preg_split('/(?=[A-Z])/', $property); |
|||
$column = null; |
|||
|
|||
foreach($parts as $part){ |
|||
if($column === null){ |
|||
$column = $part; |
|||
} else { |
|||
$column .= '_' . lcfirst($part); |
|||
} |
|||
} |
|||
|
|||
return $column; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* @return array array of updated fields for update query |
|||
*/ |
|||
public function getUpdatedFields(){ |
|||
return $this->_updatedFields; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Adds type information for a field so that its automatically casted to |
|||
* that value once its being returned from the database |
|||
* @param string $fieldName the name of the attribute |
|||
* @param string $type the type which will be used to call settype() |
|||
*/ |
|||
protected function addType($fieldName, $type){ |
|||
$this->_fieldTypes[$fieldName] = $type; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Slugify the value of a given attribute |
|||
* Warning: This doesn't result in a unique value |
|||
* @param string $attributeName the name of the attribute, which value should be slugified |
|||
* @return string slugified value |
|||
*/ |
|||
public function slugify($attributeName){ |
|||
// toSlug should only work for existing attributes
|
|||
if(property_exists($this, $attributeName)){ |
|||
$value = $this->$attributeName; |
|||
// replace everything except alphanumeric with a single '-'
|
|||
$value = preg_replace('/[^A-Za-z0-9]+/', '-', $value); |
|||
$value = strtolower($value); |
|||
// trim '-'
|
|||
return trim($value, '-'); |
|||
} else { |
|||
throw new \BadFunctionCallException($attributeName . |
|||
' is not a valid attribute'); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,51 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
/** |
|||
* Small Facade for being able to inject the database connection for tests |
|||
*/ |
|||
interface IDb { |
|||
|
|||
|
|||
/** |
|||
* Used to abstract the owncloud database access away |
|||
* @param string $sql the sql query with ? placeholder for params |
|||
* @param int $limit the maximum number of rows |
|||
* @param int $offset from which row we want to start |
|||
* @return \OCP\DB a query object |
|||
*/ |
|||
public function prepareQuery($sql, $limit=null, $offset=null); |
|||
|
|||
|
|||
/** |
|||
* Used to get the id of the just inserted element |
|||
* @param string $tableName the name of the table where we inserted the item |
|||
* @return int the id of the inserted element |
|||
*/ |
|||
public function getInsertId($tableName); |
|||
|
|||
|
|||
} |
|||
@ -0,0 +1,284 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @author Morris Jobke |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* @copyright 2013 Morris Jobke morris.jobke@gmail.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
/** |
|||
* Simple parent class for inheriting your data access layer from. This class |
|||
* may be subject to change in the future |
|||
*/ |
|||
abstract class Mapper { |
|||
|
|||
protected $tableName; |
|||
protected $entityClass; |
|||
private $db; |
|||
|
|||
/** |
|||
* @param Db $db Instance of the Db abstraction layer |
|||
* @param string $tableName the name of the table. set this to allow entity |
|||
* @param string $entityClass the name of the entity that the sql should be |
|||
* mapped to queries without using sql |
|||
*/ |
|||
public function __construct(IDb $db, $tableName, $entityClass=null){ |
|||
$this->db = $db; |
|||
$this->tableName = '*PREFIX*' . $tableName; |
|||
|
|||
// if not given set the entity name to the class without the mapper part
|
|||
// cache it here for later use since reflection is slow
|
|||
if($entityClass === null) { |
|||
$this->entityClass = str_replace('Mapper', '', get_class($this)); |
|||
} else { |
|||
$this->entityClass = $entityClass; |
|||
} |
|||
} |
|||
|
|||
|
|||
/** |
|||
* @return string the table name |
|||
*/ |
|||
public function getTableName(){ |
|||
return $this->tableName; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Deletes an entity from the table |
|||
* @param Entity $entity the entity that should be deleted |
|||
*/ |
|||
public function delete(Entity $entity){ |
|||
$sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?'; |
|||
$this->execute($sql, array($entity->getId())); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Creates a new entry in the db from an entity |
|||
* @param Entity $enttiy the entity that should be created |
|||
* @return the saved entity with the set id |
|||
*/ |
|||
public function insert(Entity $entity){ |
|||
// get updated fields to save, fields have to be set using a setter to
|
|||
// be saved
|
|||
$properties = $entity->getUpdatedFields(); |
|||
$values = ''; |
|||
$columns = ''; |
|||
$params = array(); |
|||
|
|||
// build the fields
|
|||
$i = 0; |
|||
foreach($properties as $property => $updated) { |
|||
$column = $entity->propertyToColumn($property); |
|||
$getter = 'get' . ucfirst($property); |
|||
|
|||
$columns .= '`' . $column . '`'; |
|||
$values .= '?'; |
|||
|
|||
// only append colon if there are more entries
|
|||
if($i < count($properties)-1){ |
|||
$columns .= ','; |
|||
$values .= ','; |
|||
} |
|||
|
|||
array_push($params, $entity->$getter()); |
|||
$i++; |
|||
|
|||
} |
|||
|
|||
$sql = 'INSERT INTO `' . $this->tableName . '`(' . |
|||
$columns . ') VALUES(' . $values . ')'; |
|||
|
|||
$this->execute($sql, $params); |
|||
|
|||
$entity->setId((int) $this->db->getInsertId($this->tableName)); |
|||
return $entity; |
|||
} |
|||
|
|||
|
|||
|
|||
/** |
|||
* Updates an entry in the db from an entity |
|||
* @throws \InvalidArgumentException if entity has no id |
|||
* @param Entity $enttiy the entity that should be created |
|||
*/ |
|||
public function update(Entity $entity){ |
|||
// entity needs an id
|
|||
$id = $entity->getId(); |
|||
if($id === null){ |
|||
throw new \InvalidArgumentException( |
|||
'Entity which should be updated has no id'); |
|||
} |
|||
|
|||
// get updated fields to save, fields have to be set using a setter to
|
|||
// be saved
|
|||
$properties = $entity->getUpdatedFields(); |
|||
// dont update the id field
|
|||
unset($properties['id']); |
|||
|
|||
$columns = ''; |
|||
$params = array(); |
|||
|
|||
// build the fields
|
|||
$i = 0; |
|||
foreach($properties as $property => $updated) { |
|||
|
|||
$column = $entity->propertyToColumn($property); |
|||
$getter = 'get' . ucfirst($property); |
|||
|
|||
$columns .= '`' . $column . '` = ?'; |
|||
|
|||
// only append colon if there are more entries
|
|||
if($i < count($properties)-1){ |
|||
$columns .= ','; |
|||
} |
|||
|
|||
array_push($params, $entity->$getter()); |
|||
$i++; |
|||
} |
|||
|
|||
$sql = 'UPDATE `' . $this->tableName . '` SET ' . |
|||
$columns . ' WHERE `id` = ?'; |
|||
array_push($params, $id); |
|||
|
|||
$this->execute($sql, $params); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Runs an sql query |
|||
* @param string $sql the prepare string |
|||
* @param array $params the params which should replace the ? in the sql query |
|||
* @param int $limit the maximum number of rows |
|||
* @param int $offset from which row we want to start |
|||
* @return \PDOStatement the database query result |
|||
*/ |
|||
protected function execute($sql, array $params=array(), $limit=null, $offset=null){ |
|||
$query = $this->db->prepareQuery($sql, $limit, $offset); |
|||
|
|||
$index = 1; // bindParam is 1 indexed
|
|||
foreach($params as $param) { |
|||
|
|||
switch (gettype($param)) { |
|||
case 'integer': |
|||
$pdoConstant = \PDO::PARAM_INT; |
|||
break; |
|||
|
|||
case 'boolean': |
|||
$pdoConstant = \PDO::PARAM_BOOL; |
|||
break; |
|||
|
|||
default: |
|||
$pdoConstant = \PDO::PARAM_STR; |
|||
break; |
|||
} |
|||
|
|||
$query->bindValue($index, $param, $pdoConstant); |
|||
|
|||
$index++; |
|||
} |
|||
|
|||
return $query->execute(); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Returns an db result and throws exceptions when there are more or less |
|||
* results |
|||
* @see findEntity |
|||
* @param string $sql the sql query |
|||
* @param array $params the parameters of the sql query |
|||
* @param int $limit the maximum number of rows |
|||
* @param int $offset from which row we want to start |
|||
* @throws DoesNotExistException if the item does not exist |
|||
* @throws MultipleObjectsReturnedException if more than one item exist |
|||
* @return array the result as row |
|||
*/ |
|||
protected function findOneQuery($sql, array $params=array(), $limit=null, $offset=null){ |
|||
$result = $this->execute($sql, $params, $limit, $offset); |
|||
$row = $result->fetchRow(); |
|||
|
|||
if($row === false || $row === null){ |
|||
throw new DoesNotExistException('No matching entry found'); |
|||
} |
|||
$row2 = $result->fetchRow(); |
|||
//MDB2 returns null, PDO and doctrine false when no row is available
|
|||
if( ! ($row2 === false || $row2 === null )) { |
|||
throw new MultipleObjectsReturnedException('More than one result'); |
|||
} else { |
|||
return $row; |
|||
} |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Creates an entity from a row. Automatically determines the entity class |
|||
* from the current mapper name (MyEntityMapper -> MyEntity) |
|||
* @param array $row the row which should be converted to an entity |
|||
* @return Entity the entity |
|||
*/ |
|||
protected function mapRowToEntity($row) { |
|||
return call_user_func($this->entityClass .'::fromRow', $row); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Runs a sql query and returns an array of entities |
|||
* @param string $sql the prepare string |
|||
* @param array $params the params which should replace the ? in the sql query |
|||
* @param int $limit the maximum number of rows |
|||
* @param int $offset from which row we want to start |
|||
* @return array all fetched entities |
|||
*/ |
|||
protected function findEntities($sql, array $params=array(), $limit=null, $offset=null) { |
|||
$result = $this->execute($sql, $params, $limit, $offset); |
|||
|
|||
$entities = array(); |
|||
|
|||
while($row = $result->fetchRow()){ |
|||
$entities[] = $this->mapRowToEntity($row); |
|||
} |
|||
|
|||
return $entities; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Returns an db result and throws exceptions when there are more or less |
|||
* results |
|||
* @param string $sql the sql query |
|||
* @param array $params the parameters of the sql query |
|||
* @param int $limit the maximum number of rows |
|||
* @param int $offset from which row we want to start |
|||
* @throws DoesNotExistException if the item does not exist |
|||
* @throws MultipleObjectsReturnedException if more than one item exist |
|||
* @return Entity the entity |
|||
*/ |
|||
protected function findEntity($sql, array $params=array(), $limit=null, $offset=null){ |
|||
return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset)); |
|||
} |
|||
|
|||
|
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
/** |
|||
* This is returned or should be returned when a find request finds more than one |
|||
* row |
|||
*/ |
|||
class MultipleObjectsReturnedException extends \Exception { |
|||
|
|||
/** |
|||
* Constructor |
|||
* @param string $msg the error message |
|||
*/ |
|||
public function __construct($msg){ |
|||
parent::__construct($msg); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,204 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
|
|||
class TestEntity extends Entity { |
|||
public $name; |
|||
public $email; |
|||
public $testId; |
|||
public $preName; |
|||
|
|||
public function __construct(){ |
|||
$this->addType('testId', 'integer'); |
|||
} |
|||
}; |
|||
|
|||
|
|||
class EntityTest extends \PHPUnit_Framework_TestCase { |
|||
|
|||
private $entity; |
|||
|
|||
protected function setUp(){ |
|||
$this->entity = new TestEntity(); |
|||
} |
|||
|
|||
|
|||
public function testResetUpdatedFields(){ |
|||
$entity = new TestEntity(); |
|||
$entity->setId(3); |
|||
$entity->resetUpdatedFields(); |
|||
|
|||
$this->assertEquals(array(), $entity->getUpdatedFields()); |
|||
} |
|||
|
|||
|
|||
public function testFromRow(){ |
|||
$row = array( |
|||
'pre_name' => 'john', |
|||
'email' => 'john@something.com' |
|||
); |
|||
$this->entity = TestEntity::fromRow($row); |
|||
|
|||
$this->assertEquals($row['pre_name'], $this->entity->getPreName()); |
|||
$this->assertEquals($row['email'], $this->entity->getEmail()); |
|||
} |
|||
|
|||
|
|||
public function testGetSetId(){ |
|||
$id = 3; |
|||
$this->entity->setId(3); |
|||
|
|||
$this->assertEquals($id, $this->entity->getId()); |
|||
} |
|||
|
|||
|
|||
public function testColumnToPropertyNoReplacement(){ |
|||
$column = 'my'; |
|||
$this->assertEquals('my', |
|||
$this->entity->columnToProperty($column)); |
|||
} |
|||
|
|||
|
|||
public function testColumnToProperty(){ |
|||
$column = 'my_attribute'; |
|||
$this->assertEquals('myAttribute', |
|||
$this->entity->columnToProperty($column)); |
|||
} |
|||
|
|||
|
|||
public function testPropertyToColumnNoReplacement(){ |
|||
$property = 'my'; |
|||
$this->assertEquals('my', |
|||
$this->entity->propertyToColumn($property)); |
|||
} |
|||
|
|||
|
|||
public function testSetterMarksFieldUpdated(){ |
|||
$id = 3; |
|||
$this->entity->setId(3); |
|||
|
|||
$this->assertContains('id', $this->entity->getUpdatedFields()); |
|||
} |
|||
|
|||
|
|||
public function testCallShouldOnlyWorkForGetterSetter(){ |
|||
$this->setExpectedException('\BadFunctionCallException'); |
|||
|
|||
$this->entity->something(); |
|||
} |
|||
|
|||
|
|||
public function testGetterShouldFailIfAttributeNotDefined(){ |
|||
$this->setExpectedException('\BadFunctionCallException'); |
|||
|
|||
$this->entity->getTest(); |
|||
} |
|||
|
|||
|
|||
public function testSetterShouldFailIfAttributeNotDefined(){ |
|||
$this->setExpectedException('\BadFunctionCallException'); |
|||
|
|||
$this->entity->setTest(); |
|||
} |
|||
|
|||
|
|||
public function testFromRowShouldNotAssignEmptyArray(){ |
|||
$row = array(); |
|||
$entity2 = new TestEntity(); |
|||
|
|||
$this->entity = TestEntity::fromRow($row); |
|||
$this->assertEquals($entity2, $this->entity); |
|||
} |
|||
|
|||
|
|||
public function testIdGetsConvertedToInt(){ |
|||
$row = array('id' => '4'); |
|||
|
|||
$this->entity = TestEntity::fromRow($row); |
|||
$this->assertSame(4, $this->entity->getId()); |
|||
} |
|||
|
|||
|
|||
public function testSetType(){ |
|||
$row = array('testId' => '4'); |
|||
|
|||
$this->entity = TestEntity::fromRow($row); |
|||
$this->assertSame(4, $this->entity->getTestId()); |
|||
} |
|||
|
|||
|
|||
public function testFromParams(){ |
|||
$params = array( |
|||
'testId' => 4, |
|||
'email' => 'john@doe' |
|||
); |
|||
|
|||
$entity = TestEntity::fromParams($params); |
|||
|
|||
$this->assertEquals($params['testId'], $entity->getTestId()); |
|||
$this->assertEquals($params['email'], $entity->getEmail()); |
|||
$this->assertTrue($entity instanceof TestEntity); |
|||
} |
|||
|
|||
public function testSlugify(){ |
|||
$entity = new TestEntity(); |
|||
$entity->setName('Slugify this!'); |
|||
$this->assertEquals('slugify-this', $entity->slugify('name')); |
|||
$entity->setName('°!"§$%&/()=?`´ß\}][{³²#\'+~*-_.:,;<>|äöüÄÖÜSlugify this!'); |
|||
$this->assertEquals('slugify-this', $entity->slugify('name')); |
|||
} |
|||
|
|||
|
|||
public function testSetterCasts() { |
|||
$entity = new TestEntity(); |
|||
$entity->setId('3'); |
|||
$this->assertSame(3, $entity->getId()); |
|||
} |
|||
|
|||
|
|||
public function testSetterDoesNotCastOnNull() { |
|||
$entity = new TestEntity(); |
|||
$entity->setId(null); |
|||
$this->assertSame(null, $entity->getId()); |
|||
} |
|||
|
|||
|
|||
public function testGetFieldTypes() { |
|||
$entity = new TestEntity(); |
|||
$this->assertEquals(array( |
|||
'id' => 'integer', |
|||
'testId' => 'integer' |
|||
), $entity->getFieldTypes()); |
|||
} |
|||
|
|||
|
|||
public function testGetItInt() { |
|||
$entity = new TestEntity(); |
|||
$entity->setId(3); |
|||
$this->assertEquals('integer', gettype($entity->getId())); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,264 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
require_once __DIR__ . '/MapperTestUtility.php'; |
|||
|
|||
|
|||
class Example extends Entity { |
|||
public $preName; |
|||
public $email; |
|||
}; |
|||
|
|||
|
|||
class ExampleMapper extends Mapper { |
|||
public function __construct(IDb $db){ parent::__construct($db, 'table'); } |
|||
public function find($table, $id){ return $this->findOneQuery($table, $id); } |
|||
public function findOneEntity($table, $id){ return $this->findEntity($table, $id); } |
|||
public function findAll($table){ return $this->findAllQuery($table); } |
|||
public function findAllEntities($table){ return $this->findEntities($table); } |
|||
public function mapRow($row){ return $this->mapRowToEntity($row); } |
|||
public function pDeleteQuery($table, $id){ $this->deleteQuery($table, $id); } |
|||
} |
|||
|
|||
|
|||
class MapperTest extends MapperTestUtility { |
|||
|
|||
private $mapper; |
|||
|
|||
public function setUp(){ |
|||
parent::setUp(); |
|||
$this->mapper = new ExampleMapper($this->db); |
|||
} |
|||
|
|||
|
|||
public function testMapperShouldSetTableName(){ |
|||
$this->assertEquals('*PREFIX*table', $this->mapper->getTableName()); |
|||
} |
|||
|
|||
|
|||
public function testFindQuery(){ |
|||
$sql = 'hi'; |
|||
$params = array('jo'); |
|||
$rows = array( |
|||
array('hi') |
|||
); |
|||
$row = $this->setMapperResult($sql, $params, $rows); |
|||
$this->mapper->find($sql, $params); |
|||
} |
|||
|
|||
public function testFindEntity(){ |
|||
$sql = 'hi'; |
|||
$params = array('jo'); |
|||
$rows = array( |
|||
array('pre_name' => 'hi') |
|||
); |
|||
$row = $this->setMapperResult($sql, $params, $rows); |
|||
$this->mapper->findOneEntity($sql, $params); |
|||
} |
|||
|
|||
public function testFindNotFound(){ |
|||
$sql = 'hi'; |
|||
$params = array('jo'); |
|||
$rows = array(); |
|||
$row = $this->setMapperResult($sql, $params, $rows); |
|||
$this->setExpectedException( |
|||
'\OCP\AppFramework\Db\DoesNotExistException'); |
|||
$this->mapper->find($sql, $params); |
|||
} |
|||
|
|||
public function testFindEntityNotFound(){ |
|||
$sql = 'hi'; |
|||
$params = array('jo'); |
|||
$rows = array(); |
|||
$row = $this->setMapperResult($sql, $params, $rows); |
|||
$this->setExpectedException( |
|||
'\OCP\AppFramework\Db\DoesNotExistException'); |
|||
$this->mapper->findOneEntity($sql, $params); |
|||
} |
|||
|
|||
public function testFindMultiple(){ |
|||
$sql = 'hi'; |
|||
$params = array('jo'); |
|||
$rows = array( |
|||
array('jo'), array('ho') |
|||
); |
|||
$row = $this->setMapperResult($sql, $params, $rows); |
|||
$this->setExpectedException( |
|||
'\OCP\AppFramework\Db\MultipleObjectsReturnedException'); |
|||
$this->mapper->find($sql, $params); |
|||
} |
|||
|
|||
public function testFindEntityMultiple(){ |
|||
$sql = 'hi'; |
|||
$params = array('jo'); |
|||
$rows = array( |
|||
array('jo'), array('ho') |
|||
); |
|||
$row = $this->setMapperResult($sql, $params, $rows); |
|||
$this->setExpectedException( |
|||
'\OCP\AppFramework\Db\MultipleObjectsReturnedException'); |
|||
$this->mapper->findOneEntity($sql, $params); |
|||
} |
|||
|
|||
|
|||
public function testDelete(){ |
|||
$sql = 'DELETE FROM `*PREFIX*table` WHERE `id` = ?'; |
|||
$params = array(2); |
|||
|
|||
$this->setMapperResult($sql, $params); |
|||
$entity = new Example(); |
|||
$entity->setId($params[0]); |
|||
|
|||
$this->mapper->delete($entity); |
|||
} |
|||
|
|||
|
|||
public function testCreate(){ |
|||
$this->db->expects($this->once()) |
|||
->method('getInsertId') |
|||
->with($this->equalTo('*PREFIX*table')) |
|||
->will($this->returnValue(3)); |
|||
$this->mapper = new ExampleMapper($this->db); |
|||
|
|||
$sql = 'INSERT INTO `*PREFIX*table`(`pre_name`,`email`) ' . |
|||
'VALUES(?,?)'; |
|||
$params = array('john', 'my@email'); |
|||
$entity = new Example(); |
|||
$entity->setPreName($params[0]); |
|||
$entity->setEmail($params[1]); |
|||
|
|||
$this->setMapperResult($sql, $params); |
|||
|
|||
$this->mapper->insert($entity); |
|||
} |
|||
|
|||
|
|||
public function testCreateShouldReturnItemWithCorrectInsertId(){ |
|||
$this->db->expects($this->once()) |
|||
->method('getInsertId') |
|||
->with($this->equalTo('*PREFIX*table')) |
|||
->will($this->returnValue(3)); |
|||
$this->mapper = new ExampleMapper($this->db); |
|||
|
|||
$sql = 'INSERT INTO `*PREFIX*table`(`pre_name`,`email`) ' . |
|||
'VALUES(?,?)'; |
|||
$params = array('john', 'my@email'); |
|||
$entity = new Example(); |
|||
$entity->setPreName($params[0]); |
|||
$entity->setEmail($params[1]); |
|||
|
|||
$this->setMapperResult($sql, $params); |
|||
|
|||
$result = $this->mapper->insert($entity); |
|||
|
|||
$this->assertEquals(3, $result->getId()); |
|||
} |
|||
|
|||
|
|||
public function testUpdate(){ |
|||
$sql = 'UPDATE `*PREFIX*table` ' . |
|||
'SET ' . |
|||
'`pre_name` = ?,'. |
|||
'`email` = ? ' . |
|||
'WHERE `id` = ?'; |
|||
|
|||
$params = array('john', 'my@email', 1); |
|||
$entity = new Example(); |
|||
$entity->setPreName($params[0]); |
|||
$entity->setEmail($params[1]); |
|||
$entity->setId($params[2]); |
|||
|
|||
$this->setMapperResult($sql, $params); |
|||
|
|||
$this->mapper->update($entity); |
|||
} |
|||
|
|||
|
|||
public function testUpdateNoId(){ |
|||
$sql = 'UPDATE `*PREFIX*table` ' . |
|||
'SET ' . |
|||
'`pre_name` = ?,'. |
|||
'`email` = ? ' . |
|||
'WHERE `id` = ?'; |
|||
|
|||
$params = array('john', 'my@email'); |
|||
$entity = new Example(); |
|||
$entity->setPreName($params[0]); |
|||
$entity->setEmail($params[1]); |
|||
|
|||
$this->setExpectedException('InvalidArgumentException'); |
|||
|
|||
$this->mapper->update($entity); |
|||
} |
|||
|
|||
|
|||
public function testMapRowToEntity(){ |
|||
$entity1 = $this->mapper->mapRow(array('pre_name' => 'test1', 'email' => 'test2')); |
|||
$entity2 = new Example(); |
|||
$entity2->setPreName('test1'); |
|||
$entity2->setEmail('test2'); |
|||
$entity2->resetUpdatedFields(); |
|||
$this->assertEquals($entity2, $entity1); |
|||
} |
|||
|
|||
public function testFindEntities(){ |
|||
$sql = 'hi'; |
|||
$rows = array( |
|||
array('pre_name' => 'hi') |
|||
); |
|||
$entity = new Example(); |
|||
$entity->setPreName('hi'); |
|||
$entity->resetUpdatedFields(); |
|||
$row = $this->setMapperResult($sql, array(), $rows); |
|||
$result = $this->mapper->findAllEntities($sql); |
|||
$this->assertEquals(array($entity), $result); |
|||
} |
|||
|
|||
public function testFindEntitiesNotFound(){ |
|||
$sql = 'hi'; |
|||
$rows = array(); |
|||
$row = $this->setMapperResult($sql, array(), $rows); |
|||
$result = $this->mapper->findAllEntities($sql); |
|||
$this->assertEquals(array(), $result); |
|||
} |
|||
|
|||
public function testFindEntitiesMultiple(){ |
|||
$sql = 'hi'; |
|||
$rows = array( |
|||
array('pre_name' => 'jo'), array('email' => 'ho') |
|||
); |
|||
$entity1 = new Example(); |
|||
$entity1->setPreName('jo'); |
|||
$entity1->resetUpdatedFields(); |
|||
$entity2 = new Example(); |
|||
$entity2->setEmail('ho'); |
|||
$entity2->resetUpdatedFields(); |
|||
$row = $this->setMapperResult($sql, array(), $rows); |
|||
$result = $this->mapper->findAllEntities($sql); |
|||
$this->assertEquals(array($entity1, $entity2), $result); |
|||
} |
|||
} |
|||
@ -0,0 +1,179 @@ |
|||
<?php |
|||
|
|||
/** |
|||
* ownCloud - App Framework |
|||
* |
|||
* @author Bernhard Posselt |
|||
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com |
|||
* |
|||
* This library is free software; you can redistribute it and/or |
|||
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE |
|||
* License as published by the Free Software Foundation; either |
|||
* version 3 of the License, or any later version. |
|||
* |
|||
* This library is distributed in the hope that it will be useful, |
|||
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|||
* GNU AFFERO GENERAL PUBLIC LICENSE for more details. |
|||
* |
|||
* You should have received a copy of the GNU Affero General Public |
|||
* License along with this library. If not, see <http://www.gnu.org/licenses/>. |
|||
* |
|||
*/ |
|||
|
|||
|
|||
namespace OCP\AppFramework\Db; |
|||
|
|||
|
|||
/** |
|||
* Simple utility class for testing mappers |
|||
*/ |
|||
abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase { |
|||
|
|||
|
|||
protected $db; |
|||
private $query; |
|||
private $pdoResult; |
|||
private $queryAt; |
|||
private $prepareAt; |
|||
private $fetchAt; |
|||
private $iterators; |
|||
|
|||
|
|||
/** |
|||
* Run this function before the actual test to either set or initialize the |
|||
* db. After this the db can be accessed by using $this->db |
|||
*/ |
|||
protected function setUp(){ |
|||
$this->db = $this->getMockBuilder( |
|||
'\OCP\AppFramework\Db\IDb') |
|||
->disableOriginalConstructor() |
|||
->getMock(); |
|||
|
|||
$this->query = $this->getMock('Query', array('execute', 'bindValue')); |
|||
$this->pdoResult = $this->getMock('Result', array('fetchRow')); |
|||
$this->queryAt = 0; |
|||
$this->prepareAt = 0; |
|||
$this->iterators = array(); |
|||
$this->fetchAt = 0; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* Create mocks and set expected results for database queries |
|||
* @param string $sql the sql query that you expect to receive |
|||
* @param array $arguments the expected arguments for the prepare query |
|||
* method |
|||
* @param array $returnRows the rows that should be returned for the result |
|||
* of the database query. If not provided, it wont be assumed that fetchRow |
|||
* will be called on the result |
|||
*/ |
|||
protected function setMapperResult($sql, $arguments=array(), $returnRows=array(), |
|||
$limit=null, $offset=null){ |
|||
|
|||
$this->iterators[] = new ArgumentIterator($returnRows); |
|||
|
|||
$iterators = $this->iterators; |
|||
$fetchAt = $this->fetchAt; |
|||
|
|||
$this->pdoResult->expects($this->any()) |
|||
->method('fetchRow') |
|||
->will($this->returnCallback( |
|||
function() use ($iterators, $fetchAt){ |
|||
$iterator = $iterators[$fetchAt]; |
|||
$result = $iterator->next(); |
|||
|
|||
if($result === false) { |
|||
$fetchAt++; |
|||
} |
|||
|
|||
return $result; |
|||
} |
|||
)); |
|||
|
|||
$index = 1; |
|||
foreach($arguments as $argument) { |
|||
switch (gettype($argument)) { |
|||
case 'integer': |
|||
$pdoConstant = \PDO::PARAM_INT; |
|||
break; |
|||
|
|||
case 'NULL': |
|||
$pdoConstant = \PDO::PARAM_NULL; |
|||
break; |
|||
|
|||
case 'boolean': |
|||
$pdoConstant = \PDO::PARAM_BOOL; |
|||
break; |
|||
|
|||
default: |
|||
$pdoConstant = \PDO::PARAM_STR; |
|||
break; |
|||
} |
|||
$this->query->expects($this->at($this->queryAt)) |
|||
->method('bindValue') |
|||
->with($this->equalTo($index), |
|||
$this->equalTo($argument), |
|||
$this->equalTo($pdoConstant)); |
|||
$index++; |
|||
$this->queryAt++; |
|||
} |
|||
|
|||
$this->query->expects($this->at($this->queryAt)) |
|||
->method('execute') |
|||
->with() |
|||
->will($this->returnValue($this->pdoResult)); |
|||
$this->queryAt++; |
|||
|
|||
if($limit === null && $offset === null) { |
|||
$this->db->expects($this->at($this->prepareAt)) |
|||
->method('prepareQuery') |
|||
->with($this->equalTo($sql)) |
|||
->will(($this->returnValue($this->query))); |
|||
} elseif($limit !== null && $offset === null) { |
|||
$this->db->expects($this->at($this->prepareAt)) |
|||
->method('prepareQuery') |
|||
->with($this->equalTo($sql), $this->equalTo($limit)) |
|||
->will(($this->returnValue($this->query))); |
|||
} elseif($limit === null && $offset !== null) { |
|||
$this->db->expects($this->at($this->prepareAt)) |
|||
->method('prepareQuery') |
|||
->with($this->equalTo($sql), |
|||
$this->equalTo(null), |
|||
$this->equalTo($offset)) |
|||
->will(($this->returnValue($this->query))); |
|||
} else { |
|||
$this->db->expects($this->at($this->prepareAt)) |
|||
->method('prepareQuery') |
|||
->with($this->equalTo($sql), |
|||
$this->equalTo($limit), |
|||
$this->equalTo($offset)) |
|||
->will(($this->returnValue($this->query))); |
|||
} |
|||
$this->prepareAt++; |
|||
$this->fetchAt++; |
|||
|
|||
} |
|||
|
|||
|
|||
} |
|||
|
|||
|
|||
class ArgumentIterator { |
|||
|
|||
private $arguments; |
|||
|
|||
public function __construct($arguments){ |
|||
$this->arguments = $arguments; |
|||
} |
|||
|
|||
public function next(){ |
|||
$result = array_shift($this->arguments); |
|||
if($result === null){ |
|||
return false; |
|||
} else { |
|||
return $result; |
|||
} |
|||
} |
|||
} |
|||
|
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue