]>
src.bluestatic.org Git - isso.git/blob - Api.php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 Blue Static
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.
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
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 \*=====================================================================*/
23 * Abstract Datamanger API (api.php)
28 if (!defined('REQ_AUTO'))
41 * Auto-increasing value
43 define('REQ_AUTO', -1);
46 * Set by a cusotm set_*() function
51 * Index for cleaning type
56 * Index for requirement type
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
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) {}
75 * @copyright Copyright (c)2005 - 2008, Blue Static
82 * Fields: used for verification and sanitization
83 * NAME => array(TYPE, REQUIRED)
86 protected $fields = array();
89 * The table name the API maps objects for
92 protected $table = '___UNDEFINED___';
95 * The database table prefix
98 protected $prefix = '';
101 * Values array: sanitized and validated field values
104 public $values = array();
107 * Fields that were set by the client
110 private $setfields = array();
116 protected $condition = '';
119 * The object table row; a fetched row that represents this instance
122 public $record = array();
125 * Insert ID from the insert() command
128 public $insertid = 0;
131 * Error queue that builds up errors
134 private $exception = null;
136 // ###################################################################
138 * Constructor: cannot instantiate class directly
140 public function __construct()
142 BSApp
::required_modules(array('Db', 'Input'));
145 // ###################################################################
147 * Adds an error into the error queue that is then hit
149 * @param Exception Error message
151 protected function _error(Exception
$e)
153 if ($this->exception
== null)
155 $this->exception
= new ApiException();
157 $this->exception
->addException($e);
160 // ###################################################################
162 * This simply throws the ApiException if it exists, which inside holds
163 * all of the individual and specific errors
165 private function _processErrorQueue()
167 if ($this->exception
)
169 throw $this->exception
;
173 // ###################################################################
175 * Sets a value, sanitizes it, and validates it
177 * @param string Field name
179 * @param bool Do clean?
180 * @param bool Do validation?
182 public function set($field, $value, $doclean = true, $dovalidate = true)
184 if (!isset($this->fields
["$field"]))
186 throw new Exception('Field "' . $field . '" is not valid');
189 $this->values["$field"] = ($doclean ? BSApp
::registry()->getType('Input')->clean($value, $this->fields
["$field"][F_TYPE]) : $value);
191 $this->setfields["$field"] = $field;
193 if ($dovalidate AND method_exists($this, "validate_$field"))
195 $this->{"validate_$field"}($field);
199 // ###################################################################
201 * Sets the condition to use in the WHERE clause; if not passed, then
202 * it calculates it from the REQ_AUTO field
204 * @param mixed String with WHERE condition; array of fields to use for WHERE builder
206 public function setCondition($condition = null)
208 if (is_array($condition) AND sizeof($condition) > 0)
210 $this->condition = '';
212 foreach ($condition AS $field)
214 if (!$this->values["$field"])
216 throw new Exception('The specified field "' . $field . '" for the condition could not be found as it is not set');
219 $condbits[] = "$field = " . $this->_prepareFieldForSql($field);
221 $this->condition
= implode(' AND ', $condbits);
225 $this->condition
= $condition;
229 foreach ($this->fields
AS $name => $options)
231 if ($options[F_REQ
] == REQ_AUTO
)
233 if (!$this->values
["$name"])
235 throw new Exception('Cannot determine condition from the REQ_AUTO field because it is not set');
238 $this->condition = "$name = " . $this->_prepareFieldForSql($name);
242 if (!$this->condition)
244 throw new Exception('No REQ_AUTO fields are present and therefore the condition cannot be created');
249 // ###################################################################
251 * Fetches a record based on the condition
253 * @param bool Run pre_fetch()?
254 * @param bool Run post_fetch()?
256 * @return boolean Whether or not the row was successfully fetched
258 public function fetch($doPre = true, $doPost = true)
260 if (!$this->condition)
262 $this->setCondition();
265 // reset the error queue due to any validation errors caused by fetchable fields
266 $this->errors = null;
268 $this->_runActionMethod('pre_fetch', $doPre);
270 $result = BSApp::registry()->getType('Db')->queryFirst("SELECT
* FROM {$this
->prefix
}{$this
->table
} WHERE {$this
->condition
}");
276 $this->_runActionMethod('post_fetch', $doPost);
278 $this->record = $result;
283 // ###################################################################
285 * Inserts a record in the database
287 * @param bool Run pre_insert()?
288 * @param bool Run post_insert()?
290 public function insert($doPre = true, $doPost = true)
292 $this->_verifyRequired();
293 $this->_processErrorQueue();
295 $this->_runActionMethod('pre_insert', $doPre);
297 $fields = $values = array();
298 foreach ($this->setfields AS $field)
301 $values[] = $this->_prepareFieldForSql($field);
304 BSApp::registry()->getType('Db')->query("INSERT INTO {$this
->prefix
}{$this
->table
} (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")");
306 if (BSApp::registry()->getType('DbPostgreSql'))
308 foreach ($this->fields AS $field => $info)
310 if ($info[F_REQ] == REQ_AUTO)
317 $this->insertid = BSApp::registry()->getType('Db')->insertId($this->prefix . $this->table, $autofield);
321 $this->insertid = BSApp::registry()->getType('Db')->insertId();
324 $this->_runActionMethod('post_insert', $doPost);
327 // ###################################################################
329 * Updates a record in the database using the data in $vaues
331 * @param bool Run pre_update()?
332 * @param bool Run post_update()?
334 public function update($doPre = true, $doPost = true)
336 if (!$this->condition)
338 $this->setCondition();
341 $this->_processErrorQueue();
343 $this->_runActionMethod('pre_update', $doPre);
345 foreach ($this->setfields AS $field)
347 $updates[] = "$field = " . $this->_prepareFieldForSql($field);
349 $updates = implode(', ', $updates);
351 BSApp::registry()->getType('Db')->query("UPDATE {$this
->prefix
}{$this
->table
} SET
$updates WHERE {$this
->condition
}");
353 $this->_runActionMethod('post_update', $doPost);
356 // ###################################################################
360 * @param bool Run pre_remove()?
361 * @param bool Run post_remove()?
363 public function remove($doPre = true, $doPost = true)
365 if (!$this->condition)
367 $this->setCondition();
372 $this->_runActionMethod('pre_remove', $doPre);
374 BSApp::registry()->getType('Db')->query("DELETE FROM {$this
->prefix
}{$this
->table
} WHERE {$this
->condition
}");
376 $this->_runActionMethod('post_remove', $doPost);
379 // ###################################################################
381 * Verifies that all required fields are set
383 private function _verifyRequired()
385 foreach ($this->fields AS $name => $options)
387 if ($options[F_REQ] == REQ_YES)
389 if (!isset($this->values["$name"]))
391 $this->_error(new FieldException(sprintf(_('The required field "%1$s" was not set'), $name), $name));
394 else if ($options[F_REQ
] == REQ_SET
)
396 $this->{"set_$name"}();
401 // ###################################################################
403 * Runs a pre- or post-action method for database commands
405 * @param string Action to run
406 * @param bool Actually run it?
408 private function _runActionMethod($method, $doRun)
410 if (!$doRun OR !method_exists($this, $method))
418 // ###################################################################
420 * Prepares a value for use in a SQL query; it encases and escapes
421 * strings and string-like values
423 * @param string Field name
425 * @return string Prepared value entry
427 private function _prepareFieldForSql($name)
429 $type = $this->fields
["$name"][F_TYPE];
431 if ($type == TYPE_NONE OR $type == TYPE_STR OR $type == TYPE_STRUN)
433 return "'" . BSApp::registry()->getType('Db
')->escapeString($this->values["$name"]) . "'";
435 else if ($type == TYPE_BOOL)
437 return ($this->values["$name"] == true ? "'1'" : "'0'");
439 else if ($type == TYPE_BIN
)
441 return "'" . BSApp
::registry()->getType('Db')->escapeBinary($this->values
["$name"]) . "'";
445 return $this->values["$name"];
449 // ###################################################################
451 * Verify field: not a zero value
453 protected function _verifyIsNotZero($field)
455 if ($this->values[$field] == 0)
457 $this->_error(new FieldException(sprintf(_('The field
"%1$s" cannot be zero'), $field), $field));
464 // ###################################################################
466 * Verify field: not empty
468 protected function _verifyIsNotEmpty($field)
470 if (empty($this->values[$field]))
472 $this->_error(new FieldException(sprintf(_('The field "%
1$s" cannot be
empty'), $field), $field));
479 // ###################################################################
481 * Verify field: unique
483 protected function _verifyIsNotUnique($field)
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})"));
488 $this->_error(new FieldException(sprintf(_('The
"%1$s" field must contain a unique value'), $field), $field));
499 * This class is an exception container that can be used to store a series
500 * of exceptions that can be thrown as one
503 * @copyright Copyright (c)2005 - 2008, Blue Static
507 class ApiException extends Exception
510 * Array of exceptions
513 private $exceptions = array();
515 // ###################################################################
519 public function __construct()
521 parent::__construct(_('An error occurred while processing the API data.'));
524 // ###################################################################
526 * Adds an exception to the collection
528 * @param Exception $e
530 public function addException(Exception $e)
532 $this->exceptions[] = $e;
535 // ###################################################################
537 * Returns an array of all the exceptions in the collection
541 public function getExceptions()
543 return $this->exceptions;
550 * This exception represents a problem with an API field
553 * @copyright Copyright (c)2005 - 2008, Blue Static
558 class FieldException extends Exception
561 * The name of the erroring field
566 // ###################################################################
568 * Constructor: create a new exception
570 public function __construct($error, $field)
572 $this->field = $field;
573 parent::__construct($error);
576 // ###################################################################
578 * Returns the name of the field the exception is for
582 public function getField()