adding db classes & UserProvider

This commit is contained in:
a-sansara 2017-03-15 13:07:32 +01:00
parent 4af88d5d6e
commit 0782ab0b1c
5 changed files with 600 additions and 0 deletions

View File

@ -0,0 +1,48 @@
<?php
namespace MetaTech\Core;
/*!
* Singleton Pattern
*
* @package Mtc\Core
* @class Singleton
* @author a-Sansara
* @date 2014-11-05 23:45:12 CET
*/
class Singleton
{
/*! @protected @static @var $_instance the class instance */
protected static $_instance;
/*!
* @constructor
* @protected
*/
protected function __construct()
{
}
/*!
* @method __clone
* @protected
*/
protected function __clone()
{
}
/*!
* get the class instance
*
* @method getInstance
* @public
* @static
* @return Singleton
*/
public static function getInstance()
{
if (!(static::$_instance instanceof static)) {
static::$_instance = new static();
}
return static::$_instance;
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace MetaTech\Core\Db;
use PDO;
use MetaTech\Core\Singleton;
/*!
* @package MetaTech\Db
* @class PdoConnector
* @extends MetaTech\Core\Singleton
* @author a-Sansara
* @date 2015-02-13 16:36:12 CET
*/
class PdoConnector extends Singleton
{
/*! @protected @var [] $conn */
protected $conn = array();
/*! @protected @var string $currentProfile */
protected $currentProfile;
/*!
* @private
* @param MetaTech\Db\Profile $profile
* @param bool $recreate
* @return \PDO
*/
private function getPdo(Profile $profile, $recreate=false)
{
$name = $profile->getName();
if ($recreate || !isset($this->conn[$name]) || $this->conn[$name] == null) {
$this->setPdo($profile);
}
return $this->conn[$name];
}
/*!
* @method setCurrentProfile
* @private
* @param str $name
*/
private function setCurrentProfile($name)
{
$this->currentProfile = $name;
}
/*!
* @method setPdo
* @private
* @param MetaTech\Db\Profile $profile
*/
private function setPdo(Profile $profile)
{
$pdo = new PDO($profile->getDsn(), $profile->getUser(), $profile->getPassword());
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query("SET NAMES '".$profile->getCharset()."'");
$this->conn[$profile->getName()] = $pdo;
}
/*!
* @method switchDb
* @public
* @param MetaTech\Db\Profile $profile
* @param bool $recreate
*/
public function switchDb(Profile $profile, $recreate=false)
{
$this->currentProfile = $profile->getName();
$this->getPdo($profile, $recreate);
}
/*!
* @method conn
* @public
* @return PDO
*/
public function conn()
{
return $this->conn[$this->currentProfile];
}
}

View File

@ -0,0 +1,234 @@
<?php
namespace MetaTech\Db;
use MetaTech\Db\PdoConnector;
use MetaTech\Db\Profile;
/*!
* Little Db utility to improve db interractions
*
* @package Mtc\Db
* @class PdoWrapper
* @author a-Sansara
* @date 2015-02-13 22:40:12 CET
*/
class PdoWrapper
{
/*! @protected @var Monolog\Handler\StreamHandler $logger */
protected $logger;
/*! @protected @var MetaTech\Db\Profile $profile */
protected $profile;
/*! @protected @var $bypasslog */
protected $bypasslog;
/*!
* @constructor
* @public
* @param MetaTech\Db\Profile $profile
* @param Monolog\Handler\StreamHandler $logger
*/
public function __construct(Profile $profile, $logger = null)
{
$this->profile = $profile;
$this->logger = $logger;
}
/*!
* Return the PDO connection object
*
* @method getPdoConnection
* @public
* @return PDO
*/
public function getPdoConnection()
{
return PdoConnector::getInstance()->conn();
}
/*!
* @method switchDb
* @public
* @param Mtc\Core\Db\Profile $profile
* @return PDO
*/
public function switchDb(Profile $profile = null, $recreate=false)
{
if (is_null($profile)) {
$profile = $this->profile;
}
return PdoConnector::getInstance()->switchDb($profile, $recreate);
}
/*!
* @method getLogger
* @public
* @return Monolog\Handler\StreamHandler
*/
public function getLogger()
{
return $this->logger;
}
/*!
* @method log
* @private
* @param str $query
* @param [] $data
* @param bool $start
*/
private function log($query, $data, $start=true, $forceLog=false)
{
if ($this->logger != null) {
$minisql = substr($query, 0, 35);
$bypasslog = strpos(substr($query, 0, 35), 'SELECT')!==false;
if (!$this->bypasslog || $forceLog) {
$this->bypasslog = $bypasslog;
if ($start) {
if (!$bypasslog || $forceLog) {
$this->logger->addDebug(" => ".str_pad("QUERY", 8, " ", STR_PAD_LEFT).' '.preg_replace('/[ ]{2,}/', ' ', $query));
if( !empty($data)) $this->logger->addDebug(str_pad("PARAMS", 12, " ", STR_PAD_LEFT), $data);
}
}
else {
$this->logger->addDebug(" <= $query", $data);
}
}
elseif (!$start) $this->bypasslog = false;
}
}
/*!
* execute a query and get Result Statement for the specified $data
*
* @method exec
* @public
* @param str $query
* @param [] $data
* @param int $fetch
* @return PdoStatement
*/
public function exec($query, $data = array(), $fetch = null, $forceLog=false)
{
$this->switchDb(null, true);
$this->log($query, $data, true, $forceLog);
if ($fetch == null) {
$fetch = \PDO::FETCH_OBJ;
}
$stmt = $this->getPdoConnection()->prepare($query);
if (is_array($data)) {
foreach ($data as $cl => $f) {
if (!is_null($f)) {
@$stmt->bindParam(':'.$cl, $data[$cl], ($cl == 'queryIndex' || $cl == 'queryLimit' ? \PDO::PARAM_INT : \PDO::PARAM_STR)); // don't use $f, cause value pass by reference
}
else {
$stmt->bindValue(':'.$cl, null, \PDO::PARAM_INT /* prefer to \PDO::PARAM_NULL for compat*/);
}
}
}
try {
$stmt->execute();
if ($fetch !== false) {
$stmt->setFetchMode($fetch);
}
$rowCount = $stmt!=null ? $stmt->rowCount() : 0;
$lastInsertId = $this->getLastInsertId();
$this->log(str_pad("RS", 8, " ", STR_PAD_LEFT), compact('rowCount', 'lastInsertId'), false, $forceLog);
}
catch(\Exception $e) {
if (!is_null($this->logger)) {
$this->bypasslog = false;
$this->logger->addError($e->getMessage());
foreach (preg_split('/#/', $e->getTraceAsString()) as $error) {
if (!empty($error)) {
$this->logger->addDebug("#$error");
}
}
}
throw $e;
}
return $stmt;
}
/*!
* get last insert id in db
*
* @method getLastInsertId
* @public
* @return int
*/
public function getLastInsertId()
{
return $this->getPdoConnection()->lastInsertId();
}
/*!
* persist $data in table $table
*
* @method persist
* @public
* @param str $table
* @param [] $data
* @param bool $updateOnDuplicate
* @return PdoStatement
*/
public function persist($table, $data, $updateOnDuplicate = true)
{
if (isset($data['id']) && is_null($data['id'])) {
unset($data['id']);
$updateOnDuplicate = false;
}
$argnames = array_keys($data);
$updateDef = '';
if ($updateOnDuplicate) {
foreach ($argnames as $field) {
$updateDef .= ($updateDef == '' ? '' : ',')." `$field` = VALUES(`$field`)";
}
$updateDef = "ON DUPLICATE KEY UPDATE $updateDef";
}
return $this->exec(
"INSERT INTO $table (`".implode('`, `', $argnames).'`) VALUES (:'.implode(', :', $argnames).") $updateDef",
$data
);
}
/*!
* get autoincrement
*
* @method nextIncrement
* @public
* @param str $table
* @return int
*/
public function nextIncrement($table)
{
$data = $this->exec('SHOW TABLE STATUS WHERE `Name`= :table', compact('table'))->fetch();
return $data != false ? $data->Auto_increment : null;
}
/*!
* @method encodeJsonBase64
* @public
* @static
* @param mixed $data
* @return str
*/
public static function encodeJsonBase64($data)
{
return base64_encode(json_encode($data));
}
/*!
* @method decodeJsonBase64
* @public
* @static
* @param str $data
* @param bool $onlyb64
* @return stdclass
*/
public static function decodeJsonBase64($data, $onlyb64 = false)
{
return $onlyb64 ? base64_decode($data) : json_decode(base64_decode($data));
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace MetaTech\Db;
/*!
* Db Profile
*
* @package MetaTech\Db
* @class Profile
* @author a-Sansara
* @date 2014-02-13 12:30:12 CET
*/
class Profile
{
/*! @public @var $config */
private $config;
/*!
* @constructor
* @public
* @param [assoc] $config
*/
public function __construct(array $config = [])
{
if (is_array($config) && !empty($config)) {
$this->config = $config;
} else {
throw new \Exception("$config must be associative array");
}
}
/*!
* @method getName
* @public
* @return str
*/
public function getName()
{
return !isset($this->config['name']) ? $this->config['dbname'] : $this->config['name'];
}
/*!
* @method getUser
* @public
* @return str
*/
public function getUser()
{
return $this->config['user'];
}
/*!
* @method getPassword
* @public
* @return str
*/
public function getPassword()
{
return $this->config['password'];
}
/*!
* @method getCharset
* @public
* @return str
*/
public function getCharset()
{
return $this->config['charset'];
}
/*!
* @method getDsn
* @public
* @return str
*/
public function getDsn()
{
return 'mysql:host='.$this->config['host'].';port=3306;dbname='.$this->config['dbname'];
}
}

View File

@ -0,0 +1,159 @@
<?php
namespace MetaTech\Silex\Provider;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use MetaTech\Db\PdoWrapper;
/*!
* desc
*
* @package MetaTech\Silex\Provider
* @class UserProvider
* @implements Symfony\Component\Security\Core\User\UserInterface
* @author a-Sansara
* @date 2016-02-08 18:29:06 CET
*/
class UserProvider implements UserProviderInterface
{
/*! @private @var MetaTech\Db\PdoWrapper $pdo */
private $pdo;
/*! @private @var str $table */
private $table;
/*!
* @constructor
* @public
* @param MetaTech\Db\PdoWrapper $pdo
*/
public function __construct(PdoWrapper $pdo, $table='`users`')
{
$this->pdo = $pdo;
$this->table = $table;
}
/*!
* @method loadUser
* @private
* @param str $login
* @return Symfony\Component\Security\Core\User\User
*/
private function loadUser($login)
{
$username = strtolower($login);
$stmt = $this->pdo->exec('SELECT * FROM ' . $this->table . ' WHERE username = :username', compact('username'));
if (!$user = $stmt->fetch()) {
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
return $user;
}
/*!
* @method getUserNameById
* @public
* @param int $id
* @return Symfony\Component\Security\Core\User\User
*/
public function getUserNameById($id)
{
$stmt = $this->pdo->exec('SELECT name FROM ' . $this->table . ' WHERE id = :id', compact('id'));
if (!$user = $stmt->fetch()) {
throw new UsernameNotFoundException(sprintf('Userid "%s" does not exist.', $id));
}
return $user;
}
/*!
* @method loadUserPrograms
* @public
* @return Symfony\Component\Security\Core\User\User
*/
private function loadUserByRole($role)
{
return $this->pdo->exec('SELECT * FROM ' . $this->table . ' WHERE roles LIKE :role', compact('role'))->fetchAll();
}
/*!
* @method loadProgramKeys
* @public
* @return Symfony\Component\Security\Core\User\User
*/
public function loadProgramKeys()
{
$keys = [];
$rows = $this->loadUserPrograms();
$rows = array_merge($rows, $this->loadUserPrograms('INSURER'));
if (!empty($rows)) {
foreach ($rows as $row) {
$keys[] = $row->key;
}
}
return $keys;
}
/*!
* @method loadUserByUsername
* @public
* @param str $username
* @return Symfony\Component\Security\Core\User\User
*/
public function loadUserByUsername($username)
{
$user = $this->loadUser($username);
$u = new User($user->username, $user->password, explode(',', $user->roles), true, true, true, true);
$u->labelName = $user->name;
return $u;
}
/*!
* @method getUserKey
* @public
* @param str $username
* @return Symfony\Component\Security\Core\User\User
*/
public function getUserKey($username)
{
$user = $this->loadUser($username);
return $user->key;
}
/*!
* @method getIdUser
* @public
* @param str $username
* @return int|null
*/
public function getIdUser($username)
{
$user = $this->loadUser($username);
return isset($user->id) ? $user->id : null;
}
/*!
* @method refreshUser
* @public
* @param Symfony\Component\Security\Core\User\UserInterface $user
* @return Symfony\Component\Security\Core\User\User
*/
public function refreshUser(UserInterface $user)
{
if (!$user instanceof User) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
return $this->loadUserByUsername($user->getUsername());
}
/*!
* @method supportsClass
* @public
* @param str $class
* @return bool
*/
public function supportsClass($class) {
return $class === User::class;
}
}