Completed
Pull Request — master (#4617)
by Julius
14:00
created
lib/public/AppFramework/Controller.php 1 patch
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -45,219 +45,219 @@
 block discarded – undo
45 45
  */
46 46
 abstract class Controller {
47 47
 
48
-	/**
49
-	 * app name
50
-	 * @var string
51
-	 * @since 7.0.0
52
-	 */
53
-	protected $appName;
54
-
55
-	/**
56
-	 * current request
57
-	 * @var \OCP\IRequest
58
-	 * @since 6.0.0
59
-	 */
60
-	protected $request;
61
-
62
-	/**
63
-	 * @var array
64
-	 * @since 7.0.0
65
-	 */
66
-	private $responders;
67
-
68
-	/**
69
-	 * constructor of the controller
70
-	 * @param string $appName the name of the app
71
-	 * @param IRequest $request an instance of the request
72
-	 * @since 6.0.0 - parameter $appName was added in 7.0.0 - parameter $app was removed in 7.0.0
73
-	 */
74
-	public function __construct($appName,
75
-	                            IRequest $request) {
76
-		$this->appName = $appName;
77
-		$this->request = $request;
78
-
79
-		// default responders
80
-		$this->responders = array(
81
-			'json' => function ($data) {
82
-				if ($data instanceof DataResponse) {
83
-					$response = new JSONResponse(
84
-						$data->getData(),
85
-						$data->getStatus()
86
-					);
87
-					$dataHeaders = $data->getHeaders();
88
-					$headers = $response->getHeaders();
89
-					// do not overwrite Content-Type if it already exists
90
-					if (isset($dataHeaders['Content-Type'])) {
91
-						unset($headers['Content-Type']);
92
-					}
93
-					$response->setHeaders(array_merge($dataHeaders, $headers));
94
-					return $response;
95
-				}
96
-				return new JSONResponse($data);
97
-			}
98
-		);
99
-	}
100
-
101
-
102
-	/**
103
-	 * Parses an HTTP accept header and returns the supported responder type
104
-	 * @param string $acceptHeader
105
-	 * @return string the responder type
106
-	 * @since 7.0.0
107
-	 * @since 9.1.0 Added default parameter
108
-	 */
109
-	public function getResponderByHTTPHeader($acceptHeader, $default='json') {
110
-		$headers = explode(',', $acceptHeader);
111
-
112
-		// return the first matching responder
113
-		foreach ($headers as $header) {
114
-			$header = strtolower(trim($header));
115
-
116
-			$responder = str_replace('application/', '', $header);
117
-
118
-			if (array_key_exists($responder, $this->responders)) {
119
-				return $responder;
120
-			}
121
-		}
122
-
123
-		// no matching header return default
124
-		return $default;
125
-	}
126
-
127
-
128
-	/**
129
-	 * Registers a formatter for a type
130
-	 * @param string $format
131
-	 * @param \Closure $responder
132
-	 * @since 7.0.0
133
-	 */
134
-	protected function registerResponder($format, \Closure $responder) {
135
-		$this->responders[$format] = $responder;
136
-	}
137
-
138
-
139
-	/**
140
-	 * Serializes and formats a response
141
-	 * @param mixed $response the value that was returned from a controller and
142
-	 * is not a Response instance
143
-	 * @param string $format the format for which a formatter has been registered
144
-	 * @throws \DomainException if format does not match a registered formatter
145
-	 * @return Response
146
-	 * @since 7.0.0
147
-	 */
148
-	public function buildResponse($response, $format='json') {
149
-		if(array_key_exists($format, $this->responders)) {
150
-
151
-			$responder = $this->responders[$format];
152
-
153
-			return $responder($response);
154
-
155
-		}
156
-		throw new \DomainException('No responder registered for format '.
157
-			$format . '!');
158
-	}
159
-
160
-
161
-	/**
162
-	 * Lets you access post and get parameters by the index
163
-	 * @deprecated 7.0.0 write your parameters as method arguments instead
164
-	 * @param string $key the key which you want to access in the URL Parameter
165
-	 *                     placeholder, $_POST or $_GET array.
166
-	 *                     The priority how they're returned is the following:
167
-	 *                     1. URL parameters
168
-	 *                     2. POST parameters
169
-	 *                     3. GET parameters
170
-	 * @param string $default If the key is not found, this value will be returned
171
-	 * @return mixed the content of the array
172
-	 * @since 6.0.0
173
-	 */
174
-	public function params($key, $default=null){
175
-		return $this->request->getParam($key, $default);
176
-	}
177
-
178
-
179
-	/**
180
-	 * Returns all params that were received, be it from the request
181
-	 * (as GET or POST) or through the URL by the route
182
-	 * @deprecated 7.0.0 use $this->request instead
183
-	 * @return array the array with all parameters
184
-	 * @since 6.0.0
185
-	 */
186
-	public function getParams() {
187
-		return $this->request->getParams();
188
-	}
189
-
190
-
191
-	/**
192
-	 * Returns the method of the request
193
-	 * @deprecated 7.0.0 use $this->request instead
194
-	 * @return string the method of the request (POST, GET, etc)
195
-	 * @since 6.0.0
196
-	 */
197
-	public function method() {
198
-		return $this->request->getMethod();
199
-	}
200
-
201
-
202
-	/**
203
-	 * Shortcut for accessing an uploaded file through the $_FILES array
204
-	 * @deprecated 7.0.0 use $this->request instead
205
-	 * @param string $key the key that will be taken from the $_FILES array
206
-	 * @return array the file in the $_FILES element
207
-	 * @since 6.0.0
208
-	 */
209
-	public function getUploadedFile($key) {
210
-		return $this->request->getUploadedFile($key);
211
-	}
212
-
213
-
214
-	/**
215
-	 * Shortcut for getting env variables
216
-	 * @deprecated 7.0.0 use $this->request instead
217
-	 * @param string $key the key that will be taken from the $_ENV array
218
-	 * @return array the value in the $_ENV element
219
-	 * @since 6.0.0
220
-	 */
221
-	public function env($key) {
222
-		return $this->request->getEnv($key);
223
-	}
224
-
225
-
226
-	/**
227
-	 * Shortcut for getting cookie variables
228
-	 * @deprecated 7.0.0 use $this->request instead
229
-	 * @param string $key the key that will be taken from the $_COOKIE array
230
-	 * @return array the value in the $_COOKIE element
231
-	 * @since 6.0.0
232
-	 */
233
-	public function cookie($key) {
234
-		return $this->request->getCookie($key);
235
-	}
236
-
237
-
238
-	/**
239
-	 * Shortcut for rendering a template
240
-	 * @deprecated 7.0.0 return a template response instead
241
-	 * @param string $templateName the name of the template
242
-	 * @param array $params the template parameters in key => value structure
243
-	 * @param string $renderAs user renders a full page, blank only your template
244
-	 *                          admin an entry in the admin settings
245
-	 * @param string[] $headers set additional headers in name/value pairs
246
-	 * @return \OCP\AppFramework\Http\TemplateResponse containing the page
247
-	 * @since 6.0.0
248
-	 */
249
-	public function render($templateName, array $params=array(),
250
-							$renderAs='user', array $headers=array()){
251
-		$response = new TemplateResponse($this->appName, $templateName);
252
-		$response->setParams($params);
253
-		$response->renderAs($renderAs);
254
-
255
-		foreach($headers as $name => $value){
256
-			$response->addHeader($name, $value);
257
-		}
258
-
259
-		return $response;
260
-	}
48
+    /**
49
+     * app name
50
+     * @var string
51
+     * @since 7.0.0
52
+     */
53
+    protected $appName;
54
+
55
+    /**
56
+     * current request
57
+     * @var \OCP\IRequest
58
+     * @since 6.0.0
59
+     */
60
+    protected $request;
61
+
62
+    /**
63
+     * @var array
64
+     * @since 7.0.0
65
+     */
66
+    private $responders;
67
+
68
+    /**
69
+     * constructor of the controller
70
+     * @param string $appName the name of the app
71
+     * @param IRequest $request an instance of the request
72
+     * @since 6.0.0 - parameter $appName was added in 7.0.0 - parameter $app was removed in 7.0.0
73
+     */
74
+    public function __construct($appName,
75
+                                IRequest $request) {
76
+        $this->appName = $appName;
77
+        $this->request = $request;
78
+
79
+        // default responders
80
+        $this->responders = array(
81
+            'json' => function ($data) {
82
+                if ($data instanceof DataResponse) {
83
+                    $response = new JSONResponse(
84
+                        $data->getData(),
85
+                        $data->getStatus()
86
+                    );
87
+                    $dataHeaders = $data->getHeaders();
88
+                    $headers = $response->getHeaders();
89
+                    // do not overwrite Content-Type if it already exists
90
+                    if (isset($dataHeaders['Content-Type'])) {
91
+                        unset($headers['Content-Type']);
92
+                    }
93
+                    $response->setHeaders(array_merge($dataHeaders, $headers));
94
+                    return $response;
95
+                }
96
+                return new JSONResponse($data);
97
+            }
98
+        );
99
+    }
100
+
101
+
102
+    /**
103
+     * Parses an HTTP accept header and returns the supported responder type
104
+     * @param string $acceptHeader
105
+     * @return string the responder type
106
+     * @since 7.0.0
107
+     * @since 9.1.0 Added default parameter
108
+     */
109
+    public function getResponderByHTTPHeader($acceptHeader, $default='json') {
110
+        $headers = explode(',', $acceptHeader);
111
+
112
+        // return the first matching responder
113
+        foreach ($headers as $header) {
114
+            $header = strtolower(trim($header));
115
+
116
+            $responder = str_replace('application/', '', $header);
117
+
118
+            if (array_key_exists($responder, $this->responders)) {
119
+                return $responder;
120
+            }
121
+        }
122
+
123
+        // no matching header return default
124
+        return $default;
125
+    }
126
+
127
+
128
+    /**
129
+     * Registers a formatter for a type
130
+     * @param string $format
131
+     * @param \Closure $responder
132
+     * @since 7.0.0
133
+     */
134
+    protected function registerResponder($format, \Closure $responder) {
135
+        $this->responders[$format] = $responder;
136
+    }
137
+
138
+
139
+    /**
140
+     * Serializes and formats a response
141
+     * @param mixed $response the value that was returned from a controller and
142
+     * is not a Response instance
143
+     * @param string $format the format for which a formatter has been registered
144
+     * @throws \DomainException if format does not match a registered formatter
145
+     * @return Response
146
+     * @since 7.0.0
147
+     */
148
+    public function buildResponse($response, $format='json') {
149
+        if(array_key_exists($format, $this->responders)) {
150
+
151
+            $responder = $this->responders[$format];
152
+
153
+            return $responder($response);
154
+
155
+        }
156
+        throw new \DomainException('No responder registered for format '.
157
+            $format . '!');
158
+    }
159
+
160
+
161
+    /**
162
+     * Lets you access post and get parameters by the index
163
+     * @deprecated 7.0.0 write your parameters as method arguments instead
164
+     * @param string $key the key which you want to access in the URL Parameter
165
+     *                     placeholder, $_POST or $_GET array.
166
+     *                     The priority how they're returned is the following:
167
+     *                     1. URL parameters
168
+     *                     2. POST parameters
169
+     *                     3. GET parameters
170
+     * @param string $default If the key is not found, this value will be returned
171
+     * @return mixed the content of the array
172
+     * @since 6.0.0
173
+     */
174
+    public function params($key, $default=null){
175
+        return $this->request->getParam($key, $default);
176
+    }
177
+
178
+
179
+    /**
180
+     * Returns all params that were received, be it from the request
181
+     * (as GET or POST) or through the URL by the route
182
+     * @deprecated 7.0.0 use $this->request instead
183
+     * @return array the array with all parameters
184
+     * @since 6.0.0
185
+     */
186
+    public function getParams() {
187
+        return $this->request->getParams();
188
+    }
189
+
190
+
191
+    /**
192
+     * Returns the method of the request
193
+     * @deprecated 7.0.0 use $this->request instead
194
+     * @return string the method of the request (POST, GET, etc)
195
+     * @since 6.0.0
196
+     */
197
+    public function method() {
198
+        return $this->request->getMethod();
199
+    }
200
+
201
+
202
+    /**
203
+     * Shortcut for accessing an uploaded file through the $_FILES array
204
+     * @deprecated 7.0.0 use $this->request instead
205
+     * @param string $key the key that will be taken from the $_FILES array
206
+     * @return array the file in the $_FILES element
207
+     * @since 6.0.0
208
+     */
209
+    public function getUploadedFile($key) {
210
+        return $this->request->getUploadedFile($key);
211
+    }
212
+
213
+
214
+    /**
215
+     * Shortcut for getting env variables
216
+     * @deprecated 7.0.0 use $this->request instead
217
+     * @param string $key the key that will be taken from the $_ENV array
218
+     * @return array the value in the $_ENV element
219
+     * @since 6.0.0
220
+     */
221
+    public function env($key) {
222
+        return $this->request->getEnv($key);
223
+    }
224
+
225
+
226
+    /**
227
+     * Shortcut for getting cookie variables
228
+     * @deprecated 7.0.0 use $this->request instead
229
+     * @param string $key the key that will be taken from the $_COOKIE array
230
+     * @return array the value in the $_COOKIE element
231
+     * @since 6.0.0
232
+     */
233
+    public function cookie($key) {
234
+        return $this->request->getCookie($key);
235
+    }
236
+
237
+
238
+    /**
239
+     * Shortcut for rendering a template
240
+     * @deprecated 7.0.0 return a template response instead
241
+     * @param string $templateName the name of the template
242
+     * @param array $params the template parameters in key => value structure
243
+     * @param string $renderAs user renders a full page, blank only your template
244
+     *                          admin an entry in the admin settings
245
+     * @param string[] $headers set additional headers in name/value pairs
246
+     * @return \OCP\AppFramework\Http\TemplateResponse containing the page
247
+     * @since 6.0.0
248
+     */
249
+    public function render($templateName, array $params=array(),
250
+                            $renderAs='user', array $headers=array()){
251
+        $response = new TemplateResponse($this->appName, $templateName);
252
+        $response->setParams($params);
253
+        $response->renderAs($renderAs);
254
+
255
+        foreach($headers as $name => $value){
256
+            $response->addHeader($name, $value);
257
+        }
258
+
259
+        return $response;
260
+    }
261 261
 
262 262
 
263 263
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/ApiController.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
      * defaults to 'Authorization, Content-Type, Accept'
56 56
      * @param int $corsMaxAge number in seconds how long a preflighted OPTIONS
57 57
      * request should be cached, defaults to 1728000 seconds
58
-	 * @since 7.0.0
58
+     * @since 7.0.0
59 59
      */
60 60
     public function __construct($appName,
61 61
                                 IRequest $request,
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
      * @NoAdminRequired
77 77
      * @NoCSRFRequired
78 78
      * @PublicPage
79
-	 * @since 7.0.0
79
+     * @since 7.0.0
80 80
      */
81 81
     public function preflightedCors() {
82 82
         if(isset($this->request->server['HTTP_ORIGIN'])) {
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/MultipleObjectsReturnedException.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -32,13 +32,13 @@
 block discarded – undo
32 32
  */
33 33
 class MultipleObjectsReturnedException extends \Exception {
34 34
 
35
-	/**
36
-	 * Constructor
37
-	 * @param string $msg the error message
38
-	 * @since 7.0.0
39
-	 */
40
-	public function __construct($msg){
41
-		parent::__construct($msg);
42
-	}
35
+    /**
36
+     * Constructor
37
+     * @param string $msg the error message
38
+     * @since 7.0.0
39
+     */
40
+    public function __construct($msg){
41
+        parent::__construct($msg);
42
+    }
43 43
 
44 44
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/Mapper.php 1 patch
Indentation   +321 added lines, -321 removed lines patch added patch discarded remove patch
@@ -37,327 +37,327 @@
 block discarded – undo
37 37
  */
38 38
 abstract class Mapper {
39 39
 
40
-	protected $tableName;
41
-	protected $entityClass;
42
-	protected $db;
43
-
44
-	/**
45
-	 * @param IDBConnection $db Instance of the Db abstraction layer
46
-	 * @param string $tableName the name of the table. set this to allow entity
47
-	 * @param string $entityClass the name of the entity that the sql should be
48
-	 * mapped to queries without using sql
49
-	 * @since 7.0.0
50
-	 */
51
-	public function __construct(IDBConnection $db, $tableName, $entityClass=null){
52
-		$this->db = $db;
53
-		$this->tableName = '*PREFIX*' . $tableName;
54
-
55
-		// if not given set the entity name to the class without the mapper part
56
-		// cache it here for later use since reflection is slow
57
-		if($entityClass === null) {
58
-			$this->entityClass = str_replace('Mapper', '', get_class($this));
59
-		} else {
60
-			$this->entityClass = $entityClass;
61
-		}
62
-	}
63
-
64
-
65
-	/**
66
-	 * @return string the table name
67
-	 * @since 7.0.0
68
-	 */
69
-	public function getTableName(){
70
-		return $this->tableName;
71
-	}
72
-
73
-
74
-	/**
75
-	 * Deletes an entity from the table
76
-	 * @param Entity $entity the entity that should be deleted
77
-	 * @return Entity the deleted entity
78
-	 * @since 7.0.0 - return value added in 8.1.0
79
-	 */
80
-	public function delete(Entity $entity){
81
-		$sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
82
-		$stmt = $this->execute($sql, [$entity->getId()]);
83
-		$stmt->closeCursor();
84
-		return $entity;
85
-	}
86
-
87
-
88
-	/**
89
-	 * Creates a new entry in the db from an entity
90
-	 * @param Entity $entity the entity that should be created
91
-	 * @return Entity the saved entity with the set id
92
-	 * @since 7.0.0
93
-	 */
94
-	public function insert(Entity $entity){
95
-		// get updated fields to save, fields have to be set using a setter to
96
-		// be saved
97
-		$properties = $entity->getUpdatedFields();
98
-		$values = '';
99
-		$columns = '';
100
-		$params = [];
101
-
102
-		// build the fields
103
-		$i = 0;
104
-		foreach($properties as $property => $updated) {
105
-			$column = $entity->propertyToColumn($property);
106
-			$getter = 'get' . ucfirst($property);
107
-
108
-			$columns .= '`' . $column . '`';
109
-			$values .= '?';
110
-
111
-			// only append colon if there are more entries
112
-			if($i < count($properties)-1){
113
-				$columns .= ',';
114
-				$values .= ',';
115
-			}
116
-
117
-			$params[] = $entity->$getter();
118
-			$i++;
119
-
120
-		}
121
-
122
-		$sql = 'INSERT INTO `' . $this->tableName . '`(' .
123
-				$columns . ') VALUES(' . $values . ')';
124
-
125
-		$stmt = $this->execute($sql, $params);
126
-
127
-		$entity->setId((int) $this->db->lastInsertId($this->tableName));
128
-
129
-		$stmt->closeCursor();
130
-
131
-		return $entity;
132
-	}
133
-
134
-
135
-
136
-	/**
137
-	 * Updates an entry in the db from an entity
138
-	 * @throws \InvalidArgumentException if entity has no id
139
-	 * @param Entity $entity the entity that should be created
140
-	 * @return Entity the saved entity with the set id
141
-	 * @since 7.0.0 - return value was added in 8.0.0
142
-	 */
143
-	public function update(Entity $entity){
144
-		// if entity wasn't changed it makes no sense to run a db query
145
-		$properties = $entity->getUpdatedFields();
146
-		if(count($properties) === 0) {
147
-			return $entity;
148
-		}
149
-
150
-		// entity needs an id
151
-		$id = $entity->getId();
152
-		if($id === null){
153
-			throw new \InvalidArgumentException(
154
-				'Entity which should be updated has no id');
155
-		}
156
-
157
-		// get updated fields to save, fields have to be set using a setter to
158
-		// be saved
159
-		// do not update the id field
160
-		unset($properties['id']);
161
-
162
-		$columns = '';
163
-		$params = [];
164
-
165
-		// build the fields
166
-		$i = 0;
167
-		foreach($properties as $property => $updated) {
168
-
169
-			$column = $entity->propertyToColumn($property);
170
-			$getter = 'get' . ucfirst($property);
171
-
172
-			$columns .= '`' . $column . '` = ?';
173
-
174
-			// only append colon if there are more entries
175
-			if($i < count($properties)-1){
176
-				$columns .= ',';
177
-			}
178
-
179
-			$params[] = $entity->$getter();
180
-			$i++;
181
-		}
182
-
183
-		$sql = 'UPDATE `' . $this->tableName . '` SET ' .
184
-				$columns . ' WHERE `id` = ?';
185
-		$params[] = $id;
186
-
187
-		$stmt = $this->execute($sql, $params);
188
-		$stmt->closeCursor();
189
-
190
-		return $entity;
191
-	}
192
-
193
-	/**
194
-	 * Checks if an array is associative
195
-	 * @param array $array
196
-	 * @return bool true if associative
197
-	 * @since 8.1.0
198
-	 */
199
-	private function isAssocArray(array $array) {
200
-		return array_values($array) !== $array;
201
-	}
202
-
203
-	/**
204
-	 * Returns the correct PDO constant based on the value type
205
-	 * @param $value
206
-	 * @return int PDO constant
207
-	 * @since 8.1.0
208
-	 */
209
-	private function getPDOType($value) {
210
-		switch (gettype($value)) {
211
-			case 'integer':
212
-				return \PDO::PARAM_INT;
213
-			case 'boolean':
214
-				return \PDO::PARAM_BOOL;
215
-			default:
216
-				return \PDO::PARAM_STR;
217
-		}
218
-	}
219
-
220
-
221
-	/**
222
-	 * Runs an sql query
223
-	 * @param string $sql the prepare string
224
-	 * @param array $params the params which should replace the ? in the sql query
225
-	 * @param int $limit the maximum number of rows
226
-	 * @param int $offset from which row we want to start
227
-	 * @return \PDOStatement the database query result
228
-	 * @since 7.0.0
229
-	 */
230
-	protected function execute($sql, array $params=[], $limit=null, $offset=null){
231
-		$query = $this->db->prepare($sql, $limit, $offset);
232
-
233
-		if ($this->isAssocArray($params)) {
234
-			foreach ($params as $key => $param) {
235
-				$pdoConstant = $this->getPDOType($param);
236
-				$query->bindValue($key, $param, $pdoConstant);
237
-			}
238
-		} else {
239
-			$index = 1;  // bindParam is 1 indexed
240
-			foreach ($params as $param) {
241
-				$pdoConstant = $this->getPDOType($param);
242
-				$query->bindValue($index, $param, $pdoConstant);
243
-				$index++;
244
-			}
245
-		}
246
-
247
-		$result = $query->execute();
248
-
249
-		return $query;
250
-	}
251
-
252
-
253
-	/**
254
-	 * Returns an db result and throws exceptions when there are more or less
255
-	 * results
256
-	 * @see findEntity
257
-	 * @param string $sql the sql query
258
-	 * @param array $params the parameters of the sql query
259
-	 * @param int $limit the maximum number of rows
260
-	 * @param int $offset from which row we want to start
261
-	 * @throws DoesNotExistException if the item does not exist
262
-	 * @throws MultipleObjectsReturnedException if more than one item exist
263
-	 * @return array the result as row
264
-	 * @since 7.0.0
265
-	 */
266
-	protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
267
-		$stmt = $this->execute($sql, $params, $limit, $offset);
268
-		$row = $stmt->fetch();
269
-
270
-		if($row === false || $row === null){
271
-			$stmt->closeCursor();
272
-			$msg = $this->buildDebugMessage(
273
-				'Did expect one result but found none when executing', $sql, $params, $limit, $offset
274
-			);
275
-			throw new DoesNotExistException($msg);
276
-		}
277
-		$row2 = $stmt->fetch();
278
-		$stmt->closeCursor();
279
-		//MDB2 returns null, PDO and doctrine false when no row is available
280
-		if( ! ($row2 === false || $row2 === null )) {
281
-			$msg = $this->buildDebugMessage(
282
-				'Did not expect more than one result when executing', $sql, $params, $limit, $offset
283
-			);
284
-			throw new MultipleObjectsReturnedException($msg);
285
-		} else {
286
-			return $row;
287
-		}
288
-	}
289
-
290
-	/**
291
-	 * Builds an error message by prepending the $msg to an error message which
292
-	 * has the parameters
293
-	 * @see findEntity
294
-	 * @param string $sql the sql query
295
-	 * @param array $params the parameters of the sql query
296
-	 * @param int $limit the maximum number of rows
297
-	 * @param int $offset from which row we want to start
298
-	 * @return string formatted error message string
299
-	 * @since 9.1.0
300
-	 */
301
-	private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
302
-		return $msg .
303
-					': query "' .	$sql . '"; ' .
304
-					'parameters ' . print_r($params, true) . '; ' .
305
-					'limit "' . $limit . '"; '.
306
-					'offset "' . $offset . '"';
307
-	}
308
-
309
-
310
-	/**
311
-	 * Creates an entity from a row. Automatically determines the entity class
312
-	 * from the current mapper name (MyEntityMapper -> MyEntity)
313
-	 * @param array $row the row which should be converted to an entity
314
-	 * @return Entity the entity
315
-	 * @since 7.0.0
316
-	 */
317
-	protected function mapRowToEntity($row) {
318
-		return call_user_func($this->entityClass .'::fromRow', $row);
319
-	}
320
-
321
-
322
-	/**
323
-	 * Runs a sql query and returns an array of entities
324
-	 * @param string $sql the prepare string
325
-	 * @param array $params the params which should replace the ? in the sql query
326
-	 * @param int $limit the maximum number of rows
327
-	 * @param int $offset from which row we want to start
328
-	 * @return array all fetched entities
329
-	 * @since 7.0.0
330
-	 */
331
-	protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
332
-		$stmt = $this->execute($sql, $params, $limit, $offset);
333
-
334
-		$entities = [];
335
-
336
-		while($row = $stmt->fetch()){
337
-			$entities[] = $this->mapRowToEntity($row);
338
-		}
339
-
340
-		$stmt->closeCursor();
341
-
342
-		return $entities;
343
-	}
344
-
345
-
346
-	/**
347
-	 * Returns an db result and throws exceptions when there are more or less
348
-	 * results
349
-	 * @param string $sql the sql query
350
-	 * @param array $params the parameters of the sql query
351
-	 * @param int $limit the maximum number of rows
352
-	 * @param int $offset from which row we want to start
353
-	 * @throws DoesNotExistException if the item does not exist
354
-	 * @throws MultipleObjectsReturnedException if more than one item exist
355
-	 * @return Entity the entity
356
-	 * @since 7.0.0
357
-	 */
358
-	protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
359
-		return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
360
-	}
40
+    protected $tableName;
41
+    protected $entityClass;
42
+    protected $db;
43
+
44
+    /**
45
+     * @param IDBConnection $db Instance of the Db abstraction layer
46
+     * @param string $tableName the name of the table. set this to allow entity
47
+     * @param string $entityClass the name of the entity that the sql should be
48
+     * mapped to queries without using sql
49
+     * @since 7.0.0
50
+     */
51
+    public function __construct(IDBConnection $db, $tableName, $entityClass=null){
52
+        $this->db = $db;
53
+        $this->tableName = '*PREFIX*' . $tableName;
54
+
55
+        // if not given set the entity name to the class without the mapper part
56
+        // cache it here for later use since reflection is slow
57
+        if($entityClass === null) {
58
+            $this->entityClass = str_replace('Mapper', '', get_class($this));
59
+        } else {
60
+            $this->entityClass = $entityClass;
61
+        }
62
+    }
63
+
64
+
65
+    /**
66
+     * @return string the table name
67
+     * @since 7.0.0
68
+     */
69
+    public function getTableName(){
70
+        return $this->tableName;
71
+    }
72
+
73
+
74
+    /**
75
+     * Deletes an entity from the table
76
+     * @param Entity $entity the entity that should be deleted
77
+     * @return Entity the deleted entity
78
+     * @since 7.0.0 - return value added in 8.1.0
79
+     */
80
+    public function delete(Entity $entity){
81
+        $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?';
82
+        $stmt = $this->execute($sql, [$entity->getId()]);
83
+        $stmt->closeCursor();
84
+        return $entity;
85
+    }
86
+
87
+
88
+    /**
89
+     * Creates a new entry in the db from an entity
90
+     * @param Entity $entity the entity that should be created
91
+     * @return Entity the saved entity with the set id
92
+     * @since 7.0.0
93
+     */
94
+    public function insert(Entity $entity){
95
+        // get updated fields to save, fields have to be set using a setter to
96
+        // be saved
97
+        $properties = $entity->getUpdatedFields();
98
+        $values = '';
99
+        $columns = '';
100
+        $params = [];
101
+
102
+        // build the fields
103
+        $i = 0;
104
+        foreach($properties as $property => $updated) {
105
+            $column = $entity->propertyToColumn($property);
106
+            $getter = 'get' . ucfirst($property);
107
+
108
+            $columns .= '`' . $column . '`';
109
+            $values .= '?';
110
+
111
+            // only append colon if there are more entries
112
+            if($i < count($properties)-1){
113
+                $columns .= ',';
114
+                $values .= ',';
115
+            }
116
+
117
+            $params[] = $entity->$getter();
118
+            $i++;
119
+
120
+        }
121
+
122
+        $sql = 'INSERT INTO `' . $this->tableName . '`(' .
123
+                $columns . ') VALUES(' . $values . ')';
124
+
125
+        $stmt = $this->execute($sql, $params);
126
+
127
+        $entity->setId((int) $this->db->lastInsertId($this->tableName));
128
+
129
+        $stmt->closeCursor();
130
+
131
+        return $entity;
132
+    }
133
+
134
+
135
+
136
+    /**
137
+     * Updates an entry in the db from an entity
138
+     * @throws \InvalidArgumentException if entity has no id
139
+     * @param Entity $entity the entity that should be created
140
+     * @return Entity the saved entity with the set id
141
+     * @since 7.0.0 - return value was added in 8.0.0
142
+     */
143
+    public function update(Entity $entity){
144
+        // if entity wasn't changed it makes no sense to run a db query
145
+        $properties = $entity->getUpdatedFields();
146
+        if(count($properties) === 0) {
147
+            return $entity;
148
+        }
149
+
150
+        // entity needs an id
151
+        $id = $entity->getId();
152
+        if($id === null){
153
+            throw new \InvalidArgumentException(
154
+                'Entity which should be updated has no id');
155
+        }
156
+
157
+        // get updated fields to save, fields have to be set using a setter to
158
+        // be saved
159
+        // do not update the id field
160
+        unset($properties['id']);
161
+
162
+        $columns = '';
163
+        $params = [];
164
+
165
+        // build the fields
166
+        $i = 0;
167
+        foreach($properties as $property => $updated) {
168
+
169
+            $column = $entity->propertyToColumn($property);
170
+            $getter = 'get' . ucfirst($property);
171
+
172
+            $columns .= '`' . $column . '` = ?';
173
+
174
+            // only append colon if there are more entries
175
+            if($i < count($properties)-1){
176
+                $columns .= ',';
177
+            }
178
+
179
+            $params[] = $entity->$getter();
180
+            $i++;
181
+        }
182
+
183
+        $sql = 'UPDATE `' . $this->tableName . '` SET ' .
184
+                $columns . ' WHERE `id` = ?';
185
+        $params[] = $id;
186
+
187
+        $stmt = $this->execute($sql, $params);
188
+        $stmt->closeCursor();
189
+
190
+        return $entity;
191
+    }
192
+
193
+    /**
194
+     * Checks if an array is associative
195
+     * @param array $array
196
+     * @return bool true if associative
197
+     * @since 8.1.0
198
+     */
199
+    private function isAssocArray(array $array) {
200
+        return array_values($array) !== $array;
201
+    }
202
+
203
+    /**
204
+     * Returns the correct PDO constant based on the value type
205
+     * @param $value
206
+     * @return int PDO constant
207
+     * @since 8.1.0
208
+     */
209
+    private function getPDOType($value) {
210
+        switch (gettype($value)) {
211
+            case 'integer':
212
+                return \PDO::PARAM_INT;
213
+            case 'boolean':
214
+                return \PDO::PARAM_BOOL;
215
+            default:
216
+                return \PDO::PARAM_STR;
217
+        }
218
+    }
219
+
220
+
221
+    /**
222
+     * Runs an sql query
223
+     * @param string $sql the prepare string
224
+     * @param array $params the params which should replace the ? in the sql query
225
+     * @param int $limit the maximum number of rows
226
+     * @param int $offset from which row we want to start
227
+     * @return \PDOStatement the database query result
228
+     * @since 7.0.0
229
+     */
230
+    protected function execute($sql, array $params=[], $limit=null, $offset=null){
231
+        $query = $this->db->prepare($sql, $limit, $offset);
232
+
233
+        if ($this->isAssocArray($params)) {
234
+            foreach ($params as $key => $param) {
235
+                $pdoConstant = $this->getPDOType($param);
236
+                $query->bindValue($key, $param, $pdoConstant);
237
+            }
238
+        } else {
239
+            $index = 1;  // bindParam is 1 indexed
240
+            foreach ($params as $param) {
241
+                $pdoConstant = $this->getPDOType($param);
242
+                $query->bindValue($index, $param, $pdoConstant);
243
+                $index++;
244
+            }
245
+        }
246
+
247
+        $result = $query->execute();
248
+
249
+        return $query;
250
+    }
251
+
252
+
253
+    /**
254
+     * Returns an db result and throws exceptions when there are more or less
255
+     * results
256
+     * @see findEntity
257
+     * @param string $sql the sql query
258
+     * @param array $params the parameters of the sql query
259
+     * @param int $limit the maximum number of rows
260
+     * @param int $offset from which row we want to start
261
+     * @throws DoesNotExistException if the item does not exist
262
+     * @throws MultipleObjectsReturnedException if more than one item exist
263
+     * @return array the result as row
264
+     * @since 7.0.0
265
+     */
266
+    protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){
267
+        $stmt = $this->execute($sql, $params, $limit, $offset);
268
+        $row = $stmt->fetch();
269
+
270
+        if($row === false || $row === null){
271
+            $stmt->closeCursor();
272
+            $msg = $this->buildDebugMessage(
273
+                'Did expect one result but found none when executing', $sql, $params, $limit, $offset
274
+            );
275
+            throw new DoesNotExistException($msg);
276
+        }
277
+        $row2 = $stmt->fetch();
278
+        $stmt->closeCursor();
279
+        //MDB2 returns null, PDO and doctrine false when no row is available
280
+        if( ! ($row2 === false || $row2 === null )) {
281
+            $msg = $this->buildDebugMessage(
282
+                'Did not expect more than one result when executing', $sql, $params, $limit, $offset
283
+            );
284
+            throw new MultipleObjectsReturnedException($msg);
285
+        } else {
286
+            return $row;
287
+        }
288
+    }
289
+
290
+    /**
291
+     * Builds an error message by prepending the $msg to an error message which
292
+     * has the parameters
293
+     * @see findEntity
294
+     * @param string $sql the sql query
295
+     * @param array $params the parameters of the sql query
296
+     * @param int $limit the maximum number of rows
297
+     * @param int $offset from which row we want to start
298
+     * @return string formatted error message string
299
+     * @since 9.1.0
300
+     */
301
+    private function buildDebugMessage($msg, $sql, array $params=[], $limit=null, $offset=null) {
302
+        return $msg .
303
+                    ': query "' .	$sql . '"; ' .
304
+                    'parameters ' . print_r($params, true) . '; ' .
305
+                    'limit "' . $limit . '"; '.
306
+                    'offset "' . $offset . '"';
307
+    }
308
+
309
+
310
+    /**
311
+     * Creates an entity from a row. Automatically determines the entity class
312
+     * from the current mapper name (MyEntityMapper -> MyEntity)
313
+     * @param array $row the row which should be converted to an entity
314
+     * @return Entity the entity
315
+     * @since 7.0.0
316
+     */
317
+    protected function mapRowToEntity($row) {
318
+        return call_user_func($this->entityClass .'::fromRow', $row);
319
+    }
320
+
321
+
322
+    /**
323
+     * Runs a sql query and returns an array of entities
324
+     * @param string $sql the prepare string
325
+     * @param array $params the params which should replace the ? in the sql query
326
+     * @param int $limit the maximum number of rows
327
+     * @param int $offset from which row we want to start
328
+     * @return array all fetched entities
329
+     * @since 7.0.0
330
+     */
331
+    protected function findEntities($sql, array $params=[], $limit=null, $offset=null) {
332
+        $stmt = $this->execute($sql, $params, $limit, $offset);
333
+
334
+        $entities = [];
335
+
336
+        while($row = $stmt->fetch()){
337
+            $entities[] = $this->mapRowToEntity($row);
338
+        }
339
+
340
+        $stmt->closeCursor();
341
+
342
+        return $entities;
343
+    }
344
+
345
+
346
+    /**
347
+     * Returns an db result and throws exceptions when there are more or less
348
+     * results
349
+     * @param string $sql the sql query
350
+     * @param array $params the parameters of the sql query
351
+     * @param int $limit the maximum number of rows
352
+     * @param int $offset from which row we want to start
353
+     * @throws DoesNotExistException if the item does not exist
354
+     * @throws MultipleObjectsReturnedException if more than one item exist
355
+     * @return Entity the entity
356
+     * @since 7.0.0
357
+     */
358
+    protected function findEntity($sql, array $params=[], $limit=null, $offset=null){
359
+        return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset));
360
+    }
361 361
 
362 362
 
363 363
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/DoesNotExistException.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -32,13 +32,13 @@
 block discarded – undo
32 32
  */
33 33
 class DoesNotExistException extends \Exception {
34 34
 
35
-	/**
36
-	 * Constructor
37
-	 * @param string $msg the error message
38
-	 * @since 7.0.0
39
-	 */
40
-	public function __construct($msg){
41
-		parent::__construct($msg);
42
-	}
35
+    /**
36
+     * Constructor
37
+     * @param string $msg the error message
38
+     * @since 7.0.0
39
+     */
40
+    public function __construct($msg){
41
+        parent::__construct($msg);
42
+    }
43 43
 
44 44
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/Entity.php 1 patch
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -31,224 +31,224 @@
 block discarded – undo
31 31
  */
32 32
 abstract class Entity {
33 33
 
34
-	public $id;
34
+    public $id;
35 35
 
36
-	private $_updatedFields = array();
37
-	private $_fieldTypes = array('id' => 'integer');
36
+    private $_updatedFields = array();
37
+    private $_fieldTypes = array('id' => 'integer');
38 38
 
39 39
 
40
-	/**
41
-	 * Simple alternative constructor for building entities from a request
42
-	 * @param array $params the array which was obtained via $this->params('key')
43
-	 * in the controller
44
-	 * @return Entity
45
-	 * @since 7.0.0
46
-	 */
47
-	public static function fromParams(array $params) {
48
-		$instance = new static();
40
+    /**
41
+     * Simple alternative constructor for building entities from a request
42
+     * @param array $params the array which was obtained via $this->params('key')
43
+     * in the controller
44
+     * @return Entity
45
+     * @since 7.0.0
46
+     */
47
+    public static function fromParams(array $params) {
48
+        $instance = new static();
49 49
 
50
-		foreach($params as $key => $value) {
51
-			$method = 'set' . ucfirst($key);
52
-			$instance->$method($value);
53
-		}
50
+        foreach($params as $key => $value) {
51
+            $method = 'set' . ucfirst($key);
52
+            $instance->$method($value);
53
+        }
54 54
 
55
-		return $instance;
56
-	}
55
+        return $instance;
56
+    }
57 57
 
58 58
 
59
-	/**
60
-	 * Maps the keys of the row array to the attributes
61
-	 * @param array $row the row to map onto the entity
62
-	 * @since 7.0.0
63
-	 */
64
-	public static function fromRow(array $row){
65
-		$instance = new static();
59
+    /**
60
+     * Maps the keys of the row array to the attributes
61
+     * @param array $row the row to map onto the entity
62
+     * @since 7.0.0
63
+     */
64
+    public static function fromRow(array $row){
65
+        $instance = new static();
66 66
 
67
-		foreach($row as $key => $value){
68
-			$prop = ucfirst($instance->columnToProperty($key));
69
-			$setter = 'set' . $prop;
70
-			$instance->$setter($value);
71
-		}
67
+        foreach($row as $key => $value){
68
+            $prop = ucfirst($instance->columnToProperty($key));
69
+            $setter = 'set' . $prop;
70
+            $instance->$setter($value);
71
+        }
72 72
 
73
-		$instance->resetUpdatedFields();
73
+        $instance->resetUpdatedFields();
74 74
 
75
-		return $instance;
76
-	}
75
+        return $instance;
76
+    }
77 77
 
78 78
 
79
-	/**
80
-	 * @return array with attribute and type
81
-	 * @since 7.0.0
82
-	 */
83
-	public function getFieldTypes() {
84
-		return $this->_fieldTypes;
85
-	}
79
+    /**
80
+     * @return array with attribute and type
81
+     * @since 7.0.0
82
+     */
83
+    public function getFieldTypes() {
84
+        return $this->_fieldTypes;
85
+    }
86 86
 
87 87
 	
88
-	/**
89
-	 * Marks the entity as clean needed for setting the id after the insertion
90
-	 * @since 7.0.0
91
-	 */
92
-	public function resetUpdatedFields(){
93
-		$this->_updatedFields = array();
94
-	}
95
-
96
-	/**
97
-	 * Generic setter for properties
98
-	 * @since 7.0.0
99
-	 */
100
-	protected function setter($name, $args) {
101
-		// setters should only work for existing attributes
102
-		if(property_exists($this, $name)){
103
-			if($this->$name === $args[0]) {
104
-				return;
105
-			}
106
-			$this->markFieldUpdated($name);
107
-
108
-			// if type definition exists, cast to correct type
109
-			if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
110
-				settype($args[0], $this->_fieldTypes[$name]);
111
-			}
112
-			$this->$name = $args[0];
113
-
114
-		} else {
115
-			throw new \BadFunctionCallException($name . 
116
-				' is not a valid attribute');
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * Generic getter for properties
122
-	 * @since 7.0.0
123
-	 */
124
-	protected function getter($name) {
125
-		// getters should only work for existing attributes
126
-		if(property_exists($this, $name)){
127
-			return $this->$name;
128
-		} else {
129
-			throw new \BadFunctionCallException($name . 
130
-				' is not a valid attribute');
131
-		}
132
-	}
133
-
134
-
135
-	/**
136
-	 * Each time a setter is called, push the part after set
137
-	 * into an array: for instance setId will save Id in the 
138
-	 * updated fields array so it can be easily used to create the
139
-	 * getter method
140
-	 * @since 7.0.0
141
-	 */
142
-	public function __call($methodName, $args){
143
-		$attr = lcfirst( substr($methodName, 3) );
144
-
145
-		if(strpos($methodName, 'set') === 0){
146
-			$this->setter($attr, $args);
147
-		} elseif(strpos($methodName, 'get') === 0) {
148
-			return $this->getter($attr);
149
-		} else {
150
-			throw new \BadFunctionCallException($methodName . 
151
-					' does not exist');
152
-		}
153
-
154
-	}
155
-
156
-
157
-	/**
158
-	 * Mark am attribute as updated
159
-	 * @param string $attribute the name of the attribute
160
-	 * @since 7.0.0
161
-	 */
162
-	protected function markFieldUpdated($attribute){
163
-		$this->_updatedFields[$attribute] = true;
164
-	}
165
-
166
-
167
-	/**
168
-	 * Transform a database columnname to a property 
169
-	 * @param string $columnName the name of the column
170
-	 * @return string the property name
171
-	 * @since 7.0.0
172
-	 */
173
-	public function columnToProperty($columnName){
174
-		$parts = explode('_', $columnName);
175
-		$property = null;
176
-
177
-		foreach($parts as $part){
178
-			if($property === null){
179
-				$property = $part;
180
-			} else {
181
-				$property .= ucfirst($part);
182
-			}
183
-		}
184
-
185
-		return $property;
186
-	}
187
-
188
-
189
-	/**
190
-	 * Transform a property to a database column name
191
-	 * @param string $property the name of the property
192
-	 * @return string the column name
193
-	 * @since 7.0.0
194
-	 */
195
-	public function propertyToColumn($property){
196
-		$parts = preg_split('/(?=[A-Z])/', $property);
197
-		$column = null;
198
-
199
-		foreach($parts as $part){
200
-			if($column === null){
201
-				$column = $part;
202
-			} else {
203
-				$column .= '_' . lcfirst($part);
204
-			}
205
-		}
206
-
207
-		return $column;
208
-	}
209
-
210
-
211
-	/**
212
-	 * @return array array of updated fields for update query
213
-	 * @since 7.0.0
214
-	 */
215
-	public function getUpdatedFields(){
216
-		return $this->_updatedFields;
217
-	}
218
-
219
-
220
-	/**
221
-	 * Adds type information for a field so that its automatically casted to
222
-	 * that value once its being returned from the database
223
-	 * @param string $fieldName the name of the attribute
224
-	 * @param string $type the type which will be used to call settype()
225
-	 * @since 7.0.0
226
-	 */
227
-	protected function addType($fieldName, $type){
228
-		$this->_fieldTypes[$fieldName] = $type;
229
-	}
230
-
231
-
232
-	/**
233
-	 * Slugify the value of a given attribute
234
-	 * Warning: This doesn't result in a unique value
235
-	 * @param string $attributeName the name of the attribute, which value should be slugified
236
-	 * @return string slugified value
237
-	 * @since 7.0.0
238
-	 */
239
-	public function slugify($attributeName){
240
-		// toSlug should only work for existing attributes
241
-		if(property_exists($this, $attributeName)){
242
-			$value = $this->$attributeName;
243
-			// replace everything except alphanumeric with a single '-'
244
-			$value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
245
-			$value = strtolower($value);
246
-			// trim '-'
247
-			return trim($value, '-');
248
-		} else {
249
-			throw new \BadFunctionCallException($attributeName .
250
-				' is not a valid attribute');
251
-		}
252
-	}
88
+    /**
89
+     * Marks the entity as clean needed for setting the id after the insertion
90
+     * @since 7.0.0
91
+     */
92
+    public function resetUpdatedFields(){
93
+        $this->_updatedFields = array();
94
+    }
95
+
96
+    /**
97
+     * Generic setter for properties
98
+     * @since 7.0.0
99
+     */
100
+    protected function setter($name, $args) {
101
+        // setters should only work for existing attributes
102
+        if(property_exists($this, $name)){
103
+            if($this->$name === $args[0]) {
104
+                return;
105
+            }
106
+            $this->markFieldUpdated($name);
107
+
108
+            // if type definition exists, cast to correct type
109
+            if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
110
+                settype($args[0], $this->_fieldTypes[$name]);
111
+            }
112
+            $this->$name = $args[0];
113
+
114
+        } else {
115
+            throw new \BadFunctionCallException($name . 
116
+                ' is not a valid attribute');
117
+        }
118
+    }
119
+
120
+    /**
121
+     * Generic getter for properties
122
+     * @since 7.0.0
123
+     */
124
+    protected function getter($name) {
125
+        // getters should only work for existing attributes
126
+        if(property_exists($this, $name)){
127
+            return $this->$name;
128
+        } else {
129
+            throw new \BadFunctionCallException($name . 
130
+                ' is not a valid attribute');
131
+        }
132
+    }
133
+
134
+
135
+    /**
136
+     * Each time a setter is called, push the part after set
137
+     * into an array: for instance setId will save Id in the 
138
+     * updated fields array so it can be easily used to create the
139
+     * getter method
140
+     * @since 7.0.0
141
+     */
142
+    public function __call($methodName, $args){
143
+        $attr = lcfirst( substr($methodName, 3) );
144
+
145
+        if(strpos($methodName, 'set') === 0){
146
+            $this->setter($attr, $args);
147
+        } elseif(strpos($methodName, 'get') === 0) {
148
+            return $this->getter($attr);
149
+        } else {
150
+            throw new \BadFunctionCallException($methodName . 
151
+                    ' does not exist');
152
+        }
153
+
154
+    }
155
+
156
+
157
+    /**
158
+     * Mark am attribute as updated
159
+     * @param string $attribute the name of the attribute
160
+     * @since 7.0.0
161
+     */
162
+    protected function markFieldUpdated($attribute){
163
+        $this->_updatedFields[$attribute] = true;
164
+    }
165
+
166
+
167
+    /**
168
+     * Transform a database columnname to a property 
169
+     * @param string $columnName the name of the column
170
+     * @return string the property name
171
+     * @since 7.0.0
172
+     */
173
+    public function columnToProperty($columnName){
174
+        $parts = explode('_', $columnName);
175
+        $property = null;
176
+
177
+        foreach($parts as $part){
178
+            if($property === null){
179
+                $property = $part;
180
+            } else {
181
+                $property .= ucfirst($part);
182
+            }
183
+        }
184
+
185
+        return $property;
186
+    }
187
+
188
+
189
+    /**
190
+     * Transform a property to a database column name
191
+     * @param string $property the name of the property
192
+     * @return string the column name
193
+     * @since 7.0.0
194
+     */
195
+    public function propertyToColumn($property){
196
+        $parts = preg_split('/(?=[A-Z])/', $property);
197
+        $column = null;
198
+
199
+        foreach($parts as $part){
200
+            if($column === null){
201
+                $column = $part;
202
+            } else {
203
+                $column .= '_' . lcfirst($part);
204
+            }
205
+        }
206
+
207
+        return $column;
208
+    }
209
+
210
+
211
+    /**
212
+     * @return array array of updated fields for update query
213
+     * @since 7.0.0
214
+     */
215
+    public function getUpdatedFields(){
216
+        return $this->_updatedFields;
217
+    }
218
+
219
+
220
+    /**
221
+     * Adds type information for a field so that its automatically casted to
222
+     * that value once its being returned from the database
223
+     * @param string $fieldName the name of the attribute
224
+     * @param string $type the type which will be used to call settype()
225
+     * @since 7.0.0
226
+     */
227
+    protected function addType($fieldName, $type){
228
+        $this->_fieldTypes[$fieldName] = $type;
229
+    }
230
+
231
+
232
+    /**
233
+     * Slugify the value of a given attribute
234
+     * Warning: This doesn't result in a unique value
235
+     * @param string $attributeName the name of the attribute, which value should be slugified
236
+     * @return string slugified value
237
+     * @since 7.0.0
238
+     */
239
+    public function slugify($attributeName){
240
+        // toSlug should only work for existing attributes
241
+        if(property_exists($this, $attributeName)){
242
+            $value = $this->$attributeName;
243
+            // replace everything except alphanumeric with a single '-'
244
+            $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
245
+            $value = strtolower($value);
246
+            // trim '-'
247
+            return trim($value, '-');
248
+        } else {
249
+            throw new \BadFunctionCallException($attributeName .
250
+                ' is not a valid attribute');
251
+        }
252
+    }
253 253
 
254 254
 }
Please login to merge, or discard this patch.
lib/public/Share/IProviderFactory.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,32 +33,32 @@
 block discarded – undo
33 33
  */
34 34
 interface IProviderFactory {
35 35
 
36
-	/**
37
-	 * IProviderFactory constructor.
38
-	 * @param IServerContainer $serverContainer
39
-	 * @since 9.0.0
40
-	 */
41
-	public function __construct(IServerContainer $serverContainer);
36
+    /**
37
+     * IProviderFactory constructor.
38
+     * @param IServerContainer $serverContainer
39
+     * @since 9.0.0
40
+     */
41
+    public function __construct(IServerContainer $serverContainer);
42 42
 
43
-	/**
44
-	 * @param string $id
45
-	 * @return IShareProvider
46
-	 * @throws ProviderException
47
-	 * @since 9.0.0
48
-	 */
49
-	public function getProvider($id);
43
+    /**
44
+     * @param string $id
45
+     * @return IShareProvider
46
+     * @throws ProviderException
47
+     * @since 9.0.0
48
+     */
49
+    public function getProvider($id);
50 50
 
51
-	/**
52
-	 * @param int $shareType
53
-	 * @return IShareProvider
54
-	 * @throws ProviderException
55
-	 * @since 9.0.0
56
-	 */
57
-	public function getProviderForType($shareType);
51
+    /**
52
+     * @param int $shareType
53
+     * @return IShareProvider
54
+     * @throws ProviderException
55
+     * @since 9.0.0
56
+     */
57
+    public function getProviderForType($shareType);
58 58
 
59
-	/**
60
-	 * @return IShareProvider[]
61
-	 * @since 11.0.0
62
-	 */
63
-	public function getAllProviders();
59
+    /**
60
+     * @return IShareProvider[]
61
+     * @since 11.0.0
62
+     */
63
+    public function getAllProviders();
64 64
 }
Please login to merge, or discard this patch.
lib/public/Share/Exceptions/GenericShareException.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -31,18 +31,18 @@
 block discarded – undo
31 31
  */
32 32
 class GenericShareException extends HintException {
33 33
 
34
-	/**
35
-	 * @param string $message
36
-	 * @param string $hint
37
-	 * @param int $code
38
-	 * @param \Exception $previous
39
-	 * @since 9.0.0
40
-	 */
41
-	public function __construct($message = '', $hint = '', $code = 0, \Exception $previous = null) {
42
-		if (empty($message)) {
43
-			$message = 'Unspecified share exception';
44
-		}
45
-		parent::__construct($message, $hint, $code, $previous);
46
-	}
34
+    /**
35
+     * @param string $message
36
+     * @param string $hint
37
+     * @param int $code
38
+     * @param \Exception $previous
39
+     * @since 9.0.0
40
+     */
41
+    public function __construct($message = '', $hint = '', $code = 0, \Exception $previous = null) {
42
+        if (empty($message)) {
43
+            $message = 'Unspecified share exception';
44
+        }
45
+        parent::__construct($message, $hint, $code, $previous);
46
+    }
47 47
 
48 48
 }
Please login to merge, or discard this patch.
lib/public/SabrePluginEvent.php 1 patch
Indentation   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -33,65 +33,65 @@
 block discarded – undo
33 33
  */
34 34
 class SabrePluginEvent extends Event {
35 35
 
36
-	/** @var int */
37
-	protected $statusCode;
36
+    /** @var int */
37
+    protected $statusCode;
38 38
 
39
-	/** @var string */
40
-	protected $message;
39
+    /** @var string */
40
+    protected $message;
41 41
 
42
-	/** @var Server */
43
-	protected $server;
42
+    /** @var Server */
43
+    protected $server;
44 44
 
45
-	/**
46
-	 * @since 8.2.0
47
-	 */
48
-	public function __construct($server = null) {
49
-		$this->message = '';
50
-		$this->statusCode = Http::STATUS_OK;
51
-		$this->server = $server;
52
-	}
45
+    /**
46
+     * @since 8.2.0
47
+     */
48
+    public function __construct($server = null) {
49
+        $this->message = '';
50
+        $this->statusCode = Http::STATUS_OK;
51
+        $this->server = $server;
52
+    }
53 53
 
54
-	/**
55
-	 * @param int $statusCode
56
-	 * @return self
57
-	 * @since 8.2.0
58
-	 */
59
-	public function setStatusCode($statusCode) {
60
-		$this->statusCode = (int) $statusCode;
61
-		return $this;
62
-	}
54
+    /**
55
+     * @param int $statusCode
56
+     * @return self
57
+     * @since 8.2.0
58
+     */
59
+    public function setStatusCode($statusCode) {
60
+        $this->statusCode = (int) $statusCode;
61
+        return $this;
62
+    }
63 63
 
64
-	/**
65
-	 * @param string $message
66
-	 * @return self
67
-	 * @since 8.2.0
68
-	 */
69
-	public function setMessage($message) {
70
-		$this->message = (string) $message;
71
-		return $this;
72
-	}
64
+    /**
65
+     * @param string $message
66
+     * @return self
67
+     * @since 8.2.0
68
+     */
69
+    public function setMessage($message) {
70
+        $this->message = (string) $message;
71
+        return $this;
72
+    }
73 73
 
74
-	/**
75
-	 * @return int
76
-	 * @since 8.2.0
77
-	 */
78
-	public function getStatusCode() {
79
-		return $this->statusCode;
80
-	}
74
+    /**
75
+     * @return int
76
+     * @since 8.2.0
77
+     */
78
+    public function getStatusCode() {
79
+        return $this->statusCode;
80
+    }
81 81
 
82
-	/**
83
-	 * @return string
84
-	 * @since 8.2.0
85
-	 */
86
-	public function getMessage() {
87
-		return $this->message;
88
-	}
82
+    /**
83
+     * @return string
84
+     * @since 8.2.0
85
+     */
86
+    public function getMessage() {
87
+        return $this->message;
88
+    }
89 89
 
90
-	/**
91
-	 * @return null|Server
92
-	 * @since 9.0.0
93
-	 */
94
-	public function getServer() {
95
-		return $this->server;
96
-	}
90
+    /**
91
+     * @return null|Server
92
+     * @since 9.0.0
93
+     */
94
+    public function getServer() {
95
+        return $this->server;
96
+    }
97 97
 }
Please login to merge, or discard this patch.