Refactoring all the static functions to not use the upper camel-case nomenclature...
[isso.git] / Api.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 Blue Static
6 || #
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version 2 of the License.
10 || #
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 || # more details.
15 || #
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
21
22 /**
23 * Abstract Datamanger API (api.php)
24 *
25 * @package ISSO
26 */
27
28 if (!defined('REQ_AUTO'))
29 {
30 /**
31 * Yes, required
32 */
33 define('REQ_YES', 1);
34
35 /**
36 * No, not required
37 */
38 define('REQ_NO', 0);
39
40 /**
41 * Auto-increasing value
42 */
43 define('REQ_AUTO', -1);
44
45 /**
46 * Set by a cusotm set_*() function
47 */
48 define('REQ_SET', 2);
49
50 /**
51 * Index for cleaning type
52 */
53 define('F_TYPE', 0);
54
55 /**
56 * Index for requirement type
57 */
58 define('F_REQ', 1);
59 }
60
61 /**
62 * Abstract API
63 *
64 * Abstract class that is used as an API base for most common database interaction
65 * schemes. Creates a simple structure that holds data and can update, remove, and
66 * insert.
67 *
68 * Life-cycle of a new object:
69 * 1. $o = new SubApi();
70 * 2. $o->set('foo', 'abc');
71 * 3. $o->set('test', 45);
72 * 4. try { $o->insert(); <other actions that depend on the saved record> } catch (ApiException $e) {}
73 *
74 * @author Blue Static
75 * @copyright Copyright (c)2005 - 2008, Blue Static
76 * @package ISSO
77 *
78 */
79 abstract class BSApi
80 {
81 /**
82 * Fields: used for verification and sanitization
83 * NAME => array(TYPE, REQUIRED)
84 * @var array
85 */
86 protected $fields = array();
87
88 /**
89 * The table name the API maps objects for
90 * @var string
91 */
92 protected $table = '___UNDEFINED___';
93
94 /**
95 * The database table prefix
96 * @var string
97 */
98 protected $prefix = '';
99
100 /**
101 * Values array: sanitized and validated field values
102 * @var array
103 */
104 public $values = array();
105
106 /**
107 * Fields that were set by the client
108 * @var array
109 */
110 private $setfields = array();
111
112 /**
113 * WHERE condition
114 * @var string
115 */
116 protected $condition = '';
117
118 /**
119 * The object table row; a fetched row that represents this instance
120 * @var array
121 */
122 public $record = array();
123
124 /**
125 * Insert ID from the insert() command
126 * @var integer
127 */
128 public $insertid = 0;
129
130 /**
131 * Error queue that builds up errors
132 * @var ApiException
133 */
134 private $exception = null;
135
136 // ###################################################################
137 /**
138 * Constructor: cannot instantiate class directly
139 */
140 public function __construct()
141 {
142 BSApp::required_modules(array('Db', 'Input'));
143 }
144
145 // ###################################################################
146 /**
147 * Adds an error into the error queue that is then hit
148 *
149 * @param Exception Error message
150 */
151 protected function _error(Exception $e)
152 {
153 if ($this->exception == null)
154 {
155 $this->exception = new ApiException();
156 }
157 $this->exception->addException($e);
158 }
159
160 // ###################################################################
161 /**
162 * This simply throws the ApiException if it exists, which inside holds
163 * all of the individual and specific errors
164 */
165 private function _processErrorQueue()
166 {
167 if ($this->exception)
168 {
169 throw $this->exception;
170 }
171 }
172
173 // ###################################################################
174 /**
175 * Sets a value, sanitizes it, and validates it
176 *
177 * @param string Field name
178 * @param mixed Value
179 * @param bool Do clean?
180 * @param bool Do validation?
181 */
182 public function set($field, $value, $doclean = true, $dovalidate = true)
183 {
184 if (!isset($this->fields["$field"]))
185 {
186 throw new Exception('Field "' . $field . '" is not valid');
187 }
188
189 $this->values["$field"] = ($doclean ? BSApp::registry()->getType('Input')->clean($value, $this->fields["$field"][F_TYPE]) : $value);
190
191 $this->setfields["$field"] = $field;
192
193 if ($dovalidate AND method_exists($this, "validate_$field"))
194 {
195 $this->{"validate_$field"}($field);
196 }
197 }
198
199 // ###################################################################
200 /**
201 * Sets the condition to use in the WHERE clause; if not passed, then
202 * it calculates it from the REQ_AUTO field
203 *
204 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
205 */
206 public function setCondition($condition = null)
207 {
208 if (is_array($condition) AND sizeof($condition) > 0)
209 {
210 $this->condition = '';
211
212 foreach ($condition AS $field)
213 {
214 if (!$this->values["$field"])
215 {
216 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
217 }
218
219 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
220 }
221 $this->condition = implode(' AND ', $condbits);
222 }
223 else if ($condition)
224 {
225 $this->condition = $condition;
226 }
227 else
228 {
229 foreach ($this->fields AS $name => $options)
230 {
231 if ($options[F_REQ] == REQ_AUTO)
232 {
233 if (!$this->values["$name"])
234 {
235 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
236 }
237
238 $this->condition = "$name = " . $this->_prepareFieldForSql($name);
239 }
240 }
241
242 if (!$this->condition)
243 {
244 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
245 }
246 }
247 }
248
249 // ###################################################################
250 /**
251 * Fetches a record based on the condition
252 *
253 * @param bool Run pre_fetch()?
254 * @param bool Run post_fetch()?
255 *
256 * @return boolean Whether or not the row was successfully fetched
257 */
258 public function fetch($doPre = true, $doPost = true)
259 {
260 if (!$this->condition)
261 {
262 $this->setCondition();
263 }
264
265 // reset the error queue due to any validation errors caused by fetchable fields
266 $this->errors = null;
267
268 $this->_runActionMethod('pre_fetch', $doPre);
269
270 $result = BSApp::registry()->getType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
271 if (!$result)
272 {
273 return false;
274 }
275
276 $this->_runActionMethod('post_fetch', $doPost);
277
278 $this->record = $result;
279
280 return true;
281 }
282
283 // ###################################################################
284 /**
285 * Inserts a record in the database
286 *
287 * @param bool Run pre_insert()?
288 * @param bool Run post_insert()?
289 */
290 public function insert($doPre = true, $doPost = true)
291 {
292 $this->_verifyRequired();
293 $this->_processErrorQueue();
294
295 $this->_runActionMethod('pre_insert', $doPre);
296
297 $fields = $values = array();
298 foreach ($this->setfields AS $field)
299 {
300 $fields[] = $field;
301 $values[] = $this->_prepareFieldForSql($field);
302 }
303
304 BSApp::registry()->getType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
305
306 if (BSApp::registry()->getType('DbPostgreSql'))
307 {
308 foreach ($this->fields AS $field => $info)
309 {
310 if ($info[F_REQ] == REQ_AUTO)
311 {
312 $autofield = $field;
313 break;
314 }
315 }
316
317 $this->insertid = BSApp::registry()->getType('Db')->insertId($this->prefix . $this->table, $autofield);
318 }
319 else
320 {
321 $this->insertid = BSApp::registry()->getType('Db')->insertId();
322 }
323
324 $this->_runActionMethod('post_insert', $doPost);
325 }
326
327 // ###################################################################
328 /**
329 * Updates a record in the database using the data in $vaues
330 *
331 * @param bool Run pre_update()?
332 * @param bool Run post_update()?
333 */
334 public function update($doPre = true, $doPost = true)
335 {
336 if (!$this->condition)
337 {
338 $this->setCondition();
339 }
340
341 $this->_processErrorQueue();
342
343 $this->_runActionMethod('pre_update', $doPre);
344
345 foreach ($this->setfields AS $field)
346 {
347 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
348 }
349 $updates = implode(', ', $updates);
350
351 BSApp::registry()->getType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
352
353 $this->_runActionMethod('post_update', $doPost);
354 }
355
356 // ###################################################################
357 /**
358 * Deletes a record
359 *
360 * @param bool Run pre_remove()?
361 * @param bool Run post_remove()?
362 */
363 public function remove($doPre = true, $doPost = true)
364 {
365 if (!$this->condition)
366 {
367 $this->setCondition();
368 }
369
370 $this->fetch();
371
372 $this->_runActionMethod('pre_remove', $doPre);
373
374 BSApp::registry()->getType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
375
376 $this->_runActionMethod('post_remove', $doPost);
377 }
378
379 // ###################################################################
380 /**
381 * Verifies that all required fields are set
382 */
383 private function _verifyRequired()
384 {
385 foreach ($this->fields AS $name => $options)
386 {
387 if ($options[F_REQ] == REQ_YES)
388 {
389 if (!isset($this->values["$name"]))
390 {
391 $this->_error(new FieldException(sprintf(_('The required field "%1$s" was not set'), $name), $name));
392 }
393 }
394 else if ($options[F_REQ] == REQ_SET)
395 {
396 $this->{"set_$name"}();
397 }
398 }
399 }
400
401 // ###################################################################
402 /**
403 * Runs a pre- or post-action method for database commands
404 *
405 * @param string Action to run
406 * @param bool Actually run it?
407 */
408 private function _runActionMethod($method, $doRun)
409 {
410 if (!$doRun OR !method_exists($this, $method))
411 {
412 return;
413 }
414
415 $this->$method();
416 }
417
418 // ###################################################################
419 /**
420 * Prepares a value for use in a SQL query; it encases and escapes
421 * strings and string-like values
422 *
423 * @param string Field name
424 *
425 * @return string Prepared value entry
426 */
427 private function _prepareFieldForSql($name)
428 {
429 $type = $this->fields["$name"][F_TYPE];
430
431 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
432 {
433 return "'" . BSApp::registry()->getType('Db')->escapeString($this->values["$name"]) . "'";
434 }
435 else if ($type == TYPE_BOOL)
436 {
437 return ($this->values["$name"] == true ? "'1'" : "'0'");
438 }
439 else if ($type == TYPE_BIN)
440 {
441 return "'" . BSApp::registry()->getType('Db')->escapeBinary($this->values["$name"]) . "'";
442 }
443 else
444 {
445 return $this->values["$name"];
446 }
447 }
448
449 // ###################################################################
450 /**
451 * Verify field: not a zero value
452 */
453 protected function _verifyIsNotZero($field)
454 {
455 if ($this->values[$field] == 0)
456 {
457 $this->_error(new FieldException(sprintf(_('The field "%1$s" cannot be zero'), $field), $field));
458 return false;
459 }
460
461 return true;
462 }
463
464 // ###################################################################
465 /**
466 * Verify field: not empty
467 */
468 protected function _verifyIsNotEmpty($field)
469 {
470 if (empty($this->values[$field]))
471 {
472 $this->_error(new FieldException(sprintf(_('The field "%1$s" cannot be empty'), $field), $field));
473 return false;
474 }
475
476 return true;
477 }
478
479 // ###################################################################
480 /**
481 * Verify field: unique
482 */
483 protected function _verifyIsNotUnique($field)
484 {
485 $res = BSApp::registry()->getType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
486 if ($res)
487 {
488 $this->_error(new FieldException(sprintf(_('The "%1$s" field must contain a unique value'), $field), $field));
489 return false;
490 }
491
492 return true;
493 }
494 }
495
496 /**
497 * API Exception
498 *
499 * This class is an exception container that can be used to store a series
500 * of exceptions that can be thrown as one
501 *
502 * @author rsesek
503 * @copyright Copyright (c)2005 - 2008, Blue Static
504 * @package ISSO
505 *
506 */
507 class ApiException extends Exception
508 {
509 /**
510 * Array of exceptions
511 * @var array
512 */
513 private $exceptions = array();
514
515 // ###################################################################
516 /**
517 * Constructor
518 */
519 public function __construct()
520 {
521 parent::__construct(_('An error occurred while processing the API data.'));
522 }
523
524 // ###################################################################
525 /**
526 * Adds an exception to the collection
527 *
528 * @param Exception $e
529 */
530 public function addException(Exception $e)
531 {
532 $this->exceptions[] = $e;
533 }
534
535 // ###################################################################
536 /**
537 * Returns an array of all the exceptions in the collection
538 *
539 * @return array
540 */
541 public function getExceptions()
542 {
543 return $this->exceptions;
544 }
545 }
546
547 /**
548 * Field Exception
549 *
550 * This exception represents a problem with an API field
551 *
552 * @author rsesek
553 * @copyright Copyright (c)2005 - 2008, Blue Static
554 * @version $Id$
555 * @package ISSO
556 *
557 */
558 class FieldException extends Exception
559 {
560 /**
561 * The name of the erroring field
562 * @var string
563 */
564 private $field;
565
566 // ###################################################################
567 /**
568 * Constructor: create a new exception
569 */
570 public function __construct($error, $field)
571 {
572 $this->field = $field;
573 parent::__construct($error);
574 }
575
576 // ###################################################################
577 /**
578 * Returns the name of the field the exception is for
579 *
580 * @return string
581 */
582 public function getField()
583 {
584 return $this->field;
585 }
586 }
587
588 ?>