Exemplo n.º 1
0
 /**
  * Creates and returns a PDO connection to a database.
  * If connection failed then error is logged to the log file or debug screen. Sensitive data will be removed.
  *
  * @example:
  *  <p>Raxan::connect($dsn,$uid,$pwd,$errMode) // enables exception error mode - set $errMode to true or set to PDO error mode constant</p>
  *  <p>Raxan::connect($dsn,$uid,$pwd,$attribs) // set attributes</p>
  * 
  * @param mixed $dsn Acceptts string or array
  * @param string $user Optional user name
  * @param string $password Optional password
  * @param mixed $attribs Optional PDO error mode or array of attributes. Set to TRUE to enable PDO error mode
  * @return RaxanPDO  False if connection failed
  */
 public static function connect($dsn, $user = null, $password = null, $attribs = null)
 {
     $dsn = is_string($dsn) && ($d = Raxan::config('db.' . $dsn)) ? $d : $dsn;
     if (!self::$isPDOLoaded) {
         self::$isPDOLoaded = true;
         include_once self::$config['base.path'] . 'shared/raxan.pdo.php';
     }
     if (is_array($dsn)) {
         // build pdo dsn
         $dsn = array_merge(array('user' => '', 'password' => '', 'attribs' => ''), $dsn);
         // set default keys
         $user = $user ? $user : $dsn['user'];
         $password = $password ? $password : $dsn['password'];
         $attribs = $attribs ? $attribs : ($dsn['attribs'] ? $dsn['attribs'] : null);
         $dsn = $dsn['dsn'];
     }
     // check for error mode
     if ($attribs === true) {
         $attribs = PDO::ERRMODE_EXCEPTION;
     }
     if ($attribs === PDO::ERRMODE_EXCEPTION || $attribs === PDO::ERRMODE_WARNING) {
         $attribs = array(PDO::ATTR_ERRMODE => $attribs);
     }
     $errmode = $attribs && is_array($attribs) && isset($attribs[PDO::ATTR_ERRMODE]) ? $attribs[PDO::ATTR_ERRMODE] : null;
     try {
         $args = array($dsn, $user, $password, $attribs);
         $rt = self::triggerSysEvent('data_connection', $args);
         if ($rt !== null) {
             return $rt;
         } else {
             $pdo = new RaxanPDO($dsn, $user, $password, $attribs);
         }
         return $pdo;
     } catch (PDOException $e) {
         $lbl = 'Raxan::connect';
         $msg = $e->getMessage();
         $msg = str_replace(array($dsn, $user, $password), '...', $msg);
         // remove sensitive data
         if ($errmode !== null) {
             throw new PDOException($msg, $e->getCode());
         } else {
             self::log($msg, 'error', $lbl) || self::debug($lbl . ' Error: ' . $msg);
             return false;
         }
     }
 }