From f19df13840950a6df7b2dcbfb709e70ae3041a1c Mon Sep 17 00:00:00 2001 From: Giovanni Ramos Date: Mon, 7 Oct 2013 16:13:52 -0400 Subject: [PATCH] Refactory full --- .gitignore | 2 +- .htaccess | 5 ++ .travis.yml | 6 +- README-pt.md | 5 +- README.md | 5 +- bootstrap.php | 23 ------- composer.json | 7 +- demos/DemoCRUD.php | 84 +++++++++++------------ demos/demo4.php | 3 + index.php | 4 +- install.sh | 2 +- src/PDO4You/PDO4You.php | 85 ++++++++++++++--------- src/bootstrap.php | 28 ++++++++ tests/PDO4You/PDO4YouTest.php | 119 +++++++++++++++++++++++++++++++++ tests/phpunit-codecoverage.xml | 39 +++++++++++ tests/phpunit.xml | 33 +++++++++ 16 files changed, 339 insertions(+), 111 deletions(-) create mode 100644 .htaccess delete mode 100644 bootstrap.php create mode 100644 src/bootstrap.php create mode 100644 tests/PDO4You/PDO4YouTest.php create mode 100644 tests/phpunit-codecoverage.xml create mode 100644 tests/phpunit.xml diff --git a/.gitignore b/.gitignore index c87de2f..ed79d67 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ composer.lock composer.phar -/vendor +/vendor \ No newline at end of file diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..92786d7 --- /dev/null +++ b/.htaccess @@ -0,0 +1,5 @@ +# Blocking access to confidential files + + Order Allow,Deny + Deny from all + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 352638a..6d0d594 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,10 @@ language: php - php: - 5.3 - 5.4 - - 5.5 before_script: - curl -s http://getcomposer.org/installer | php - - php composer.phar install --prefer-source --no-interaction --dev + - php composer.phar install --dev -script: phpunit \ No newline at end of file +script: "phpunit --colors --coverage-text" \ No newline at end of file diff --git a/README-pt.md b/README-pt.md index 31e7b51..2deb46d 100644 --- a/README-pt.md +++ b/README-pt.md @@ -325,7 +325,7 @@ Os drivers suportados serão exibidos na tela. ~~~ @@ -357,7 +357,8 @@ MS SQL Server (Versão antiga): http://bit.ly/PDO_MSSQL-PHP53 Dependências -------------------------------------------------- -PHP >= 5.3.2 +PHP >= 5.3.2
+PHPUnit >= 3.7.0 (necessário para executar o conjunto de testes) diff --git a/README.md b/README.md index ce1e6f8..d036479 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,7 @@ Supported drivers will be displayed on the screen. ~~~ @@ -357,7 +357,8 @@ MS SQL Server (Old version): http://bit.ly/PDO_MSSQL-PHP53 Dependencies -------------------------------------------------- -PHP >= 5.3.2 +PHP >= 5.3.2
+PHPUnit >= 3.7.0 (needed to run the test suite) diff --git a/bootstrap.php b/bootstrap.php deleted file mode 100644 index 33fbd20..0000000 --- a/bootstrap.php +++ /dev/null @@ -1,23 +0,0 @@ -AUTOLOADER NOT FOUND'; - echo '

To continue the installation, click INSTALL and wait, or run install.sh from the command line.

'; - exit; - } else { - $output = shell_exec(INSTALL); - exit("
{$output}
"); - } - } -} \ No newline at end of file diff --git a/composer.json b/composer.json index 8a01f41..2ccd839 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "type": "library", "description": "Access SQL databases using the PDO extension", "keywords": ["database", "singleton", "pdo", "mysql", "postgresql", "sqlite", "mariadb", "oracle"], - "homepage": "https://github.com/giovanniramos/PDO4You", + "homepage": "https://github.com/giovanniramos", "license": "MIT", "authors": [ { @@ -19,9 +19,12 @@ "require": { "php": ">=5.3.0" }, + "require-dev": { + "phpunit/phpunit": "3.7.*" + }, "autoload": { "psr-0": { - "PDO4You": "src" + "PDO4You\\": "src/" } } } \ No newline at end of file diff --git a/demos/DemoCRUD.php b/demos/DemoCRUD.php index 2b3250c..6cb7d58 100644 --- a/demos/DemoCRUD.php +++ b/demos/DemoCRUD.php @@ -50,7 +50,7 @@ public function select($instance = null) // Execute the SQL query in a "pre-defined instance" and store the result $result = PDO4You::select($sql, $instance); - echo '
Demo with the method - PDO4You::select()
'; + echo '
Demo with the method PDO4You::select()
'; echo '
PDO4You::select(' . $this->getQuery($sql) . '); ' . $this->getResult($result) . '
'; } @@ -63,23 +63,23 @@ public function allSelects() // SQL query $sql = self::sql(); - // Execute the SQL query in a instance and store the result - $result_1 = PDO4You::select($sql); - $result_2 = PDO4You::selectNum($sql); - $result_3 = PDO4You::selectObj($sql); - $result_4 = PDO4You::selectAll($sql); + // Executes the SQL and stores the result + $result = PDO4You::select($sql); + $result_num = PDO4You::selectNum($sql); + $result_obj = PDO4You::selectObj($sql); + $result_all = PDO4You::selectAll($sql); - echo '
Demo with the method - PDO4You::select()
'; - echo '
PDO4You::select(' . $this->getQuery($sql) . '); ' . $this->getResult($result_1) . '
'; + echo '
Demo with the method PDO4You::select()
'; + echo '
PDO4You::select(' . $this->getQuery($sql) . '); ' . $this->getResult($result) . '
'; - echo '
Demo with the method - PDO4You::selectNum()
'; - echo '
PDO4You::selectNum(' . $this->getQuery($sql) . '); ' . $this->getResult($result_2) . '
'; + echo '
Demo with the method PDO4You::selectNum()
'; + echo '
PDO4You::selectNum(' . $this->getQuery($sql) . '); ' . $this->getResult($result_num) . '
'; - echo '
Demo with the method - PDO4You::selectObj()
'; - echo '
PDO4You::selectObj(' . $this->getQuery($sql) . '); ' . $this->getResult($result_3) . '
'; + echo '
Demo with the method PDO4You::selectObj()
'; + echo '
PDO4You::selectObj(' . $this->getQuery($sql) . '); ' . $this->getResult($result_obj) . '
'; - echo '
Demo with the method - PDO4You::selectAll()
'; - echo '
PDO4You::selectAll(' . $this->getQuery($sql) . '); ' . $this->getResult($result_4) . '
'; + echo '
Demo with the method PDO4You::selectAll()
'; + echo '
PDO4You::selectAll(' . $this->getQuery($sql) . '); ' . $this->getResult($result_all) . '
'; } /** @@ -88,23 +88,23 @@ public function allSelects() * */ public function multipleInsert() { - // SQL insertion in JSON format + // SQL Insert in JSON format $json = ' insert: [ { table: "users" , - values: { firstname: "' . $this->genFakeName() . '", lastname: "' . $this->genFakeName() . '" } + values: { firstname: "' . $this->fakeName(true) . '", lastname: "' . $this->fakeName(true) . '" } },{ table: "users" , - values: { firstname: "' . $this->genFakeName() . '", lastname: "' . $this->genFakeName() . '" } + values: { firstname: "' . $this->fakeName(true) . '", lastname: "' . $this->fakeName(true) . '" } } ] '; - // Store the result + // Executes the SQL and stores the result $result = PDO4You::execute($json); - echo '
Demo with the method - PDO4You::execute() using the INSERT command
'; + echo '
Demo with Insert command
'; echo '
PDO4You::execute(' . $this->getQuery($json) . '); ' . $this->getResult($result, true) . '
'; } @@ -114,33 +114,33 @@ public function multipleInsert() * */ public function multipleUpdate() { - // SQL update in JSON format + // SQL Update in JSON format $json = ' update: [ { table: "users" , - values: { mail: "' . strtolower($this->genFakeName()) . '@gmail.com" } , + values: { mail: "' . $this->fakeName() . '@gmail.com" } , where: { id: 2 } },{ table: "users" , - values: { mail: "' . strtolower($this->genFakeName()) . '@gmail.com" } , + values: { mail: "' . $this->fakeName() . '@gmail.com" } , where: { id: 12 } },{ table: "users" , - values: { mail: "' . strtolower($this->genFakeName()) . '@gmail.com" } , + values: { mail: "' . $this->fakeName() . '@gmail.com" } , where: { id: 30 } },{ table: "users" , - values: { mail: "' . strtolower($this->genFakeName()) . '@gmail.com" } , + values: { mail: "' . $this->fakeName() . '@gmail.com" } , where: { id: 1 } } ] '; - // Store the result + // Executes the SQL and stores the result $result = PDO4You::execute($json); - echo '
Demo with the method - PDO4You::execute() using the UPDATE command
'; + echo '
Demo with Update command
'; echo '
PDO4You::execute(' . $this->getQuery($json) . '); ' . $this->getResult($result) . '
'; } @@ -150,7 +150,7 @@ public function multipleUpdate() * */ public function multipleDelete() { - // SQL delete in JSON format + // SQL Delete in JSON format $json = ' delete: [ { @@ -169,10 +169,10 @@ public function multipleDelete() ] '; - // Store the result + // Executes the SQL and stores the result $result = PDO4You::execute($json); - echo '
Demo with the method - PDO4You::execute() using the DELETE command
'; + echo '
Demo with Delete command
'; echo '
PDO4You::execute(' . $this->getQuery($json) . '); ' . $this->getResult($result) . '
'; } @@ -180,12 +180,12 @@ public function multipleDelete() * Update Where * * */ - public function updateWhere($s, $i) + public function updateWhere($desc, $id) { // SQL update in JSON format - $json = ' query: [ { table: "books" , values: { description: "' . $s . '" } , where: { id: ' . $i . ' } } ] '; + $json = ' query: [ { table: "books" , values: { description: "' . $desc . '" } , where: { id: ' . $id . ' } } ] '; - // Store the result + // Executes the SQL and stores the result $result = PDO4You::update($json); echo '
Demo with the old method PDO4You::update()
'; @@ -198,10 +198,10 @@ public function updateWhere($s, $i) */ private function getQuery($sql) { - $x = '' . htmlspecialchars($sql) . ''; - $y = '' . PDO4You::getConnection() . ''; + $sql = '' . htmlspecialchars($sql) . ''; + $conn = '' . PDO4You::getConnection() . ''; - return '"' . $x . '", "' . $y . '"'; + return '"' . $sql . '", "' . $conn . '"'; } /** @@ -210,11 +210,11 @@ private function getQuery($sql) */ private function getResult($result, $show_lastid = false) { - $s = '

- The code above will output:
' . print_r($this->sanitize($result), true) . '
'; - $s.= 'Total records affected: ' . PDO4You::rowCount() . ''; - $s.= ($show_lastid) ? '   Id of the last iteration: ' . PDO4You::lastId() . '' : null; + $result = '

- The code above will output:
' . print_r($this->sanitize($result), true) . '
'; + $result.= 'Total records affected: ' . PDO4You::rowCount() . ''; + $result.= ($show_lastid) ? '   Id of the last iteration: ' . PDO4You::lastId() . '' : null; - return $s; + return $result; } /** @@ -242,12 +242,14 @@ private function sanitize($data) * Random name generator * * */ - private function genFakeName() + private function fakeName($ucfirst = false) { $v = array("a", "e", "i", "o", "u"); $c = array("b", "c", "d", "f", "g", "h", "j", "l", "m", "n", "p", "q", "r", "s", "t", "v", "x", "z"); - return ucfirst($c[array_rand($c, 1)] . $v[array_rand($v, 1)] . $c[array_rand($c, 1)] . $v[array_rand($v, 1)] . $v[array_rand($v, 1)]); + $fakename = $c[array_rand($c, 1)] . $v[array_rand($v, 1)] . $c[array_rand($c, 1)] . $v[array_rand($v, 1)] . $v[array_rand($v, 1)]; + + return ($ucfirst) ? ucfirst($fakename) : $fakename; } } \ No newline at end of file diff --git a/demos/demo4.php b/demos/demo4.php index 00a14e4..0bdc3bf 100644 --- a/demos/demo4.php +++ b/demos/demo4.php @@ -11,5 +11,8 @@ // Sample text $sample_text = '

Lorem ipsum "dolor" sit amet

'; +// Escape double quotes +$sample_text = addslashes($sample_text); + // UPDATE books SET description = ? WHERE id = 1 $demo->updateWhere($sample_text, 1); \ No newline at end of file diff --git a/index.php b/index.php index 8fd8b03..cd70978 100644 --- a/index.php +++ b/index.php @@ -1,6 +1,6 @@ diff --git a/install.sh b/install.sh index 4234df1..15db899 100644 --- a/install.sh +++ b/install.sh @@ -1,6 +1,6 @@ #!/bin/sh if [ ! -f "composer.phar" ]; then - curl -s "https://getcomposer.org/installer" | php + curl -sS https://getcomposer.org/installer | php fi php composer.phar install --dev echo "" diff --git a/src/PDO4You/PDO4You.php b/src/PDO4You/PDO4You.php index 0bfe2db..e193b92 100644 --- a/src/PDO4You/PDO4You.php +++ b/src/PDO4You/PDO4You.php @@ -486,7 +486,7 @@ public static function getDriver() * @return void * * */ - public static function getServerInfo() + public static function showServerInfo() { try { if (self::$instance instanceof PDO) { @@ -510,7 +510,7 @@ public static function getServerInfo() * @return void * * */ - public static function getAvailableDrivers() + public static function showAvailableDrivers() { try { if (self::$instance instanceof PDO) { @@ -570,16 +570,20 @@ public static function stackTrace(PDOException $e, $show = true) $jarr['info']['stack'][$i] = '#' . $i++ . ' ' . basename($t['file']) . ':' . $t['line']; } - $json = json_encode($jarr, true); + $json_stack = json_encode($jarr, true); - exit($json); + exit($json_stack); } else { - self::css(); + if (defined('PHPUnit_MAIN_METHOD')) { + return; + } - if (!static::PDO4YOU_FIREDEBUG) { + if (static::PDO4YOU_FIREDEBUG == FALSE) { return; } + self::css(); + if (defined(static::PDO4YOU_WEBMASTER)) { self::fireAlert(self::$exception['critical-error'], $e); } @@ -652,6 +656,7 @@ private static function selectRecords($query, $type, $use, $count = true) self::setInstance($use); } + $result = null; $pdo = self::$instance; if (!$pdo instanceof PDO) { throw new PDOException(self::$exception['no-instance']); @@ -668,7 +673,11 @@ private static function selectRecords($query, $type, $use, $count = true) } $pre = $pdo->prepare($query); - $pre->execute(); + if (!is_object($pre)) { + return; + } else { + $pre->execute(); + } switch ($type) { case 'num': $result = $pre->fetchAll(PDO::FETCH_NUM); @@ -883,10 +892,13 @@ private static function executeQuery($json, $type, $use) * */ public static function execute($json, $use = null) { - preg_match('~([[:alnum:]]+)[\s\n\r\t]{0,}?:~', $json, $match); - $command = $match[1]; + // Finds a word that is at the beginning, in quotation marks or not + $match = null; + preg_match('~["]?([[:alnum:]]+)["]?[\s\n\r\t]{0,}?:~', $json, $match); try { + // Checks the word if found, is among the allowed commands for execution + $command = $match[1]; if (!in_array($command, array('insert', 'update', 'delete', 'query'))) { throw new PDOException(self::$exception['not-implemented'] . ' PDO4You::' . $command . '()'); } else { @@ -1005,19 +1017,30 @@ public static function rowCount() private static function parseJSON($json) { try { - preg_match('~([[:alnum:]]+)[\s\n\r\t]{0,}?:~', $json, $match); + // Format JSON + $json = '{' . $json . '}'; + + // Finds a word that is at the beginning, in quotation marks or not and replaces + $match = null; + preg_match('~["]?([[:alnum:]]+)["]?[\s\n\r\t]{0,}?:~', $json, $match); $command = $match[1]; if ($command != 'query') { $json = preg_replace('~' . $command . '~', 'query', $json, 1); } - - $json = '{ ' . $json . ' }'; + + // Converts the encoding $json = mb_detect_encoding($json, 'UTF-8', true) ? $json : utf8_encode($json); - $json = preg_replace('~[\s]{2,}~', ' ', $json); - $json = preg_replace('~[\n\r\t]~', '', $json); - $json = preg_replace('~(,?[{,])[\s]*([^"]+?)[\s]*:~', '$1"$2":', $json); - $json = preg_replace('~(<\/?)(\w+)([^>]*>)~e', "'$1$2$3'", $json); - $json = preg_replace('~(?= 0) { @@ -1168,29 +1191,27 @@ final private function __clone() } - public static function beginTransaction() + public static function exec($query) { try { if (!self::$instance instanceof PDO) { throw new PDOException(self::$exception['no-instance']); } - if (!self::$instance->beginTransaction()) { - throw new PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo())); - } + return self::$instance->exec($query); } catch (PDOException $e) { self::stackTrace($e); } } - public static function commit() + public static function query($query) { try { if (!self::$instance instanceof PDO) { throw new PDOException(self::$exception['no-instance']); } - if (!self::$instance->commit()) { + if (!self::$instance->query($query)) { throw new PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo())); } } catch (PDOException $e) { @@ -1198,31 +1219,29 @@ public static function commit() } } - public static function exec($query) + public static function lastInsertId($name) { try { if (!self::$instance instanceof PDO) { throw new PDOException(self::$exception['no-instance']); } - if (!self::$instance->exec($query)) { + if (!self::$instance->lastInsertId($name)) { throw new PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo())); - } else { - return self::$instance->exec($query); } } catch (PDOException $e) { self::stackTrace($e); } } - public static function query($query) + public static function beginTransaction() { try { if (!self::$instance instanceof PDO) { throw new PDOException(self::$exception['no-instance']); } - if (!self::$instance->query($query)) { + if (!self::$instance->beginTransaction()) { throw new PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo())); } } catch (PDOException $e) { @@ -1230,14 +1249,14 @@ public static function query($query) } } - public static function rollBack() + public static function commit() { try { if (!self::$instance instanceof PDO) { throw new PDOException(self::$exception['no-instance']); } - if (!self::$instance->rollBack()) { + if (!self::$instance->commit()) { throw new PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo())); } } catch (PDOException $e) { @@ -1245,14 +1264,14 @@ public static function rollBack() } } - public static function lastInsertId($name) + public static function rollBack() { try { if (!self::$instance instanceof PDO) { throw new PDOException(self::$exception['no-instance']); } - if (!self::$instance->lastInsertId($name)) { + if (!self::$instance->rollBack()) { throw new PDOException(current(self::$instance->errorInfo()) . ' ' . end(self::$instance->errorInfo())); } } catch (PDOException $e) { diff --git a/src/bootstrap.php b/src/bootstrap.php new file mode 100644 index 0000000..5f3cccd --- /dev/null +++ b/src/bootstrap.php @@ -0,0 +1,28 @@ +AUTOLOADER NOT FOUND'; + echo '

To continue the installation, click INSTALL and wait, or run install.sh from the command line.

'; + exit; + } else { + $output = shell_exec(INSTALL); + exit("
{$output}
"); + } + } else { + $loader = require_once DEFAULT_LOADER; + } +} diff --git a/tests/PDO4You/PDO4YouTest.php b/tests/PDO4You/PDO4YouTest.php new file mode 100644 index 0000000..9a4381c --- /dev/null +++ b/tests/PDO4You/PDO4YouTest.php @@ -0,0 +1,119 @@ +createDatabase(); + + // Creates a table in the database + $this->createTable(); + } + + public function createDatabase() + { + PDO4You::getInstance('test', 'sqlite::memory:'); + } + + public function createTable() + { + PDO4You::exec('CREATE TABLE users (id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT);'); + } + + public function testMultipleInsert() + { + // SQL Insert in JSON format + $json = ' + insert: [ + { table: "users" , values: { firstname: "John", lastname: "Lennon" } } , + { table: "users" , values: { firstname: "Paul", lastname: "McCartney" } } + ] + '; + + // Executes the SQL and stores the result + $result = PDO4You::execute($json); + + $this->assertEquals(2, self::getNumRowsAffected($result), 'Test with Insert command'); + } + + public function testMultipleUpdate() + { + // SQL Update in JSON format + $json = ' + update: [ + { table: "users" , values: { firstname: "John", lastname: "Doe" } , where: { id: 1 } } , + { table: "users" , values: { firstname: "Sparta", lastname: "" } , where: { id: 300 } } + ] + '; + + // Executes the SQL and stores the result + $result = PDO4You::execute($json); + + $this->assertEquals(1, self::getNumRowsAffected($result), 'Test with Update command'); + } + + public function testMultipleDelete() + { + // SQL Delete in JSON format + $json = ' + delete: [ + { table: "users" , where: { id: 1 } } , + { table: "users" , where: { id: 300 } } + ] + '; + + // Executes the SQL and stores the result + $result = PDO4You::execute($json); + + $this->assertEquals(1, self::getNumRowsAffected($result), 'Test with Delete command'); + } + + public function testAllSelects() + { + // SQL query + $sql = 'SELECT * FROM users'; + + // Executes the SQL and stores the result + $result = PDO4You::select($sql); + + $this->assertEquals(1, self::getNumRows($result)); + + // Executes the SQL and stores the result + $result_num = PDO4You::selectNum($sql); + + $this->assertEquals(1, self::getNumRows($result_num)); + + // Executes the SQL and stores the result + $result_obj = PDO4You::selectObj($sql); + + $this->assertEquals(1, self::getNumRows($result_obj)); + + // Executes the SQL and stores the result + $result_all = PDO4You::selectAll($sql); + + $this->assertEquals(1, self::getNumRows($result_all)); + } + + private function getNumRows($result) + { + return count($result); + } + + private function getNumRowsAffected($result) + { + return array_sum($result); + } + +} diff --git a/tests/phpunit-codecoverage.xml b/tests/phpunit-codecoverage.xml new file mode 100644 index 0000000..33e9735 --- /dev/null +++ b/tests/phpunit-codecoverage.xml @@ -0,0 +1,39 @@ + + + + + + ../tests/PDO4You/ + + + + + ../src/PDO4You/ + + ../src/bootstrap.php + ../src/PDO4You/PDO4You.config.php + ../src/PDO4You/PDO4You.settings.ini + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/phpunit.xml b/tests/phpunit.xml new file mode 100644 index 0000000..906d824 --- /dev/null +++ b/tests/phpunit.xml @@ -0,0 +1,33 @@ + + + + + + ../tests/PDO4You/ + + + + + ../src/PDO4You/ + + ../src/bootstrap.php + ../src/PDO4You/PDO4You.config.php + ../src/PDO4You/PDO4You.settings.ini + + + + + + +