Db\Connection::quote(), SQL debuging, code linted to new standard

This commit is contained in:
Juan 2018-05-23 11:08:11 +02:00
parent dc2d74847f
commit e458b72748
14 changed files with 326 additions and 372 deletions

View File

@ -4,14 +4,13 @@ namespace Vn\Db;
use Vn\Lib\Type;
class Connection
{
class Connection {
private $conn = NULL;
private $isOpen = FALSE;
var $enableDebug = FALSE;
function __construct ()
{
$this->initHandler ();
function __construct() {
$this->initHandler();
}
/**
@ -24,32 +23,28 @@ class Connection
*
* @return boolean %TRUE on success, %FALSE otherwise
*/
function open ($host, $user, $pass, $name, $port = NULL)
{
$conn = $this->initHandler ();
$conn->options (MYSQLI_OPT_LOCAL_INFILE, TRUE);
$conn->real_connect ($host, $user, $pass, $name, $port);
function open($host, $user, $pass, $name, $port = NULL) {
$conn = $this->initHandler();
$conn->options(MYSQLI_OPT_LOCAL_INFILE, TRUE);
$conn->real_connect($host, $user, $pass, $name, $port);
if (mysqli_connect_errno ())
{
sleep (3);
throw new Exception (mysqli_connect_errno (), mysqli_connect_error ());
if (mysqli_connect_errno()) {
sleep(3);
throw new Exception(mysqli_connect_errno(), mysqli_connect_error());
return FALSE;
}
$this->isOpen = TRUE;
$this->query ('SET CHARACTER SET utf8');
$this->query('SET CHARACTER SET utf8');
return TRUE;
}
/**
* Closes the current connection, if it's closed does nothing.
*/
function close ()
{
if ($this->isOpen)
{
$this->conn->close ();
function close() {
if ($this->isOpen) {
$this->conn->close();
$this->conn = NULL;
}
@ -61,10 +56,9 @@ class Connection
*
* @return Objetct The connection handler
*/
function initHandler ()
{
function initHandler() {
if (!$this->conn)
$this->conn = new \mysqli ();
$this->conn = new \mysqli();
return $this->conn;
}
@ -76,8 +70,7 @@ class Connection
*
* @return Objetct The connection handler
*/
function getHandler ()
{
function getHandler() {
return $this->conn;
}
@ -87,9 +80,8 @@ class Connection
* @param string $schema The schema name
* @return boolean %TRUE if success, %FALSE otherwise
*/
function selectDb ($dbName)
{
return $this->conn->select_db ($dbName);
function selectDb($dbName) {
return $this->conn->select_db($dbName);
}
/**
@ -100,15 +92,14 @@ class Connection
*
* @return mixed The value or %NULL if error
*/
function query ($query, $params = NULL)
{
$result = $this->conn->query ($this->render ($query, $params));
function query($query, $params = NULL) {
$result = $this->conn->query($this->renderDebug($query, $params));
if (!$result)
$this->checkError ();
$this->checkError();
else
while ($this->moreResults ())
$this->nextResult ();
while ($this->moreResults())
$this->nextResult();
return $result;
}
@ -118,8 +109,7 @@ class Connection
*
* @return boolean %TRUE if connection is open, %FALSE otherwise
*/
function isOpen ()
{
function isOpen() {
return $this->isOpen;
}
@ -130,12 +120,10 @@ class Connection
*
* @return mixed[] An associative array with the first row, %NULL if error
*/
function getRowFromResult ($result)
{
if ($result)
{
$row = $result->fetch_assoc ();
$result->free ();
function getRowFromResult($result) {
if ($result) {
$row = $result->fetch_assoc();
$result->free();
return $row;
}
@ -149,12 +137,10 @@ class Connection
*
* @return object An object with the first row, %NULL if error
*/
function getObjectFromResult ($result)
{
if ($result)
{
$row = $result->fetch_object ();
$result->free ();
function getObjectFromResult($result) {
if ($result) {
$row = $result->fetch_object();
$result->free();
return $row;
}
@ -168,18 +154,16 @@ class Connection
*
* @return mixed The value or %NULL if error
*/
function getValueFromResult ($result)
{
function getValueFromResult($result) {
$value = NULL;
if ($result)
{
$row = $result->fetch_row ();
if ($result) {
$row = $result->fetch_row();
if ($row && count ($row) > 0)
if ($row && count($row) > 0)
$value = $row[0];
$result->free ();
$result->free();
}
return $value;
@ -193,10 +177,9 @@ class Connection
*
* @return mixed[] An associative array with the first row, %NULL if error
*/
function getRow ($query, $params = NULL)
{
$result = $this->query ($query, $params);
return $this->getRowFromResult ($result);
function getRow($query, $params = NULL) {
$result = $this->query($query, $params);
return $this->getRowFromResult($result);
}
/**
@ -207,10 +190,9 @@ class Connection
*
* @return object An object with the first row, %NULL if error
*/
function getObject ($query, $params = NULL)
{
$result = $this->query ($query, $params);
return $this->getObjectFromResult ($result);
function getObject($query, $params = NULL) {
$result = $this->query($query, $params);
return $this->getObjectFromResult($result);
}
/**
@ -221,10 +203,9 @@ class Connection
*
* @return mixed The value or %NULL if error
*/
function getValue ($query, $params = NULL)
{
$result = $this->query ($query, $params);
return $this->getValueFromResult ($result);
function getValue($query, $params = NULL) {
$result = $this->query($query, $params);
return $this->getValueFromResult($result);
}
/**
@ -235,14 +216,13 @@ class Connection
*
* @return mixed The query string
*/
function loadFromFile ($file, $params = NULL)
{
$query = file_get_contents ($file .'.sql');
function loadFromFile($file, $params = NULL) {
$query = file_get_contents($file .'.sql');
if ($query === FALSE)
throw new Exception (NULL, 'Can not load query from file');
throw new Exception(NULL, 'Can not load query from file');
return $this->render ($query, $params);
return $this->render($query, $params);
}
/**
@ -253,12 +233,11 @@ class Connection
*
* @return mixed The value or %NULL if error
*/
function queryFromFile ($file, $params = NULL)
{
$query = $this->loadFromFile ($file, $params);
function queryFromFile($file, $params = NULL) {
$query = $this->loadFromFile($file, $params);
if ($query)
return $this->query ($query);
return $this->query($query);
return NULL;
}
@ -271,10 +250,9 @@ class Connection
*
* @return mixed[] An associative array with the first row, %NULL if error
*/
function getRowFromFile ($file, $params = NULL)
{
$result = $this->queryFromFile ($file, $params);
return $this->getRowFromResult ($result);
function getRowFromFile($file, $params = NULL) {
$result = $this->queryFromFile($file, $params);
return $this->getRowFromResult($result);
}
/**
@ -285,10 +263,9 @@ class Connection
*
* @return mixed The value or %NULL if error
*/
function getValueFromFile ($file, $params = NULL)
{
$result = $this->queryFromFile ($file, $params);
return $this->getValueFromResult ($result);
function getValueFromFile($file, $params = NULL) {
$result = $this->queryFromFile($file, $params);
return $this->getValueFromResult($result);
}
/**
@ -299,12 +276,11 @@ class Connection
*
* @return mixed The value or %NULL if error
*/
function multiQuery ($query, $params = NULL)
{
$success = $this->conn->multi_query ($this->render ($query, $params));
function multiQuery($query, $params = NULL) {
$success = $this->conn->multi_query($this->renderDebug($query, $params));
if (!$success)
$this->checkError ();
$this->checkError();
return $success;
}
@ -316,30 +292,26 @@ class Connection
*
* @return mixed The statement object or %FALSE if an error occurred
*/
function prepare ($query)
{
return $this->conn->prepare ($query);
function prepare($query) {
return $this->conn->prepare($query);
}
function storeResult ()
{
$result = $this->conn->store_result ();
function storeResult() {
$result = $this->conn->store_result();
if (!$result)
$this->checkError ();
$this->checkError();
return $result;
}
function moreResults ()
{
return $this->conn->more_results ();
function moreResults() {
return $this->conn->more_results();
}
function nextResult ()
{
$hasNext = $this->conn->next_result ();
$this->checkError ();
function nextResult() {
$hasNext = $this->conn->next_result();
$this->checkError();
return $hasNext;
}
@ -347,10 +319,9 @@ class Connection
* Check if there has been an error in the last query or multiquery,
* throwing a @Exception exception if any.
*/
function checkError ()
{
function checkError() {
if ($this->conn->errno)
throw new Exception ($this->conn->errno, $this->conn->error);
throw new Exception($this->conn->errno, $this->conn->error);
}
/**
@ -358,8 +329,7 @@ class Connection
*
* @return boolean %TRUE if there have been warnings %FALSE otherwise
*/
function checkWarnings ()
{
function checkWarnings() {
return $this->conn->warning_count > 0;
}
@ -371,29 +341,26 @@ class Connection
*
* @return string The rendered SQL string
*/
function render ($query, $paramsMap = NULL)
{
if (isset ($paramsMap) && is_array ($paramsMap) && count ($paramsMap) > 0)
{
function render($query, $paramsMap = NULL) {
if (isset($paramsMap) && is_array($paramsMap) && count($paramsMap) > 0) {
$i = 0;
$params = [];
foreach ($paramsMap as $key => $value)
$params[$key] = $this->renderValue ($value);
foreach($paramsMap as $key => $value)
$params[$key] = $this->renderValue($value);
$replaceFunc = function ($matches) use (&$params, &$i)
{
$key = substr ($matches[0], 1);
$replaceFunc = function($matches) use(&$params, &$i) {
$key = substr($matches[0], 1);
if (strlen ($key) == 0)
if (strlen($key) == 0)
$key = $i++;
if (isset ($params[$key]))
if (isset($params[$key]))
return $params[$key];
return '#'. $key;
};
return preg_replace_callback ('/#\w*/', $replaceFunc, $query);
return preg_replace_callback('/#\w*/', $replaceFunc, $query);
}
else
return $query;
@ -406,25 +373,61 @@ class Connection
*
* @return string The SQL value
*/
function renderValue ($value)
{
function renderValue($value) {
if ($value !== NULL)
switch (Type::get ($value))
{
switch (Type::get($value)) {
case Type::BOOLEAN:
return ($value) ? 'TRUE' : 'FALSE';
return($value) ? 'TRUE' : 'FALSE';
case Type::STRING:
return '\'' . $this->conn->escape_string ($value) . '\'';
return '\'' . $this->escapeString($value) . '\'';
case Type::DATE:
return strftime ('\'%Y-%m-%d\'', $value->getTimestamp ());
return strftime('\'%Y-%m-%d\'', $value->getTimestamp());
case Type::TIME:
return strftime ('\'%T\'', $value->getTimestamp ());
return strftime('\'%T\'', $value->getTimestamp());
case Type::DATE_TIME:
return strftime ('\'%Y-%m-%d %T\'', $value->getTimestamp ());
return strftime('\'%Y-%m-%d %T\'', $value->getTimestamp());
default:
return '\'' . $this->conn->escape_string ($value) . '\'';
return '\'' . $this->escapeString($value) . '\'';
}
else
return 'NULL';
}
/**
* Escapes an string, escaping special characters when necessary.
*
* @param string $string The string
* @return string The escaped string
*/
function escapeString($string) {
return $this->conn->real_escape_string($string);
}
/**
* Quotes an identifier, escaping special characters when necessary.
*
* @param string $identifier The identifier without quotes
* @return string The quoted identifier
*/
function quote($identifier) {
return "`". str_replace("`", "``", $identifier) ."`";
}
/**
* Renders an SQL string using the given parameters, also debugs the
* rendered string if $enableDebug property is set to %true.
*
* @param string $query The SQL string
* @param mixed[] $paramsMap The query parameters
*
* @return string The rendered SQL string
*/
function renderDebug($query, $params = NULL) {
$renderedQuery = $this->render($query, $params);
if ($this->enableDebug)
error_log($renderedQuery);
return $renderedQuery;
}
}

View File

@ -4,15 +4,13 @@ namespace Vn\Db;
/**
* Class used to store information about database errors.
**/
class Exception extends \Exception
{
*/
class Exception extends \Exception {
/**
* @param string $code The code of message
* @param string $message The message string
**/
function __construct ($code, $message)
{
parent::__construct ($message, $code);
*/
function __construct($code, $message) {
parent::__construct($message, $code);
}
}

2
debian/changelog vendored
View File

@ -1,4 +1,4 @@
php-vn-lib (2.1.3) stable; urgency=low
php-vn-lib (2.1.4) stable; urgency=low
* Initial Release.

View File

@ -1,6 +1,6 @@
<?php
set_include_path (__DIR__.PATH_SEPARATOR.get_include_path ());
set_include_path(__DIR__.PATH_SEPARATOR.get_include_path());
$vnAutoloadMap = [];
$vnAutoloadMap['vn/lib'] = __DIR__.'/lib';

View File

@ -7,22 +7,21 @@ require_once __DIR__.'/util.php';
use Vn\Db\Connection;
use Vn\Lib\Locale;
if (!defined ('_ENABLE_DEBUG'))
define ('_ENABLE_DEBUG', FALSE);
if (!defined ('_DEV_MODE'))
define ('_DEV_MODE', FALSE);
if (!defined ('_CONFIG_DIR'))
define ('_CONFIG_DIR', '/etc');
if (!defined ('_LOG_DIR'))
define ('_LOG_DIR', '/var/log');
if (!defined ('_DATA_DIR'))
define ('_DATA_DIR', '/var/lib');
if (!defined('_ENABLE_DEBUG'))
define('_ENABLE_DEBUG', FALSE);
if (!defined('_DEV_MODE'))
define('_DEV_MODE', FALSE);
if (!defined('_CONFIG_DIR'))
define('_CONFIG_DIR', '/etc');
if (!defined('_LOG_DIR'))
define('_LOG_DIR', '/var/log');
if (!defined('_DATA_DIR'))
define('_DATA_DIR', '/var/lib');
/**
* Base class for applications.
*/
class App
{
class App {
protected $name;
protected $methodDir;
private $conf = NULL;
@ -33,8 +32,7 @@ class App
*
* @param name string The application name
*/
function __construct ($name, $methodDir = NULL)
{
function __construct($name, $methodDir = NULL) {
$this->name = $name;
$this->methodDir = $methodDir;
}
@ -44,8 +42,7 @@ class App
*
* @return The application name
*/
function getName ()
{
function getName() {
return $this->name;
}
@ -54,8 +51,7 @@ class App
*
* @return The config object
*/
function getConf ()
{
function getConf() {
return $this->conf;
}
@ -63,26 +59,23 @@ class App
* Initializes Application. Should be the first called function in any
* application that uses this class.
*/
function init ()
{
ini_set ('log_errors', TRUE);
//ini_set ('error_log', _LOG_DIR .'/'. $this->name .'.log');
function init() {
ini_set('log_errors', TRUE);
//ini_set('error_log', _LOG_DIR .'/'. $this->name .'.log');
register_shutdown_function ([$this, 'deinit']);
register_shutdown_function([$this, 'deinit']);
$configFile = $this->getConfigFile ();
$this->conf = include ($configFile);
$configFile = $this->getConfigFile();
$this->conf = include($configFile);
}
/**
* Deinitializes the Application. When init method is called, this
* function is called automatically at the end of the script.
*/
function deinit ()
{
if ($this->sysConn)
{
$this->sysConn->close ();
function deinit() {
if ($this->sysConn) {
$this->sysConn->close();
$this->sysConn = NULL;
}
}
@ -90,14 +83,13 @@ class App
/**
* Gets the configuration file name.
*/
function getConfigFile ()
{
function getConfigFile() {
$configDir = _CONFIG_DIR .'/'. $this->name;
$customFile = "$configDir/config.my.php";
if (file_exists ('config.php'))
if (file_exists('config.php'))
return 'config.php';
else if (file_exists ($customFile))
else if (file_exists($customFile))
return $customFile;
else
return "$configDir/config.php";
@ -107,23 +99,22 @@ class App
* Creates a new connection object using the configuration parameters and
* the passed user and password.
*/
function createConnection ($user, $password, $persistent = FALSE)
{
function createConnection($user, $password, $persistent = FALSE) {
$dbConf = $this->conf['db'];
$host = $dbConf['host'];
if ($persistent)
$host = 'p:'.$host;
$conn = new Connection ();
$conn->open (
$conn = new Connection();
$conn->open(
$host
,$user
,$password
,$dbConf['schema']
,$dbConf['port']
);
$conn->query ('SET @lang = #', [Locale::get ()]);
$conn->query('SET @lang = #', [Locale::get()]);
return $conn;
}
@ -132,13 +123,11 @@ class App
*
* @return Vn\Db\Conn The connection
*/
function getSysConn ()
{
if (!$this->sysConn)
{
function getSysConn() {
if (!$this->sysConn) {
$dbConf = $this->conf['db'];
$this->sysConn = $this->createConnection (
$dbConf['user'], base64_decode ($dbConf['pass']), TRUE);
$this->sysConn = $this->createConnection(
$dbConf['user'], base64_decode($dbConf['pass']), TRUE);
}
return $this->sysConn;
@ -147,48 +136,47 @@ class App
/**
* Starts the application. Should be implemented by child classes.
*/
function run () {}
function run() {}
/**
* Runs a method.
*/
function loadMethod ($methodUri = NULL, $checkClass = NULL, $baseDir = NULL)
{
function loadMethod($methodUri = NULL, $checkClass = NULL, $baseDir = NULL) {
// XXX: Partially implemented
if (!$methodUri)
$methodUri = basename ($_SERVER['SCRIPT_FILENAME'], '.php');
$methodUri = basename($_SERVER['SCRIPT_FILENAME'], '.php');
if (!$baseDir)
$baseDir = $this->methodDir;
if (!$checkClass)
$checkClass = __NAMESPACE__ .'\Method';
if (!preg_match ('/^[\/\w\-]+$/', $methodUri))
throw new \Exception ('Method contains invalid characters');
if (!preg_match('/^[\/\w\-]+$/', $methodUri))
throw new \Exception('Method contains invalid characters');
$split = explode ('/', $methodUri);
$methodName = array_pop ($split);
$methodPath = implode ('/', $split);
$split = explode('/', $methodUri);
$methodName = array_pop($split);
$methodPath = implode('/', $split);
if (empty ($methodName))
throw new \Exception ('Invalid method name');
if (empty($methodName))
throw new \Exception('Invalid method name');
$methodFile = '';
if (!empty ($baseDir))
if (!empty($baseDir))
$methodFile .= "$baseDir/";
if (!empty ($methodPath))
if (!empty($methodPath))
$methodFile .= "$methodPath/";
$methodFile .= "$methodName.php";
$className = hyphenToCamelCase ($methodName, TRUE);
include_once ($methodFile);
$className = hyphenToCamelCase($methodName, TRUE);
include_once($methodFile);
if (!class_exists ($className))
throw new \Exception ("Class '$className' not exists");
if (!is_subclass_of ($className, $checkClass))
throw new \Exception ("Class '$className' is not a '$checkClass' child");
if (!class_exists($className))
throw new \Exception("Class '$className' not exists");
if (!is_subclass_of($className, $checkClass))
throw new \Exception("Class '$className' is not a '$checkClass' child");
Locale::addPath ("$baseDir/$methodName");
return new $className ($this);
Locale::addPath("$baseDir/$methodName");
return new $className($this);
}
}

View File

@ -4,40 +4,36 @@ namespace Vn\Lib;
/**
* Implements command line applications.
**/
class CliApp extends App
{
function run ()
{
$this->init ();
*/
class CliApp extends App {
function run() {
$this->init();
if ($lang = substr (getenv ('LANG'), 0, 2))
Locale::set ($lang);
if ($lang = substr(getenv('LANG'), 0, 2))
Locale::set($lang);
try {
$options = getopt ('m:');
$options = getopt('m:');
if (empty ($options['m']))
$this->usage ();
if (empty($options['m']))
$this->usage();
$db = $this->getSysConn ();
$db = $this->getSysConn();
echo "Executing method '{$options['m']}'\n";
$method = $this->loadMethod ($options['m']);
$method->run ($db);
$method = $this->loadMethod($options['m']);
$method->run($db);
}
catch (Exception $e)
{
echo $e->getMessage ()."\n";
exit (2);
catch (Exception $e) {
echo $e->getMessage()."\n";
exit(2);
}
}
function usage ()
{
function usage() {
global $argv;
echo "Usage: {$argv[0]} -m method_path\n";
exit (1);
exit(1);
}
}

View File

@ -7,14 +7,12 @@ namespace Vn\Lib;
*
* @property string $message The message string
* @property string $code The code of message
**/
class Exception extends \Exception
{
*/
class Exception extends \Exception {
protected $code;
function __construct ($message = '', $code = NULL, $previous = NULL)
{
parent::__construct ($message, 0, $previous);
function __construct($message = '', $code = NULL, $previous = NULL) {
parent::__construct($message, 0, $previous);
$this->code = $code;
}
}

View File

@ -1,24 +1,19 @@
<?php
namespace
{
namespace {
use Vn\Lib\Locale;
function i($stringId)
{
echo Locale::getString ($stringId);
function i($stringId) {
echo Locale::getString($stringId);
}
function s($stringId)
{
return Locale::getString ($stringId);
function s($stringId) {
return Locale::getString($stringId);
}
}
namespace Vn\Lib
{
class Locale
{
namespace Vn\Lib {
class Locale {
static $localeSet = FALSE;
static $locale = 'en';
static $strings = [];
@ -29,27 +24,25 @@ namespace Vn\Lib
*
* @param string $locale The locale with 2 digits format, or %NULL to
* set the default
**/
static function set ($locale = NULL)
{
if (empty ($locale))
*/
static function set($locale = NULL) {
if (empty($locale))
$locale = self::$locale;
self::$locale = $locale;
setlocale (LC_ALL, $locale);
setlocale(LC_ALL, $locale);
self::$localeSet = TRUE;
foreach (self::$paths as $path => $kk)
self::loadFile ($path);
foreach(self::$paths as $path => $kk)
self::loadFile($path);
}
/**
* Gets the locale.
*
* @return string The locale with 2 digits format
**/
static function get ()
{
*/
static function get() {
return self::$locale;
}
@ -59,10 +52,9 @@ namespace Vn\Lib
*
* @param string $stringId The string to translate
* @return string The translated string
**/
static function getString ($stringId)
{
if (isset (self::$strings[$stringId]))
*/
static function getString($stringId) {
if (isset(self::$strings[$stringId]))
return self::$strings[$stringId];
else
return $stringId;
@ -72,28 +64,26 @@ namespace Vn\Lib
* Adds a path where a JSON file with translations is located.
*
* @param string $path The JSON file path
**/
static function addPath ($path)
{
*/
static function addPath($path) {
self::$paths[$path] = TRUE;
if (self::$localeSet)
self::loadFile ($path);
self::loadFile($path);
}
/**
* Loads translations from a JSON file.
*
* @param string $path The JSON file path
**/
static function loadFile ($path)
{
*/
static function loadFile($path) {
$locale = self::$locale;
$file = stream_resolve_include_path ("$path/locale/$locale.json");
$file = stream_resolve_include_path("$path/locale/$locale.json");
if (file_exists ($file)
&& ($jsonString = file_get_contents ($file)))
self::addTranslations (json_decode ($jsonString, TRUE));
if (file_exists($file)
&&($jsonString = file_get_contents($file)))
self::addTranslations(json_decode($jsonString, TRUE));
}
/**
@ -101,10 +91,9 @@ namespace Vn\Lib
*
* @param array $strings Associative array of every string and its
* translation
**/
static function addTranslations ($strings)
{
foreach ($strings as $string => &$translation)
*/
static function addTranslations($strings) {
foreach($strings as $string => &$translation)
self::$strings[$string] = &$translation;
}
}

View File

@ -2,70 +2,65 @@
namespace Vn\Lib;
class Log
{
class Log {
private static $fd = NULL;
private static $count;
private static $file;
static function init ($file)
{
self::close ();
static function init($file) {
self::close();
self::$file = $file;
self::$fd = fopen ($file, 'a');
self::rename ();
set_error_handler ('Vn\Lib\Log::phpHandler', E_ALL);
self::$fd = fopen($file, 'a');
self::rename();
set_error_handler('Vn\Lib\Log::phpHandler', E_ALL);
}
static function phpHandler ($no, $str, $file, $line, $context)
{
self::write ('PHP: %s:%d: %s', $file, $line, $str);
switch ($no)
{
static function phpHandler($no, $str, $file, $line, $context) {
self::write('PHP: %s:%d: %s', $file, $line, $str);
switch ($no) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
self::write ('PHP: Could not continue, exiting.');
self::close ();
exit (1);
self::write('PHP: Could not continue, exiting.');
self::close();
exit(1);
}
return TRUE;
}
static function close ()
{
if (self::$fd != NULL)
{
fclose (self::$fd);
static function close() {
if (self::$fd != NULL) {
fclose(self::$fd);
self::$fd = NULL;
}
}
static function write ()
{
static function write() {
if (self::$fd == NULL)
return;
if (self::$count > 5000)
self::rename ();
self::rename();
self::$count += fprintf (self::$fd, "%s: %s\n"
,strftime ('%Y-%m-%d %T')
,call_user_func_array ('sprintf', func_get_args ())
self::$count += fprintf(self::$fd, "%s: %s\n"
,strftime('%Y-%m-%d %T')
,call_user_func_array('sprintf', func_get_args())
);
}
static private function rename ()
{
if (filesize (self::$file) > 1000000)
{
self::close ();
static private function rename() {
if (filesize(self::$file) > 1000000) {
self::close();
$rename = self::$file.'.1';
if (file_exists ($rename))
unlink ($rename);
if (file_exists($rename))
unlink($rename);
rename (self::$file, $rename);
self::$fd = fopen ($file, 'a');
rename(self::$file, $rename);
self::$fd = fopen($file, 'a');
}
self::$count = 0;

View File

@ -5,8 +5,7 @@ namespace Vn\Lib;
/**
* Base class for rest methods.
*/
abstract class Method
{
abstract class Method {
protected $app;
protected $conn = NULL;
@ -15,8 +14,7 @@ abstract class Method
*
* @param app Lib\App The application
*/
function __construct ($app)
{
function __construct($app) {
$this->app = $app;
}
@ -26,16 +24,15 @@ abstract class Method
* @param {Db\Conn} $db The main database connection
* @return mixed The result of the method
*/
abstract function run ($db);
abstract function run($db);
/**
* Returns the system database connection.
*
* return {Db\Conn} The database connection
*/
function getSysConn ()
{
return $this->app->getSysConn ();
function getSysConn() {
return $this->app->getSysConn();
}
/**
@ -46,14 +43,12 @@ abstract class Method
* @param {array} $params The list of keys to check
* @return {boolean} %TRUE if all key are defined, %FALSE otherwise
*/
function checkParams ($map, $params)
{
if (!isset ($map))
function checkParams($map, $params) {
if (!isset($map))
return FALSE;
foreach ($params as $param)
if (!isset ($map[$param]))
{
foreach($params as $param)
if (!isset($map[$param])) {
return FALSE;
break;
}

View File

@ -18,17 +18,17 @@ class Type
const DATE = 8;
const DATE_TIME = 9;
static function get ($value)
static function get($value)
{
if (is_bool ($value))
if (is_bool($value))
return self::BOOLEAN;
elseif (is_int ($value))
elseif (is_int($value))
return self::INTEGER;
elseif (is_float ($value))
elseif (is_float($value))
return self::DOUBLE;
elseif (is_string ($value))
elseif (is_string($value))
return self::STRING;
elseif (is_object ($value))
elseif (is_object($value))
{
if ($value instanceof Time)
return self::TIME;
@ -43,21 +43,21 @@ class Type
return self::NUL;
}
static function set (& $value, $type)
static function set(& $value, $type)
{
switch ($type)
{
case self::INTEGER:
settype ($value, 'integer');
settype($value, 'integer');
break;
case self::DOUBLE:
settype ($value, 'float');
settype($value, 'float');
break;
case self::STRING:
settype ($value, 'string');
settype($value, 'string');
break;
case self::BOOLEAN:
settype ($value, 'boolean');
settype($value, 'boolean');
break;
case self::NUL:
$value = NULL;

View File

@ -9,6 +9,6 @@ namespace Vn\Lib;
* @property string $domain The domain name
* @property string $code The code of message
* @property string $message The message string
**/
*/
class UserException extends Exception {}

View File

@ -3,47 +3,43 @@
/**
* Retrieves an element from an associative array or %NULL if it is not
* defined.
**/
function nullIf ($map, $key)
*/
function nullif ($map, $key)
{
return isset ($map[$key]) ? $map[$key] : NULL;
return isset($map[$key]) ? $map[$key] : NULL;
}
/**
* Checks if passed $path is inside directory $dir.
**/
function checkFilePath ($file, $path)
*/
function checkFilePath($file, $path)
{
$checkPath = stream_resolve_include_path ($path).'/';
$filePath = stream_resolve_include_path ($checkPath.$file);
$checkPath = stream_resolve_include_path($path).'/';
$filePath = stream_resolve_include_path($checkPath.$file);
$len = strlen ($checkPath);
return substr ($filePath, 0, strlen ($checkPath)) === $checkPath;
$len = strlen($checkPath);
return substr($filePath, 0, strlen($checkPath)) === $checkPath;
}
/**
* Checks if passed token is hyphenized.
**/
function isHyphen ($token)
{
return preg_match ('/^[\w\-]+$/', $token);
*/
function isHyphen($token) {
return preg_match('/^[\w\-]+$/', $token);
}
/**
* Transforms an hyphen string to camelcase.
**/
function hyphenToCamelCase ($string, $upperFirst = FALSE)
{
$replaceFunc = function ($matches)
{
return strtoupper ($matches[0][1]);
*/
function hyphenToCamelCase($string, $upperFirst = FALSE) {
$replaceFunc = function($matches) {
return strtoupper($matches[0][1]);
};
$result = preg_replace_callback ('/-[a-z]/', $replaceFunc, $string);
$result = preg_replace_callback('/-[a-z]/', $replaceFunc, $string);
if ($upperFirst)
$result = strtoupper ($result{0}) . substr ($result, 1);
$result = strtoupper($result{0}) . substr($result, 1);
return $result;
}

View File

@ -1,10 +1,9 @@
<?php
$vnAutoloadReplace = function ($matches)
{
$match = strtolower ($matches[0]);
$vnAutoloadReplace = function($matches) {
$match = strtolower($matches[0]);
if (strlen ($match) == 1)
if (strlen($match) == 1)
return $match;
if ($match{0} == '\\')
return DIRECTORY_SEPARATOR. $match{1};
@ -12,28 +11,25 @@ $vnAutoloadReplace = function ($matches)
return $match{0} .'-'. $match{1};
};
spl_autoload_register (function ($className)
{
spl_autoload_register(function($className) {
global $vnAutoloadReplace, $vnAutoloadMap;
$classPath = preg_replace_callback ('/.?[A-Z]/', $vnAutoloadReplace, $className);
$classPath = preg_replace_callback('/.?[A-Z]/', $vnAutoloadReplace, $className);
$classPath .= '.php';
if (isset ($vnAutoloadMap))
foreach ($vnAutoloadMap as $prefix => $location)
{
$prefixLen = strlen ($prefix);
if (isset($vnAutoloadMap))
foreach($vnAutoloadMap as $prefix => $location) {
$prefixLen = strlen($prefix);
if (strncmp ($classPath, $prefix, $prefixLen) == 0)
{
$classPath = "$location/". substr ($classPath, $prefixLen);
if (strncmp($classPath, $prefix, $prefixLen) == 0) {
$classPath = "$location/". substr($classPath, $prefixLen);
break;
}
}
if ($classPath{0} != DIRECTORY_SEPARATOR)
$classPath = stream_resolve_include_path ($classPath);
$classPath = stream_resolve_include_path($classPath);
if (file_exists ($classPath))
if (file_exists($classPath))
require_once $classPath;
});