When the API needs to throw an exception regarding a field, use a new FieldException...
[isso.git] / Api.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2002-2007 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 * Index for verification type
62 */
63 define('F_VERIFY', 2);
64 }
65
66 /**
67 * Abstract API
68 *
69 * Abstract class that is used as an API base for most common database interaction
70 * schemes. Creates a simple structure that holds data and can update, remove, and
71 * insert.
72 *
73 * @author Blue Static
74 * @copyright Copyright (c)2002 - 2007, Blue Static
75 * @package ISSO
76 *
77 */
78 abstract class BSApi
79 {
80 /**
81 * Fields: used for verification and sanitization
82 * NAME => array(TYPE, REQUIRED, VERIFY METHOD (:self for self-named method), RELATION => array(FILE, CLASS IN FILE, ALTERNATE FIELD NAME))
83 * @var array
84 */
85 protected $fields = array();
86
87 /**
88 * The table name the API maps objects for
89 * @var string
90 */
91 protected $table = '___UNDEFINED___';
92
93 /**
94 * The database table prefix
95 * @var string
96 */
97 protected $prefix = '';
98
99 /**
100 * Values array: sanitized and verified field values
101 * @var array
102 */
103 public $values = array();
104
105 /**
106 * Fields that were set by the client
107 * @var array
108 */
109 private $setfields = array();
110
111 /**
112 * WHERE condition
113 * @var string
114 */
115 private $condition = '';
116
117 /**
118 * The object table row; a fetched row that represents this instance
119 * @var array
120 */
121 public $objdata = array();
122
123 /**
124 * Insert ID from the insert() command
125 * @var integer
126 */
127 public $insertid = 0;
128
129 /**
130 * Error queue that builds up errors
131 * @var ApiException
132 */
133 private $exception = null;
134
135 // ###################################################################
136 /**
137 * Constructor: cannot instantiate class directly
138 */
139 public function __construct()
140 {
141 BSApp::RequiredModules(array('Db', 'Input'));
142 }
143
144 // ###################################################################
145 /**
146 * Adds an error into the error queue that is then hit
147 *
148 * @param Exception Error message
149 */
150 protected function _error(Exception $e)
151 {
152 if ($this->exception == null)
153 {
154 $this->exception = new ApiException();
155 }
156 $this->exception->addException($e);
157 }
158
159 // ###################################################################
160 /**
161 * This simply throws the ApiException if it exists, which inside holds
162 * all of the individual and specific errors
163 */
164 private function _processErrorQueue()
165 {
166 if ($this->exception)
167 {
168 throw $this->exception;
169 }
170 }
171
172 // ###################################################################
173 /**
174 * Returns the list of exceptions contained in the ApiException
175 *
176 * @return array Array of errors
177 */
178 public function isValid()
179 {
180 if ($this->exception == null)
181 {
182 return array();
183 }
184
185 return $this->exception->getExceptions();
186 }
187
188 // ###################################################################
189 /**
190 * Sets a value, sanitizes it, and verifies it
191 *
192 * @param string Field name
193 * @param mixed Value
194 * @param bool Do clean?
195 * @param bool Do verify?
196 */
197 public function set($field, $value, $doclean = true, $doverify = true)
198 {
199 if (!isset($this->fields["$field"]))
200 {
201 throw new Exception('Field "' . $field . '" is not valid');
202 }
203
204 $this->values["$field"] = ($doclean ? BSApp::Registry()->getType('Input')->clean($value, $this->fields["$field"][F_TYPE]) : $value);
205
206 $this->setfields["$field"] = $field;
207
208 if (isset($this->fields["$field"][F_VERIFY]) AND $doverify)
209 {
210 if ($this->fields["$field"][F_VERIFY] == ':self')
211 {
212 $verify = $this->{"verify_$field"}($field);
213 }
214 else
215 {
216 $verify = $this->{$this->fields["$field"][F_VERIFY]}($field);
217 }
218
219 if ($verify !== true)
220 {
221 if ($verify === false)
222 {
223 $this->_error(new FieldException(sprintf(_('Validation of "%1$s" failed'), $field)));
224 }
225 else
226 {
227 $this->_error($verify);
228 }
229 }
230 }
231 }
232
233 // ###################################################################
234 /**
235 * Sets the condition to use in the WHERE clause; if not passed, then
236 * it calculates it from the REQ_AUTO field
237 *
238 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
239 */
240 public function setCondition($condition = '')
241 {
242 if (is_array($condition) AND sizeof($condition) > 0)
243 {
244 $this->condition = '';
245
246 foreach ($condition AS $field)
247 {
248 if (!$this->values["$field"])
249 {
250 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
251 }
252
253 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
254 }
255 $this->condition = implode(' AND ', $condbits);
256 }
257 else if ($condition != '')
258 {
259 $this->condition = $condition;
260 }
261 else
262 {
263 foreach ($this->fields AS $name => $options)
264 {
265 if ($options[F_REQ] == REQ_AUTO)
266 {
267 if (!$this->values["$name"])
268 {
269 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
270 }
271
272 $this->condition = "$name = " . $this->_prepareFieldForSql($name);
273 }
274 }
275
276 if ($this->condition == '')
277 {
278 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
279 }
280 }
281 }
282
283 // ###################################################################
284 /**
285 * Fetches a record based on the condition
286 *
287 * @param bool Run pre_fetch()?
288 * @param bool Run post_fetch()?
289 *
290 * @return boolean Whether or not the row was successfully fetched
291 */
292 public function fetch($doPre = true, $doPost = true)
293 {
294 if ($this->condition == '')
295 {
296 $this->setCondition();
297 }
298
299 // reset the error queue due to any validation errors caused by fetchable fields
300 $this->errors = null;
301
302 $this->_runActionMethod('pre_fetch', $doPre);
303
304 $result = BSApp::Registry()->getType('Db')->queryFirst("SELECT * FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
305 if (!$result)
306 {
307 return false;
308 }
309
310 $this->_runActionMethod('post_fetch', $doPost);
311
312 $this->objdata = $result;
313
314 return true;
315 }
316
317 // ###################################################################
318 /**
319 * Inserts a record in the database
320 *
321 * @param bool Run pre_insert()?
322 * @param bool Run post_insert()?
323 */
324 public function insert($doPre = true, $doPost = true)
325 {
326 $this->verify();
327 $this->_processErrorQueue();
328
329 $this->_runActionMethod('pre_insert', $doPre);
330
331 foreach ($this->setfields AS $field)
332 {
333 $fields[] = $field;
334 $values[] = $this->_prepareFieldForSql($field);
335 }
336
337 BSApp::Registry()->getType('Db')->query("INSERT INTO {$this->prefix}{$this->table} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
338
339 if (BSApp::Registry()->getType('DbPostgreSql'))
340 {
341 foreach ($this->fields AS $field => $info)
342 {
343 if ($info[F_REQ] == REQ_AUTO)
344 {
345 $autofield = $field;
346 break;
347 }
348 }
349
350 $this->insertid = BSApp::Registry()->getType('Db')->insertId($this->prefix . $this->table, $autofield);
351 }
352 else
353 {
354 $this->insertid = BSApp::Registry()->getType('Db')->insertId();
355 }
356
357 $this->_runActionMethod('post_insert', $doPost);
358 }
359
360 // ###################################################################
361 /**
362 * Updates a record in the database using the data in $vaues
363 *
364 * @param bool Run pre_update()?
365 * @param bool Run post_update()?
366 */
367 public function update($doPre = true, $doPost = true)
368 {
369 if ($this->condition == '')
370 {
371 $this->setCondition();
372 }
373
374 $this->_processErrorQueue();
375
376 $this->_runActionMethod('pre_update', $doPre);
377
378 foreach ($this->setfields AS $field)
379 {
380 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
381 }
382 $updates = implode(', ', $updates);
383
384 BSApp::Registry()->getType('Db')->query("UPDATE {$this->prefix}{$this->table} SET $updates WHERE {$this->condition}");
385
386 $this->_runActionMethod('post_update', $doPost);
387 }
388
389 // ###################################################################
390 /**
391 * Deletes a record
392 *
393 * @param bool Run pre_remove()?
394 * @param bool Run post_remove()?
395 */
396 public function remove($doPre = true, $doPost = true)
397 {
398 if ($this->condition == '')
399 {
400 $this->setCondition();
401 }
402
403 $this->fetch();
404
405 $this->_runActionMethod('pre_remove', $doPre);
406
407 BSApp::Registry()->getType('Db')->query("DELETE FROM {$this->prefix}{$this->table} WHERE {$this->condition}");
408
409 $this->_runActionMethod('post_remove', $doPost);
410 }
411
412 // ###################################################################
413 /**
414 * Verifies that all required fields are set
415 */
416 private function verify()
417 {
418 foreach ($this->fields AS $name => $options)
419 {
420 if ($options[F_REQ] == REQ_YES)
421 {
422 if (!isset($this->values["$name"]))
423 {
424 $this->_error(new FieldException(sprintf(_('The required field "%1$s" was not set'), $name), $name));
425 }
426 }
427 else if ($options[F_REQ] == REQ_SET)
428 {
429 $this->{"set_$name"}();
430 }
431 }
432 }
433
434 // ###################################################################
435 /**
436 * Runs a pre- or post-action method for database commands
437 *
438 * @param string Action to run
439 * @param bool Actually run it?
440 */
441 private function _runActionMethod($method, $doRun)
442 {
443 if (!$doRun)
444 {
445 return;
446 }
447
448 $actmethod = (method_exists($this, $method) ? $this->$method() : '');
449 }
450
451 // ###################################################################
452 /**
453 * Prepares a value for use in a SQL query; it encases and escapes
454 * strings and string-like values
455 *
456 * @param string Field name
457 *
458 * @return string Prepared value entry
459 */
460 private function _prepareFieldForSql($name)
461 {
462 $type = $this->fields["$name"][F_TYPE];
463
464 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
465 {
466 return "'" . BSApp::Registry()->getType('Db')->escapeString($this->values["$name"]) . "'";
467 }
468 else if ($type == TYPE_BOOL)
469 {
470 return ($this->values["$name"] == true ? "'1'" : "'0'");
471 }
472 else if ($type == TYPE_BIN)
473 {
474 return "'" . BSApp::Registry()->getType('Db')->escapeBinary($this->values["$name"]) . "'";
475 }
476 else
477 {
478 return $this->values["$name"];
479 }
480 }
481
482 // ###################################################################
483 /**
484 * Verify field: not a zero value
485 */
486 protected function verify_nozero($field)
487 {
488 if ($this->values["$field"] == 0)
489 {
490 return new FieldException(sprintf(_('The field "%1$s" cannot be zero'), $field), $field);
491 }
492
493 return true;
494 }
495
496 // ###################################################################
497 /**
498 * Verify field: not empty
499 */
500 protected function verify_noempty($field)
501 {
502 if (empty($this->values["$field"]))
503 {
504 return new FieldException(sprintf(_('The field "%1$s" cannot be empty'), $field), $field);
505 }
506
507 return true;
508 }
509
510 // ###################################################################
511 /**
512 * Verify field: unique
513 */
514 protected function verify_unique($field)
515 {
516 $res = BSApp::Registry()->getType('Db')->queryFirst("SELECT $field FROM {$this->prefix}{$this->table} WHERE $field = " . $this->_prepareFieldForSql($field) . (empty($this->condition) ? "" : " AND !({$this->condition})"));
517 if ($res)
518 {
519 return new FieldException(sprintf(_('The "%1$s" field must contain a unique value'), $field), $field);
520 }
521
522 return true;
523 }
524 }
525
526 /**
527 * API Exception
528 *
529 * This class is an exception container that can be used to store a series
530 * of exceptions that can be thrown as one
531 *
532 * @author rsesek
533 * @copyright Copyright (c)2002 - 2007, Blue Static
534 * @package ISSO
535 *
536 */
537 class ApiException extends Exception
538 {
539 /**
540 * Array of exceptions
541 * @var array
542 */
543 private $exceptions = array();
544
545 // ###################################################################
546 /**
547 * Constructor
548 */
549 public function __construct()
550 {
551 parent::__construct(_('An error occurred while processing the API data.'));
552 }
553
554 // ###################################################################
555 /**
556 * Adds an exception to the collection
557 *
558 * @param Exception $e
559 */
560 public function addException(Exception $e)
561 {
562 $this->exceptions[] = $e;
563 }
564
565 // ###################################################################
566 /**
567 * Returns an array of all the exceptions in the collection
568 *
569 * @return array
570 */
571 public function getExceptions()
572 {
573 return $this->exceptions;
574 }
575 }
576
577 /**
578 * Field Exception
579 *
580 * This exception represents a problem with an API field
581 *
582 * @author rsesek
583 * @copyright Copyright (c)2002 - 2007, Blue Static
584 * @version $Id$
585 * @package ISSO
586 *
587 */
588 class FieldException extends Exception
589 {
590 /**
591 * The name of the erroring field
592 * @var string
593 */
594 private $field;
595
596 // ###################################################################
597 /**
598 * Constructor: create a new exception
599 */
600 public function __construct($error, $field)
601 {
602 $this->field = $field;
603 parent::__construct($error);
604 }
605
606 // ###################################################################
607 /**
608 * Returns the name of the field the exception is for
609 *
610 * @return string
611 */
612 public function getField()
613 {
614 return $this->field;
615 }
616 }
617
618 ?>