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

View File

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

View File

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

View File

@ -4,40 +4,36 @@ namespace Vn\Lib;
/** /**
* Implements command line applications. * Implements command line applications.
**/ */
class CliApp extends App class CliApp extends App {
{ function run() {
function run () $this->init();
{
$this->init ();
if ($lang = substr (getenv ('LANG'), 0, 2)) if ($lang = substr(getenv('LANG'), 0, 2))
Locale::set ($lang); Locale::set($lang);
try { try {
$options = getopt ('m:'); $options = getopt('m:');
if (empty ($options['m'])) if (empty($options['m']))
$this->usage (); $this->usage();
$db = $this->getSysConn (); $db = $this->getSysConn();
echo "Executing method '{$options['m']}'\n"; echo "Executing method '{$options['m']}'\n";
$method = $this->loadMethod ($options['m']); $method = $this->loadMethod($options['m']);
$method->run ($db); $method->run($db);
} }
catch (Exception $e) catch (Exception $e) {
{ echo $e->getMessage()."\n";
echo $e->getMessage ()."\n"; exit(2);
exit (2);
} }
} }
function usage () function usage() {
{
global $argv; global $argv;
echo "Usage: {$argv[0]} -m method_path\n"; 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 $message The message string
* @property string $code The code of message * @property string $code The code of message
**/ */
class Exception extends \Exception class Exception extends \Exception {
{
protected $code; protected $code;
function __construct ($message = '', $code = NULL, $previous = NULL) function __construct($message = '', $code = NULL, $previous = NULL) {
{ parent::__construct($message, 0, $previous);
parent::__construct ($message, 0, $previous);
$this->code = $code; $this->code = $code;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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