Mapper.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OCP\AppFramework\Db;
  27. use OCP\IDBConnection;
  28. /**
  29. * Simple parent class for inheriting your data access layer from. This class
  30. * may be subject to change in the future
  31. * @since 7.0.0
  32. */
  33. abstract class Mapper {
  34. protected $tableName;
  35. protected $entityClass;
  36. protected $db;
  37. /**
  38. * @param IDBConnection $db Instance of the Db abstraction layer
  39. * @param string $tableName the name of the table. set this to allow entity
  40. * @param string $entityClass the name of the entity that the sql should be
  41. * mapped to queries without using sql
  42. * @since 7.0.0
  43. */
  44. public function __construct(IDBConnection $db, $tableName, $entityClass=null){
  45. $this->db = $db;
  46. $this->tableName = '*PREFIX*' . $tableName;
  47. // if not given set the entity name to the class without the mapper part
  48. // cache it here for later use since reflection is slow
  49. if($entityClass === null) {
  50. $this->entityClass = str_replace('Mapper', '', get_class($this));
  51. } else {
  52. $this->entityClass = $entityClass;
  53. }
  54. }
  55. /**
  56. * @return string the table name
  57. * @since 7.0.0
  58. */
  59. public function getTableName(){
  60. return $this->tableName;
  61. }
  62. /**
  63. * Deletes an entity from the table
  64. * @param Entity $entity the entity that should be deleted
  65. * @return Entity the deleted entity
  66. * @since 7.0.0 - return value added in 8.1.0
  67. */
  68. public function delete(Entity $entity){
  69. $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
  70. $stmt = $this->execute($sql, [$entity->getId()]);
  71. $stmt->closeCursor();
  72. return $entity;
  73. }
  74. /**
  75. * Creates a new entry in the db from an entity
  76. * @param Entity $entity the entity that should be created
  77. * @return Entity the saved entity with the set id
  78. * @since 7.0.0
  79. */
  80. public function insert(Entity $entity){
  81. // get updated fields to save, fields have to be set using a setter to
  82. // be saved
  83. $properties = $entity->getUpdatedFields();
  84. $values = '';
  85. $columns = '';
  86. $params = [];
  87. // build the fields
  88. $i = 0;
  89. foreach($properties as $property => $updated) {
  90. $column = $entity->propertyToColumn($property);
  91. $getter = 'get' . ucfirst($property);
  92. $columns .= '`' . $column . '`';
  93. $values .= '?';
  94. // only append colon if there are more entries
  95. if($i < count($properties)-1){
  96. $columns .= ',';
  97. $values .= ',';
  98. }
  99. $params[] = $entity->$getter();
  100. $i++;
  101. }
  102. $sql = 'INSERT INTO `' . $this->tableName . '`(' .
  103. $columns . ') VALUES(' . $values . ')';
  104. $stmt = $this->execute($sql, $params);
  105. $entity->setId((int) $this->db->lastInsertId($this->tableName));
  106. $stmt->closeCursor();
  107. return $entity;
  108. }
  109. /**
  110. * Updates an entry in the db from an entity
  111. * @throws \InvalidArgumentException if entity has no id
  112. * @param Entity $entity the entity that should be created
  113. * @return Entity the saved entity with the set id
  114. * @since 7.0.0 - return value was added in 8.0.0
  115. */
  116. public function update(Entity $entity){
  117. // if entity wasn't changed it makes no sense to run a db query
  118. $properties = $entity->getUpdatedFields();
  119. if(count($properties) === 0) {
  120. return $entity;
  121. }
  122. // entity needs an id
  123. $id = $entity->getId();
  124. if($id === null){
  125. throw new \InvalidArgumentException(
  126. 'Entity which should be updated has no id');
  127. }
  128. // get updated fields to save, fields have to be set using a setter to
  129. // be saved
  130. // do not update the id field
  131. unset($properties['id']);
  132. $columns = '';
  133. $params = [];
  134. // build the fields
  135. $i = 0;
  136. foreach($properties as $property => $updated) {
  137. $column = $entity->propertyToColumn($property);
  138. $getter = 'get' . ucfirst($property);
  139. $columns .= '`' . $column . '` = ?';
  140. // only append colon if there are more entries
  141. if($i < count($properties)-1){
  142. $columns .= ',';
  143. }
  144. $params[] = $entity->$getter();
  145. $i++;
  146. }
  147. $sql = 'UPDATE `' . $this->tableName . '` SET ' .
  148. $columns . ' WHERE `id` = ?';
  149. $params[] = $id;
  150. $stmt = $this->execute($sql, $params);
  151. $stmt->closeCursor();
  152. return $entity;
  153. }
  154. /**
  155. * Checks if an array is associative
  156. * @param array $array
  157. * @return bool true if associative
  158. * @since 8.1.0
  159. */
  160. private function isAssocArray(array $array) {
  161. return array_values($array) !== $array;
  162. }
  163. /**
  164. * Returns the correct PDO constant based on the value type
  165. * @param $value
  166. * @return int PDO constant
  167. * @since 8.1.0
  168. */
  169. private function getPDOType($value) {
  170. switch (gettype($value)) {
  171. case 'integer':
  172. return \PDO::PARAM_INT;
  173. case 'boolean':
  174. return \PDO::PARAM_BOOL;
  175. default:
  176. return \PDO::PARAM_STR;
  177. }
  178. }
  179. /**
  180. * Runs an sql query
  181. * @param string $sql the prepare string
  182. * @param array $params the params which should replace the ? in the sql query
  183. * @param int $limit the maximum number of rows
  184. * @param int $offset from which row we want to start
  185. * @return \PDOStatement the database query result
  186. * @since 7.0.0
  187. */
  188. protected function execute($sql, array $params=[], $limit=null, $offset=null){
  189. $query = $this->db->prepare($sql, $limit, $offset);
  190. if ($this->isAssocArray($params)) {
  191. foreach ($params as $key => $param) {
  192. $pdoConstant = $this->getPDOType($param);
  193. $query->bindValue($key, $param, $pdoConstant);
  194. }
  195. } else {
  196. $index = 1; // bindParam is 1 indexed
  197. foreach ($params as $param) {
  198. $pdoConstant = $this->getPDOType($param);
  199. $query->bindValue($index, $param, $pdoConstant);
  200. $index++;
  201. }
  202. }
  203. $result = $query->execute();
  204. return $query;
  205. }
  206. /**
  207. * Returns an db result and throws exceptions when there are more or less
  208. * results
  209. * @see findEntity
  210. * @param string $sql the sql query
  211. * @param array $params the parameters of the sql query
  212. * @param int $limit the maximum number of rows
  213. * @param int $offset from which row we want to start
  214. * @throws DoesNotExistException if the item does not exist
  215. * @throws MultipleObjectsReturnedException if more than one item exist
  216. * @return array the result as row
  217. * @since 7.0.0
  218. */
  219. protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
  220. $stmt = $this->execute($sql, $params, $limit, $offset);
  221. $row = $stmt->fetch();
  222. if($row === false || $row === null){
  223. $stmt->closeCursor();
  224. $msg = $this->buildDebugMessage(
  225. 'Did expect one result but found none when executing', $sql, $params, $limit, $offset
  226. );
  227. throw new DoesNotExistException($msg);
  228. }
  229. $row2 = $stmt->fetch();
  230. $stmt->closeCursor();
  231. //MDB2 returns null, PDO and doctrine false when no row is available
  232. if( ! ($row2 === false || $row2 === null )) {
  233. $msg = $this->buildDebugMessage(
  234. 'Did not expect more than one result when executing', $sql, $params, $limit, $offset
  235. );
  236. throw new MultipleObjectsReturnedException($msg);
  237. } else {
  238. return $row;
  239. }
  240. }
  241. /**
  242. * Builds an error message by prepending the $msg to an error message which
  243. * has the parameters
  244. * @see findEntity
  245. * @param string $sql the sql query
  246. * @param array $params the parameters of the sql query
  247. * @param int $limit the maximum number of rows
  248. * @param int $offset from which row we want to start
  249. * @return string formatted error message string
  250. * @since 9.1.0
  251. */
  252. private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
  253. return $msg .
  254. ': query "' . $sql . '"; ' .
  255. 'parameters ' . print_r($params, true) . '; ' .
  256. 'limit "' . $limit . '"; '.
  257. 'offset "' . $offset . '"';
  258. }
  259. /**
  260. * Creates an entity from a row. Automatically determines the entity class
  261. * from the current mapper name (MyEntityMapper -> MyEntity)
  262. * @param array $row the row which should be converted to an entity
  263. * @return Entity the entity
  264. * @since 7.0.0
  265. */
  266. protected function mapRowToEntity($row) {
  267. return call_user_func($this->entityClass .'::fromRow', $row);
  268. }
  269. /**
  270. * Runs a sql query and returns an array of entities
  271. * @param string $sql the prepare string
  272. * @param array $params the params which should replace the ? in the sql query
  273. * @param int $limit the maximum number of rows
  274. * @param int $offset from which row we want to start
  275. * @return array all fetched entities
  276. * @since 7.0.0
  277. */
  278. protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
  279. $stmt = $this->execute($sql, $params, $limit, $offset);
  280. $entities = [];
  281. while($row = $stmt->fetch()){
  282. $entities[] = $this->mapRowToEntity($row);
  283. }
  284. $stmt->closeCursor();
  285. return $entities;
  286. }
  287. /**
  288. * Returns an db result and throws exceptions when there are more or less
  289. * results
  290. * @param string $sql the sql query
  291. * @param array $params the parameters of the sql query
  292. * @param int $limit the maximum number of rows
  293. * @param int $offset from which row we want to start
  294. * @throws DoesNotExistException if the item does not exist
  295. * @throws MultipleObjectsReturnedException if more than one item exist
  296. * @return Entity the entity
  297. * @since 7.0.0
  298. */
  299. protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
  300. return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
  301. }
  302. }