<?php

/*
* LastUpdate:   2020-03-14	
* Version:      1.0.1 (Nur Kommentar geändert.)
* Author:       Jörg Reinholz, fastix WebDesign & Consult Kassel, http://www.fastix.org 	
* Requirements: PHP > 7.0	
* Licence:      https://code.fastix.org/lizenz.php 	
* Non-Warranty: https://code.fastix.org/haftung.php
*/


class ftxPDO extends PDO {

	protected $arErrors = [];
	protected $errorTypes = [
		0,
		E_USER_NOTICE,
		E_USER_WARNING,
		E_USER_ERROR
	];

	function __construct ( $connectString, $errType = E_USER_ERROR ) {
		
		if ( ! in_array( $errType, $this-> errorTypes ) ) {
			trigger_error( '$errType  has to be ' . implode ( ' or ', $this ->errorTypes ), E_USER_ERROR );	
		}
				
		$connectString = trim( $connectString );
		
		if ( 0 === strpos( $connectString, 'sqlite:' ) ) {
			
			/*
			** Driver is mysqli. Check the file, the permissens & connect.
			*/	
			
			$filename = trim( substr ( $connectString, 7, strlen( $connectString ) ) );
			$dirname  = dirname( $filename );
			
			if ( '' == $dirname ) {
				$dirname = './';
			}
			
			if ( ! is_writable ( $dirname ) ) {
				$eMsg = 'The directory "' . $dirname . ' has to be writable.';
				$this -> arErrors[] = $eMsg;
			} 

			if ( ! is_file( $filename ) ) {
				$eMsg = 'the file "' . $filename . '" not exits.';
				$this -> arErrors[] = $eMsg;
			} else {
				if ( ! is_readable( $filename ) ) {
					$eMsg = 'the file "' . $filename . '" is not readable';
					$this -> arErrors[] = $eMsg;	
				}
				if ( ! is_writable( $filename ) ) {
					$eMsg = 'the file "' . $filename . '" is not writable';
					$this -> arErrors[] = $eMsg;
				}
			}
            
            if ( count( $this -> arErrors ) ) {
				if ( 0 != $errType ) {
					trigger_error( implode( ' and ', $this -> arErrors ) , $errType );
				}
			}
			
			try {
				parent::__construct( 'sqlite:' . $filename );
			} catch( PDOException $e ) {
				trigger_error( $e -> __toString(), E_USER_ERROR );
			}
			
        } else {
			/*
			** Driver is not mysqli. Connect at the normal way.
			*/
			try {
				parent::__construct( $connectString );
			} catch( PDOException $e ) {
				trigger_error( $e -> __toString(), E_USER_ERROR );
			}        			
		}
	}
}