Code style fixes

This commit is contained in:
Dmitry Khomutov 2016-04-20 16:30:26 +06:00
parent 5371b8fc75
commit 5b9c1d32f1
16 changed files with 1039 additions and 1180 deletions

View file

@ -8,17 +8,17 @@
* @link https://www.phptesting.org/
*/
return array(
return [
/** Loggers attached to every command */
"_" => function() {
return array(
return [
new \Monolog\Handler\StreamHandler(__DIR__ . DIRECTORY_SEPARATOR . 'errors.log', \Monolog\Logger::ERROR),
);
];
},
/** Loggers for the RunCommand */
'RunCommand' => function() {
return array(
return [
new \Monolog\Handler\RotatingFileHandler(__DIR__ . DIRECTORY_SEPARATOR . 'everything', 3, \Monolog\Logger::DEBUG),
);
];
},
);
];

View file

@ -13,25 +13,24 @@ require_once(dirname(__FILE__) . '../bootstrap.php');
$writeServers = $config->get('b8.database.servers.write');
if (!is_array($writeServers)) {
$writeServers = array($writeServers);
$writeServers = [$writeServers];
}
$conf = array(
'paths' => array(
$conf = [
'paths' => [
'migrations' => 'PHPCI/Migrations',
),
'environments' => array(
],
'environments' => [
'default_migration_table' => 'migration',
'default_database' => 'phpci',
'phpci' => array(
'default_database' => 'phpci',
'phpci' => [
'adapter' => 'mysql',
'host' => end($writeServers),
'name' => $config->get('b8.database.name'),
'user' => $config->get('b8.database.username'),
'pass' => $config->get('b8.database.password'),
),
),
);
'host' => end($writeServers),
'name' => $config->get('b8.database.name'),
'user' => $config->get('b8.database.username'),
'pass' => $config->get('b8.database.password'),
],
],
];
return $conf;

View file

@ -4,10 +4,10 @@ return function (PHPCI\Plugin\Util\Factory $factory) {
$factory->registerResource(
// This function will be called when the resource is needed.
function() {
return array(
return [
'Foo' => "Stuff",
'Bar' => "More Stuff"
);
];
},
// In addition to the function for building the resource the system

View file

@ -51,11 +51,11 @@ if (defined('PHPCI_IS_CONSOLE') && PHPCI_IS_CONSOLE) {
}
// Load configuration if present:
$conf = array();
$conf['b8']['app']['namespace'] = 'PHPCI';
$conf = [];
$conf['b8']['app']['namespace'] = 'PHPCI';
$conf['b8']['app']['default_controller'] = 'Home';
$conf['b8']['view']['path'] = dirname(__FILE__) . '/src/PHPCI/View/';
$conf['using_custom_file'] = $usingCustomConfigFile;
$conf['b8']['view']['path'] = dirname(__FILE__) . '/src/PHPCI/View/';
$conf['using_custom_file'] = $usingCustomConfigFile;
$config = new b8\Config($conf);

View file

@ -9,21 +9,25 @@ namespace b8;
class Cache
{
const TYPE_APC = 'ApcCache';
const TYPE_REQUEST = 'RequestCache';
const TYPE_APC = 'ApcCache';
const TYPE_REQUEST = 'RequestCache';
protected static $instance = array();
protected static $instance = [];
/**
* Get a cache object of a specified type.
*/
public static function getCache($type = self::TYPE_REQUEST)
{
if (!isset(self::$instance[$type])) {
$class = '\\b8\\Cache\\' . $type;
self::$instance[$type] = new $class();
}
return self::$instance[$type];
}
}
/**
* Get a cache object of a specified type.
*
* @param string $type
*
* @return mixed
*/
public static function getCache($type = self::TYPE_REQUEST)
{
if (!isset(self::$instance[$type])) {
$class = '\\b8\\Cache\\' . $type;
self::$instance[$type] = new $class();
}
return self::$instance[$type];
}
}

View file

@ -16,7 +16,7 @@ class ApcCache implements Type\Cache
$rtn = false;
$apcCli = ini_get('apc.enable_cli');
if (function_exists('apc_fetch') && (php_sapi_name() != 'cli' || in_array($apcCli, array('1', 1, true, 'On')))) {
if (function_exists('apc_fetch') && (php_sapi_name() != 'cli' || in_array($apcCli, ['1', 1, true, 'On']))) {
$rtn = true;
}

View file

@ -6,85 +6,85 @@ use b8\Type;
class RequestCache implements Type\Cache
{
protected $data = array();
protected $data = [];
/**
* Check if caching is enabled.
*/
public function isEnabled()
{
return true;
}
/**
* Check if caching is enabled.
*/
public function isEnabled()
{
return true;
}
/**
* Get item from the cache:
*/
public function get($key, $default = null)
{
return $this->contains($key) ? $this->data[$key] : $default;
}
/**
* Get item from the cache:
*/
public function get($key, $default = null)
{
return $this->contains($key) ? $this->data[$key] : $default;
}
/**
* Add an item to the cache:
*/
public function set($key, $value = null, $ttl = 0)
{
$this->data[$key] = $value;
/**
* Add an item to the cache:
*/
public function set($key, $value = null, $ttl = 0)
{
$this->data[$key] = $value;
return $this;
}
return $this;
}
/**
* Remove an item from the cache:
*/
public function delete($key)
{
if ($this->contains($key)) {
unset($this->data[$key]);
}
return $this;
}
/**
* Remove an item from the cache:
*/
public function delete($key)
{
if ($this->contains($key)) {
unset($this->data[$key]);
}
/**
* Check if an item is in the cache:
*/
public function contains($key)
{
return array_key_exists($key, $this->data);
}
return $this;
}
/**
* Short-hand syntax for get()
* @see Config::get()
*/
/**
* Check if an item is in the cache:
*/
public function contains($key)
{
return array_key_exists($key, $this->data);
}
/**
* Short-hand syntax for get()
* @see Config::get()
*/
public function __get($key)
{
return $this->get($key, null);
}
/**
* Short-hand syntax for set()
* @see Config::set()
*/
* Short-hand syntax for set()
* @see Config::set()
*/
public function __set($key, $value = null)
{
return $this->set($key, $value);
}
/**
* Is set
*/
* Is set
*/
public function __isset($key)
{
return $this->contains($key);
}
/**
* Unset
*/
* Unset
*/
public function __unset($key)
{
$this->delete($key);
}
}
}

View file

@ -20,7 +20,7 @@ class Config
/**
* @var array
*/
protected $config = array();
protected $config = [];
public function __construct($settings = null)
{

View file

@ -2,7 +2,6 @@
namespace b8;
use b8\Config;
use b8\Http\Request;
use b8\Http\Response;
use b8\View;
@ -13,104 +12,104 @@ use b8\View;
*/
abstract class Controller
{
/**
* @var Request
*/
protected $request;
/**
* @var Request
*/
protected $request;
/**
* @var Response
*/
protected $response;
/**
* @var Response
*/
protected $response;
/**
* @var Config
*/
protected $config;
/**
* @var Config
*/
protected $config;
/**
* @var View
*/
protected $controllerView;
/**
* @var View
*/
protected $controllerView;
/**
* @var View
*/
protected $view;
/**
* @var View
*/
protected $view;
public function __construct(Config $config, Request $request, Response $response)
{
$this->config = $config;
$this->request = $request;
$this->response = $response;
}
public function __construct(Config $config, Request $request, Response $response)
{
$this->config = $config;
$this->request = $request;
$this->response = $response;
}
public function hasAction($name)
{
if (method_exists($this, $name)) {
return true;
}
public function hasAction($name)
{
if (method_exists($this, $name)) {
return true;
}
if (method_exists($this, '__call')) {
return true;
}
if (method_exists($this, '__call')) {
return true;
}
return false;
}
return false;
}
/**
* Handles an action on this controller and returns a Response object.
* @return Response
*/
public function handleAction($action, $actionParams)
{
return call_user_func_array(array($this, $action), $actionParams);
}
/**
* Handles an action on this controller and returns a Response object.
* @return Response
*/
public function handleAction($action, $actionParams)
{
return call_user_func_array([$this, $action], $actionParams);
}
/**
* Initialise the controller.
*/
abstract public function init();
/**
* Initialise the controller.
*/
abstract public function init();
/**
* Get a hash of incoming request parameters ($_GET, $_POST)
*
* @return array
*/
public function getParams()
{
return $this->request->getParams();
}
/**
* Get a hash of incoming request parameters ($_GET, $_POST)
*
* @return array
*/
public function getParams()
{
return $this->request->getParams();
}
/**
* Get a specific incoming request parameter.
*
* @param $key
* @param mixed $default Default return value (if key does not exist)
*
* @return mixed
*/
public function getParam($key, $default = null)
{
return $this->request->getParam($key, $default);
}
/**
* Get a specific incoming request parameter.
*
* @param $key
* @param mixed $default Default return value (if key does not exist)
*
* @return mixed
*/
public function getParam($key, $default = null)
{
return $this->request->getParam($key, $default);
}
/**
* Change the value of an incoming request parameter.
* @param $key
* @param $value
*/
public function setParam($key, $value)
{
return $this->request->setParam($key, $value);
}
/**
* Change the value of an incoming request parameter.
* @param $key
* @param $value
*/
public function setParam($key, $value)
{
return $this->request->setParam($key, $value);
}
/**
* Remove an incoming request parameter.
* @param $key
*/
public function unsetParam($key)
{
return $this->request->unsetParam($key);
}
/**
* Remove an incoming request parameter.
* @param $key
*/
public function unsetParam($key)
{
return $this->request->unsetParam($key);
}
}

View file

@ -1,246 +1,224 @@
<?php
namespace b8\Controller;
use b8\Controller,
b8\Type\RestUser,
b8\Store\Factory,
b8\Exception\HttpException;
b8\Type\RestUser,
b8\Store\Factory,
b8\Exception\HttpException;
class RestController extends Controller
{
const SEARCHTYPE_AND = 'AND';
const SEARCHTYPE_OR = 'OR';
const SEARCHTYPE_AND = 'AND';
const SEARCHTYPE_OR = 'OR';
public $requiresAuthentication = true;
public $updateLastAction = true;
public $requiresAuthentication = true;
public $updateLastAction = true;
/**
* @var \b8\Type\RestUser
*/
protected $activeUser;
protected $where = array();
protected $limit = null;
protected $offset = null;
protected $joins = array();
protected $arrayDepth = 2;
protected $params = null;
protected $order = array();
protected $group = null;
protected $manualJoins = array();
protected $manualWheres = array();
protected $searchType = self::SEARCHTYPE_AND;
protected $_resourceName = null;
protected $_modelName = null;
protected $_tableName = null;
protected $_modelClass = null;
/**
* @var \b8\Type\RestUser
*/
protected $activeUser;
protected $where = [];
protected $limit = null;
protected $offset = null;
protected $joins = [];
protected $arrayDepth = 2;
protected $params = null;
protected $order = [];
protected $group = null;
protected $manualJoins = [];
protected $manualWheres = [];
protected $searchType = self::SEARCHTYPE_AND;
protected $_resourceName = null;
protected $_modelName = null;
protected $_tableName = null;
protected $_modelClass = null;
public function init()
{
}
public function init()
{
}
protected function setControllerView()
{
}
protected function setControllerView()
{
}
protected function setView()
{
}
protected function setView()
{
}
public function handleAction($action, $actionParams)
{
$response = call_user_func_array(array($this, $action), $actionParams);
$this->response->setContent($response);
public function handleAction($action, $actionParams)
{
$response = call_user_func_array([$this, $action], $actionParams);
$this->response->setContent($response);
return $this->response;
}
return $this->response;
}
public function setActiveUser(RestUser $user)
{
$this->activeUser = $user;
}
public function setActiveUser(RestUser $user)
{
$this->activeUser = $user;
}
public function getActiveUser()
{
return $this->activeUser;
}
public function getActiveUser()
{
return $this->activeUser;
}
public function index()
{
if(!$this->activeUser->checkPermission('canRead', $this->_resourceName))
{
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
public function index()
{
if (!$this->activeUser->checkPermission('canRead', $this->_resourceName)) {
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
$this->where = $this->_parseWhere();
$this->limit = is_null($this->limit) ? $this->getParam('limit', 25) : $this->limit;
$this->offset = is_null($this->offset) ? $this->getParam('offset', 0) : $this->offset;
$this->order = is_null($this->order) || !count($this->order) ? $this->getParam('order', array()) : $this->order;
$this->group = is_null($this->group) || !count($this->group) ? $this->getParam('group', null) : $this->group;
$this->searchType = $this->getParam('searchType', self::SEARCHTYPE_AND);
$this->where = $this->_parseWhere();
$this->limit = is_null($this->limit) ? $this->getParam('limit', 25) : $this->limit;
$this->offset = is_null($this->offset) ? $this->getParam('offset', 0) : $this->offset;
$this->order = is_null($this->order) || !count($this->order) ? $this->getParam('order', []) : $this->order;
$this->group = is_null($this->group) || !count($this->group) ? $this->getParam('group', null) : $this->group;
$this->searchType = $this->getParam('searchType', self::SEARCHTYPE_AND);
$store = Factory::getStore($this->_modelName);
$data = $store->getWhere($this->where, $this->limit, $this->offset, $this->joins, $this->order, $this->manualJoins, $this->group, $this->manualWheres, $this->searchType);
$store = Factory::getStore($this->_modelName);
$data = $store->getWhere($this->where, $this->limit, $this->offset, $this->joins, $this->order,
$this->manualJoins, $this->group, $this->manualWheres, $this->searchType);
$rtn = array(
'debug' => array(
'where' => $this->where,
'searchType' => $this->searchType,
),
'limit' => $this->limit,
'offset' => $this->offset,
'total' => $data['count'],
'items' => array()
);
$rtn = [
'debug' => [
'where' => $this->where,
'searchType' => $this->searchType,
],
'limit' => $this->limit,
'offset' => $this->offset,
'total' => $data['count'],
'items' => []
];
foreach($data['items'] as $item)
{
$rtn['items'][] = $item->toArray($this->arrayDepth);
}
foreach ($data['items'] as $item) {
$rtn['items'][] = $item->toArray($this->arrayDepth);
}
return $rtn;
}
return $rtn;
}
/**
*
*/
protected function _parseWhere()
{
$clauses = array(
'fuzzy' => 'like',
'gt' => '>',
'gte' => '>=',
'lt' => '<',
'lte' => '<=',
'neq' => '!=',
'between' => 'between'
);
/**
*
*/
protected function _parseWhere()
{
$clauses = [
'fuzzy' => 'like',
'gt' => '>',
'gte' => '>=',
'lt' => '<',
'lte' => '<=',
'neq' => '!=',
'between' => 'between',
];
$where = $this->getParam('where', array());
$where = array_merge($where, $this->where);
$where = $this->getParam('where', []);
$where = array_merge($where, $this->where);
if(count($where))
{
foreach($where as &$value)
{
if(!is_array($value) || !isset($value['operator']))
{
if(is_array($value) && count($value) == 1)
{
$value = array_shift($value);
}
if (count($where)) {
foreach ($where as &$value) {
if (!is_array($value) || !isset($value['operator'])) {
if (is_array($value) && count($value) == 1) {
$value = array_shift($value);
}
$value = array(
'operator' => '=',
'value' => $value
);
}
}
$value = [
'operator' => '=',
'value' => $value,
];
}
}
foreach($clauses as $clause => $operator)
{
$fields = $this->getParam($clause, array());
foreach ($clauses as $clause => $operator) {
$fields = $this->getParam($clause, []);
if(count($clause))
{
if(!is_array($fields))
{
$fields = array($fields);
}
foreach($fields as $field)
{
if(isset($where[$field]))
{
$where[$field]['operator'] = $operator;
if($operator == 'like')
{
$where[$field]['value'] = str_replace(' ', '%', $where[$field]['value']);
}
}
}
}
}
}
if (count($clause)) {
if (!is_array($fields)) {
$fields = [$fields];
}
foreach ($fields as $field) {
if (isset($where[$field])) {
$where[$field]['operator'] = $operator;
if ($operator == 'like') {
$where[$field]['value'] = str_replace(' ', '%', $where[$field]['value']);
}
}
}
}
}
}
return $where;
}
return $where;
}
public function get($key)
{
if(!$this->activeUser->checkPermission('canRead', $this->_resourceName))
{
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
public function get($key)
{
if (!$this->activeUser->checkPermission('canRead', $this->_resourceName)) {
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
$rtn = Factory::getStore($this->_modelName)->getByPrimaryKey($key);
$rtn = Factory::getStore($this->_modelName)->getByPrimaryKey($key);
if(is_object($rtn) && method_exists($rtn, 'toArray'))
{
$rtn = $rtn->toArray($this->arrayDepth);
}
if (is_object($rtn) && method_exists($rtn, 'toArray')) {
$rtn = $rtn->toArray($this->arrayDepth);
}
return array(strtolower($this->_modelName) => $rtn);
}
return [strtolower($this->_modelName) => $rtn];
}
public function put($key)
{
if(!$this->activeUser->checkPermission('canEdit', $this->_resourceName))
{
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
public function put($key)
{
if (!$this->activeUser->checkPermission('canEdit', $this->_resourceName)) {
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
$store = Factory::getStore($this->_modelName);
$store = Factory::getStore($this->_modelName);
if($obj = $store->getByPrimaryKey($key))
{
$obj->setValues($this->getParams());
$rtn = $store->save($obj);
if ($obj = $store->getByPrimaryKey($key)) {
$obj->setValues($this->getParams());
$rtn = $store->save($obj);
return array(strtolower($this->_modelName) => $rtn->toArray($this->arrayDepth));
}
else
{
return null;
}
}
return [strtolower($this->_modelName) => $rtn->toArray($this->arrayDepth)];
} else {
return null;
}
}
public function post()
{
if(!$this->activeUser->checkPermission('canCreate', $this->_resourceName))
{
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
public function post()
{
if (!$this->activeUser->checkPermission('canCreate', $this->_resourceName)) {
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
$store = Factory::getStore($this->_modelName);
$store = Factory::getStore($this->_modelName);
$modelClass = $this->_modelClass;
$obj = new $modelClass();
$obj->setValues($this->getParams());
$rtn = $store->save($obj);
$modelClass = $this->_modelClass;
$obj = new $modelClass();
$obj->setValues($this->getParams());
$rtn = $store->save($obj);
return array(strtolower($this->_modelName) => $rtn->toArray($this->arrayDepth));
}
return [strtolower($this->_modelName) => $rtn->toArray($this->arrayDepth)];
}
public function delete($key)
{
if(!$this->activeUser->checkPermission('canDelete', $this->_resourceName))
{
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
public function delete($key)
{
if (!$this->activeUser->checkPermission('canDelete', $this->_resourceName)) {
throw new HttpException\ForbiddenException('You do not have permission do this.');
}
$store = Factory::getStore($this->_modelName);
$store = Factory::getStore($this->_modelName);
try
{
if($obj = $store->getByPrimaryKey($key))
{
$store->delete($obj);
return array('deleted' => true);
}
}
catch(\Exception $ex)
{
}
try {
if ($obj = $store->getByPrimaryKey($key)) {
$store->delete($obj);
return ['deleted' => true];
}
} catch (\Exception $ex) {
}
return array('deleted' => false);
}
return ['deleted' => false];
}
}

View file

@ -4,148 +4,142 @@ namespace b8;
class Database extends \PDO
{
protected static $initialised = false;
protected static $servers = array('read' => array(), 'write' => array());
protected static $connections = array('read' => null, 'write' => null);
protected static $details = array();
protected static $lastUsed = array('read' => null, 'write' => null);
protected static $initialised = false;
protected static $servers = ['read' => [], 'write' => []];
protected static $connections = ['read' => null, 'write' => null];
protected static $details = [];
protected static $lastUsed = ['read' => null, 'write' => null];
/**
* @deprecated
*/
public static function setReadServers($read)
{
$config = Config::getInstance();
/**
* @deprecated
*/
public static function setReadServers($read)
{
$config = Config::getInstance();
$settings = $config->get('b8.database', array());
$settings['servers']['read'] = $read;
$config->set('b8.database', $settings);
}
$settings = $config->get('b8.database', []);
$settings['servers']['read'] = $read;
$config->set('b8.database', $settings);
}
/**
* @deprecated
*/
public static function setWriteServers($write)
{
$config = Config::getInstance();
/**
* @deprecated
*/
public static function setWriteServers($write)
{
$config = Config::getInstance();
$settings = $config->get('b8.database', array());
$settings['servers']['write'] = $write;
$config->set('b8.database', $settings);
}
$settings = $config->get('b8.database', []);
$settings['servers']['write'] = $write;
$config->set('b8.database', $settings);
}
/**
* @deprecated
*/
public static function setDetails($database, $username, $password)
{
$config = Config::getInstance();
$settings = $config->get('b8.database', array());
$settings['name'] = $database;
$settings['username'] = $username;
$settings['password'] = $password;
$config->set('b8.database', $settings);
}
/**
* @deprecated
*/
public static function setDetails($database, $username, $password)
{
$config = Config::getInstance();
$settings = $config->get('b8.database', []);
$settings['name'] = $database;
$settings['username'] = $username;
$settings['password'] = $password;
$config->set('b8.database', $settings);
}
protected static function init()
{
$config = Config::getInstance();
$settings = $config->get('b8.database', array());
self::$servers['read'] = $settings['servers']['read'];
self::$servers['write'] = $settings['servers']['write'];
self::$details['db'] = $settings['name'];
self::$details['user'] = $settings['username'];
self::$details['pass'] = $settings['password'];
self::$initialised = true;
}
protected static function init()
{
$config = Config::getInstance();
$settings = $config->get('b8.database', []);
self::$servers['read'] = $settings['servers']['read'];
self::$servers['write'] = $settings['servers']['write'];
self::$details['db'] = $settings['name'];
self::$details['user'] = $settings['username'];
self::$details['pass'] = $settings['password'];
self::$initialised = true;
}
/**
* @param string $type
*
* @return \b8\Database
* @throws \Exception
*/
public static function getConnection($type = 'read')
{
if (!self::$initialised) {
self::init();
}
/**
* @param string $type
*
* @return \b8\Database
* @throws \Exception
*/
public static function getConnection($type = 'read')
{
if (!self::$initialised) {
self::init();
}
// If the connection hasn't been used for 5 minutes, force a reconnection:
if (!is_null(self::$lastUsed[$type]) && (time() - self::$lastUsed[$type]) > 300) {
self::$connections[$type] = null;
}
// If the connection hasn't been used for 5 minutes, force a reconnection:
if (!is_null(self::$lastUsed[$type]) && (time() - self::$lastUsed[$type]) > 300) {
self::$connections[$type] = null;
}
if(is_null(self::$connections[$type])) {
if (is_array(self::$servers[$type])) {
// Shuffle, so we pick a random server:
$servers = self::$servers[$type];
shuffle($servers);
} else {
// Only one server was specified
$servers = array(self::$servers[$type]);
}
if (is_null(self::$connections[$type])) {
if (is_array(self::$servers[$type])) {
// Shuffle, so we pick a random server:
$servers = self::$servers[$type];
shuffle($servers);
} else {
// Only one server was specified
$servers = [self::$servers[$type]];
}
$connection = null;
$connection = null;
// Loop until we get a working connection:
while(count($servers))
{
// Pull the next server:
$server = array_shift($servers);
// Loop until we get a working connection:
while (count($servers)) {
// Pull the next server:
$server = array_shift($servers);
if (stristr($server, ':')) {
list($host, $port) = explode(':', $server);
$server = $host . ';port=' . $port;
}
if (stristr($server, ':')) {
list($host, $port) = explode(':', $server);
$server = $host . ';port=' . $port;
}
// Try to connect:
try
{
$connection = new self('mysql:host=' . $server . ';dbname=' . self::$details['db'],
self::$details['user'],
self::$details['pass'],
array(
\PDO::ATTR_PERSISTENT => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_TIMEOUT => 2,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
));
}
catch(\PDOException $ex)
{
$connection = false;
}
// Try to connect:
try {
$connection = new self('mysql:host=' . $server . ';dbname=' . self::$details['db'],
self::$details['user'],
self::$details['pass'],
[
\PDO::ATTR_PERSISTENT => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_TIMEOUT => 2,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
]);
} catch (\PDOException $ex) {
$connection = false;
}
// Opened a connection? Break the loop:
if($connection)
{
break;
}
}
// Opened a connection? Break the loop:
if ($connection) {
break;
}
}
// No connection? Oh dear.
if(!$connection && $type == 'read')
{
throw new \Exception('Could not connect to any ' . $type . ' servers.');
}
// No connection? Oh dear.
if (!$connection && $type == 'read') {
throw new \Exception('Could not connect to any ' . $type . ' servers.');
}
self::$connections[$type] = $connection;
}
self::$connections[$type] = $connection;
}
self::$lastUsed[$type] = time();
return self::$connections[$type];
}
self::$lastUsed[$type] = time();
return self::$connections[$type];
}
public function getDetails()
{
return self::$details;
}
public function getDetails()
{
return self::$details;
}
public static function reset()
{
self::$connections = array('read' => null, 'write' => null);
self::$lastUsed = array('read' => null, 'write' => null);
self::$connections = ['read' => null, 'write' => null];
self::$lastUsed = ['read' => null, 'write' => null];
self::$initialised = false;
}
}

View file

@ -4,185 +4,164 @@ namespace b8;
class HttpClient
{
protected $_base = '';
protected $_params = array();
protected $_headers = array();
protected $_base = '';
protected $_params = [];
protected $_headers = [];
public function __construct($base = null)
{
$settings = Config::getInstance()->get('b8.http.client', array('base_url' => '', 'params' => array()));
$this->_base = $settings['base_url'];
$this->_params = isset($settings['params']) && is_array($settings['params']) ? $settings['params'] : array();
$this->_headers = array('Content-Type: application/x-www-form-urlencoded');
public function __construct($base = null)
{
$settings = Config::getInstance()->get('b8.http.client', ['base_url' => '', 'params' => []]);
$this->_base = $settings['base_url'];
$this->_params = isset($settings['params']) && is_array($settings['params']) ? $settings['params'] : [];
$this->_headers = ['Content-Type: application/x-www-form-urlencoded'];
if(!is_null($base))
{
$this->_base = $base;
}
}
if (!is_null($base)) {
$this->_base = $base;
}
}
public function setHeaders(array $headers)
{
$this->_headers = $headers;
}
public function setHeaders(array $headers)
{
$this->_headers = $headers;
}
public function request($method, $uri, $params = array())
{
// Clean incoming:
$method = strtoupper($method);
$getParams = $this->_params;
public function request($method, $uri, $params = [])
{
// Clean incoming:
$method = strtoupper($method);
$getParams = $this->_params;
if($method == 'GET' || $method == 'DELETE')
{
$getParams = array_merge($getParams, $params);
}
else
{
$bodyParams = is_array($params) ? http_build_query($params) : $params;
}
if ($method == 'GET' || $method == 'DELETE') {
$getParams = array_merge($getParams, $params);
} else {
$bodyParams = is_array($params) ? http_build_query($params) : $params;
}
$getParams = http_build_query($getParams);
$getParams = http_build_query($getParams);
if(substr($uri, 0, 1) != '/' && !empty($this->_base))
{
$uri = '/' . $uri;
}
if (substr($uri, 0, 1) != '/' && !empty($this->_base)) {
$uri = '/' . $uri;
}
// Build HTTP context array:
$context = array();
$context['http']['user_agent'] = 'b8/1.0';
$context['http']['timeout'] = 30;
$context['http']['method'] = $method;
$context['http']['ignore_errors'] = true;
$context['http']['header'] = implode(PHP_EOL, $this->_headers);
// Build HTTP context array:
$context = [];
$context['http']['user_agent'] = 'b8/1.0';
$context['http']['timeout'] = 30;
$context['http']['method'] = $method;
$context['http']['ignore_errors'] = true;
$context['http']['header'] = implode(PHP_EOL, $this->_headers);
if(in_array($method, array('PUT', 'POST')))
{
$context['http']['content'] = $bodyParams;
}
if (in_array($method, ['PUT', 'POST'])) {
$context['http']['content'] = $bodyParams;
}
$uri .= '?' . $getParams;
$uri .= '?' . $getParams;
$context = stream_context_create($context);
$result = file_get_contents($this->_base . $uri, false, $context);
$context = stream_context_create($context);
$result = file_get_contents($this->_base . $uri, false, $context);
$res = array();
$res['headers'] = $http_response_header;
$res['code'] = (int)preg_replace('/HTTP\/1\.[0-1] ([0-9]+)/', '$1', $res['headers'][0]);
$res['success'] = false;
$res['body'] = $this->_decodeResponse($result);
$res = [];
$res['headers'] = $http_response_header;
$res['code'] = (int)preg_replace('/HTTP\/1\.[0-1] ([0-9]+)/', '$1', $res['headers'][0]);
$res['success'] = false;
$res['body'] = $this->_decodeResponse($result);
if($res['code'] >= 200 && $res['code'] < 300)
{
$res['success'] = true;
}
if ($res['code'] >= 200 && $res['code'] < 300) {
$res['success'] = true;
}
// Handle JSON responses:
foreach($res['headers'] as $header)
{
if(stripos($header, 'Content-Type') !== false || stripos($header, 'b8-Type') !== false)
{
if(stripos($header, 'application/json') !== false)
{
$res['text_body'] = $res['body'];
$res['body'] = json_decode($res['body'], true);
}
}
}
// Handle JSON responses:
foreach ($res['headers'] as $header) {
if (stripos($header, 'Content-Type') !== false || stripos($header, 'b8-Type') !== false) {
if (stripos($header, 'application/json') !== false) {
$res['text_body'] = $res['body'];
$res['body'] = json_decode($res['body'], true);
}
}
}
return $res;
}
return $res;
}
public function get($uri, $params = array())
{
return $this->request('GET', $uri, $params);
}
public function get($uri, $params = [])
{
return $this->request('GET', $uri, $params);
}
public function put($uri, $params = array())
{
return $this->request('PUT', $uri, $params);
}
public function put($uri, $params = [])
{
return $this->request('PUT', $uri, $params);
}
public function post($uri, $params = array())
{
return $this->request('POST', $uri, $params);
}
public function post($uri, $params = [])
{
return $this->request('POST', $uri, $params);
}
public function delete($uri, $params = array())
{
return $this->request('DELETE', $uri, $params);
}
public function delete($uri, $params = [])
{
return $this->request('DELETE', $uri, $params);
}
protected function _decodeResponse($originalResponse)
{
$response = $originalResponse;
$body = '';
protected function _decodeResponse($originalResponse)
{
$response = $originalResponse;
$body = '';
do
{
$line = $this->_readChunk($response);
do {
$line = $this->_readChunk($response);
if($line == PHP_EOL)
{
continue;
}
if ($line == PHP_EOL) {
continue;
}
$length = hexdec(trim($line));
$length = hexdec(trim($line));
if(!is_int($length) || empty($response) || $line === false || $length < 1)
{
break;
}
if (!is_int($length) || empty($response) || $line === false || $length < 1) {
break;
}
do
{
$data = $this->_readChunk($response, $length);
do {
$data = $this->_readChunk($response, $length);
// remove the amount received from the total length on the next loop
// it'll attempt to read that much less data
$length -= strlen($data);
// remove the amount received from the total length on the next loop
// it'll attempt to read that much less data
$length -= strlen($data);
// store in string for later use
$body .= $data;
// store in string for later use
$body .= $data;
// zero or less or end of connection break
if($length <= 0 || empty($response))
{
break;
}
}
while(true);
}
while(true);
// zero or less or end of connection break
if ($length <= 0 || empty($response)) {
break;
}
} while (true);
} while (true);
if(empty($body))
{
$body = $originalResponse;
}
if (empty($body)) {
$body = $originalResponse;
}
return $body;
}
return $body;
}
function _readChunk(&$string, $len = 4096)
{
$rtn = '';
for($i = 0; $i <= $len; $i++)
{
if(empty($string))
{
break;
}
function _readChunk(&$string, $len = 4096)
{
$rtn = '';
for ($i = 0; $i <= $len; $i++) {
if (empty($string)) {
break;
}
$char = $string[0];
$string = substr($string, 1);
$rtn .= $char;
$char = $string[0];
$string = substr($string, 1);
$rtn .= $char;
if($char == PHP_EOL)
{
break;
}
}
if ($char == PHP_EOL) {
break;
}
}
return $rtn;
}
return $rtn;
}
}

View file

@ -53,7 +53,7 @@ class Image
public function doRender($media, $width, $height, $format = 'jpeg')
{
$focal = !empty($media['focal_point']) ? $media['focal_point'] : array(0, 0);
$focal = !empty($media['focal_point']) ? $media['focal_point'] : [0, 0];
$focalX = (int)$focal[0];
$focalY = (int)$focal[1];
@ -136,13 +136,13 @@ class Image
protected function _getQuadrants($x, $y)
{
$rtn = array();
$rtn['top_left'] = array(0, $x / 2, 0, $y / 3);
$rtn['top_right'] = array(($x / 2) + 1, $x, 0, $y / 3);
$rtn['middle_left'] = array(0, $y / 2, ($y / 3)+1, (($y / 3) * 2));
$rtn['middle_right'] = array(($x / 2) + 1, $x, ($y / 3)+1, (($y / 3) * 2));
$rtn['bottom_left'] = array(0, $y / 2, (($y / 3) * 2)+1, $y);
$rtn['bottom_right'] = array(($x / 2) + 1, $x, (($y / 3) * 2)+1, $y);
$rtn = [];
$rtn['top_left'] = [0, $x / 2, 0, $y / 3];
$rtn['top_right'] = [($x / 2) + 1, $x, 0, $y / 3];
$rtn['middle_left'] = [0, $y / 2, ($y / 3)+1, (($y / 3) * 2)];
$rtn['middle_right'] = [($x / 2) + 1, $x, ($y / 3)+1, (($y / 3) * 2)];
$rtn['bottom_left'] = [0, $y / 2, (($y / 3) * 2)+1, $y];
$rtn['bottom_right'] = [($x / 2) + 1, $x, (($y / 3) * 2)+1, $y];
return $rtn;
}

View file

@ -7,202 +7,173 @@ use b8\Cache;
class Model
{
public static $sleepable = array();
protected $getters = array();
protected $setters = array();
protected $data = array();
protected $modified = array();
protected $tableName;
protected $cache;
public static $sleepable = [];
protected $getters = [];
protected $setters = [];
protected $data = [];
protected $modified = [];
protected $tableName;
protected $cache;
public function __construct($initialData = array())
{
if(is_array($initialData))
{
$this->data = array_merge($this->data, $initialData);
}
public function __construct($initialData = [])
{
if (is_array($initialData)) {
$this->data = array_merge($this->data, $initialData);
}
$this->cache = Cache::getCache(Cache::TYPE_REQUEST);
}
$this->cache = Cache::getCache(Cache::TYPE_REQUEST);
}
public function getTableName()
{
return $this->tableName;
}
public function getTableName()
{
return $this->tableName;
}
public function toArray($depth = 2, $currentDepth = 0)
{
if(isset(static::$sleepable) && is_array(static::$sleepable) && count(static::$sleepable))
{
$sleepable = static::$sleepable;
}
else
{
$sleepable = array_keys($this->getters);
}
public function toArray($depth = 2, $currentDepth = 0)
{
if (isset(static::$sleepable) && is_array(static::$sleepable) && count(static::$sleepable)) {
$sleepable = static::$sleepable;
} else {
$sleepable = array_keys($this->getters);
}
$rtn = array();
foreach($sleepable as $property)
{
$rtn[$property] = $this->_propertyToArray($property, $currentDepth, $depth);
}
$rtn = [];
foreach ($sleepable as $property) {
$rtn[$property] = $this->_propertyToArray($property, $currentDepth, $depth);
}
return $rtn;
}
return $rtn;
}
protected function _propertyToArray($property, $currentDepth, $depth)
{
$rtn = null;
protected function _propertyToArray($property, $currentDepth, $depth)
{
$rtn = null;
if(array_key_exists($property, $this->getters))
{
$method = $this->getters[$property];
$rtn = $this->{$method}();
if (array_key_exists($property, $this->getters)) {
$method = $this->getters[$property];
$rtn = $this->{$method}();
if(is_object($rtn) || is_array($rtn))
{
$rtn = ($depth > $currentDepth) ? $this->_valueToArray($rtn, $currentDepth, $depth) : null;
}
}
if (is_object($rtn) || is_array($rtn)) {
$rtn = ($depth > $currentDepth) ? $this->_valueToArray($rtn, $currentDepth, $depth) : null;
}
}
return $rtn;
}
return $rtn;
}
protected function _valueToArray($value, $currentDepth, $depth)
{
$rtn = null;
if(!is_null($value))
{
if(is_object($value) && method_exists($value, 'toArray'))
{
$rtn = $value->toArray($depth, $currentDepth + 1);
}
elseif(is_array($value))
{
$childArray = array();
protected function _valueToArray($value, $currentDepth, $depth)
{
$rtn = null;
if (!is_null($value)) {
if (is_object($value) && method_exists($value, 'toArray')) {
$rtn = $value->toArray($depth, $currentDepth + 1);
} elseif (is_array($value)) {
$childArray = [];
foreach($value as $k => $v)
{
$childArray[$k] = $this->_valueToArray($v, $currentDepth + 1, $depth);
}
foreach ($value as $k => $v) {
$childArray[$k] = $this->_valueToArray($v, $currentDepth + 1, $depth);
}
$rtn = $childArray;
}
else
{
$rtn = (is_string($value) && !mb_check_encoding($value, 'UTF-8')) ? mb_convert_encoding($value, 'UTF-8') : $value;
}
}
$rtn = $childArray;
} else {
$rtn = (is_string($value) && !mb_check_encoding($value, 'UTF-8')) ? mb_convert_encoding($value,
'UTF-8') : $value;
}
}
return $rtn;
}
return $rtn;
}
public function getDataArray()
{
return $this->data;
}
public function getDataArray()
{
return $this->data;
}
public function getModified()
{
return $this->modified;
}
public function getModified()
{
return $this->modified;
}
public function setValues(array $values)
{
foreach($values as $key => $value)
{
if(isset($this->setters[$key]))
{
$func = $this->setters[$key];
public function setValues(array $values)
{
foreach ($values as $key => $value) {
if (isset($this->setters[$key])) {
$func = $this->setters[$key];
if($value === 'null')
{
$value = null;
}
elseif($value === 'true')
{
$value = true;
}
elseif($value === 'false')
{
$value = false;
}
if ($value === 'null') {
$value = null;
} elseif ($value === 'true') {
$value = true;
} elseif ($value === 'false') {
$value = false;
}
$this->{$func}($value);
}
}
}
$this->{$func}($value);
}
}
}
protected function _setModified($column)
{
$this->modified[$column] = $column;
}
protected function _setModified($column)
{
$this->modified[$column] = $column;
}
//----------------
// Validation
//----------------
protected function _validateString($name, $value)
{
if(!is_string($value) && !is_null($value))
{
throw new HttpException\ValidationException($name . ' must be a string.');
}
}
//----------------
// Validation
//----------------
protected function _validateString($name, $value)
{
if (!is_string($value) && !is_null($value)) {
throw new HttpException\ValidationException($name . ' must be a string.');
}
}
protected function _validateInt($name, &$value)
{
if(is_bool($value))
{
$value = $value ? 1 : 0;
}
protected function _validateInt($name, &$value)
{
if (is_bool($value)) {
$value = $value ? 1 : 0;
}
if(!is_numeric($value) && !is_null($value))
{
throw new HttpException\ValidationException($name . ' must be an integer.');
}
if (!is_numeric($value) && !is_null($value)) {
throw new HttpException\ValidationException($name . ' must be an integer.');
}
if(!is_int($value) && !is_null($value))
{
$value = (int)$value;
}
}
if (!is_int($value) && !is_null($value)) {
$value = (int)$value;
}
}
protected function _validateFloat($name, &$value)
{
if(!is_numeric($value) && !is_null($value))
{
throw new HttpException\ValidationException($name . ' must be a float.');
}
protected function _validateFloat($name, &$value)
{
if (!is_numeric($value) && !is_null($value)) {
throw new HttpException\ValidationException($name . ' must be a float.');
}
if(!is_float($value) && !is_null($value))
{
$value = (float)$value;
}
}
if (!is_float($value) && !is_null($value)) {
$value = (float)$value;
}
}
protected function _validateDate($name, &$value)
{
if(is_string($value))
{
$value = empty($value) ? null : new \DateTime($value);
}
protected function _validateDate($name, &$value)
{
if (is_string($value)) {
$value = empty($value) ? null : new \DateTime($value);
}
if((!is_object($value) || !($value instanceof \DateTime)) && !is_null($value))
{
throw new HttpException\ValidationException($name . ' must be a date object.');
}
if ((!is_object($value) || !($value instanceof \DateTime)) && !is_null($value)) {
throw new HttpException\ValidationException($name . ' must be a date object.');
}
$value = empty($value) ? null : $value->format('Y-m-d H:i:s');
}
$value = empty($value) ? null : $value->format('Y-m-d H:i:s');
}
protected function _validateNotNull($name, &$value)
{
if(is_null($value))
{
throw new HttpException\ValidationException($name . ' must not be null.');
}
}
protected function _validateNotNull($name, &$value)
{
if (is_null($value)) {
throw new HttpException\ValidationException($name . ' must not be null.');
}
}
public function __get($key)
{

View file

@ -1,272 +1,222 @@
<?php
namespace b8;
use b8\Exception\HttpException;
use b8\Database,
b8\Model;
use b8\Database;
abstract class Store
{
protected $modelName = null;
protected $tableName = null;
protected $primaryKey = null;
protected $modelName = null;
protected $tableName = null;
protected $primaryKey = null;
/**
* @return \b8\Model
*/
abstract public function getByPrimaryKey($key, $useConnection = 'read');
/**
* @return \b8\Model
*/
abstract public function getByPrimaryKey($key, $useConnection = 'read');
public function getWhere($where = array(), $limit = 25, $offset = 0, $joins = array(), $order = array(), $manualJoins = array(), $group = null, $manualWheres = array(), $whereType = 'AND')
{
$query = 'SELECT ' . $this->tableName . '.* FROM ' . $this->tableName;
$countQuery = 'SELECT COUNT(*) AS cnt FROM ' . $this->tableName;
public function getWhere(
$where = [],
$limit = 25,
$offset = 0,
$joins = [],
$order = [],
$manualJoins = [],
$group = null,
$manualWheres = [],
$whereType = 'AND'
) {
$query = 'SELECT ' . $this->tableName . '.* FROM ' . $this->tableName;
$countQuery = 'SELECT COUNT(*) AS cnt FROM ' . $this->tableName;
$wheres = array();
$params = array();
foreach($where as $key => $value)
{
$key = $this->fieldCheck($key);
$wheres = [];
$params = [];
foreach ($where as $key => $value) {
$key = $this->fieldCheck($key);
if(!is_array($value))
{
$params[] = $value;
$wheres[] = $key . ' = ?';
}
else
{
if(isset($value['operator']))
{
if(is_array($value['value']))
{
if($value['operator'] == 'between')
{
$params[] = $value['value'][0];
$params[] = $value['value'][1];
$wheres[] = $key . ' BETWEEN ? AND ?';
}
elseif($value['operator'] == 'IN')
{
$in = array();
if (!is_array($value)) {
$params[] = $value;
$wheres[] = $key . ' = ?';
} else {
if (isset($value['operator'])) {
if (is_array($value['value'])) {
if ($value['operator'] == 'between') {
$params[] = $value['value'][0];
$params[] = $value['value'][1];
$wheres[] = $key . ' BETWEEN ? AND ?';
} elseif ($value['operator'] == 'IN') {
$in = [];
foreach($value['value'] as $item)
{
$params[] = $item;
$in[] = '?';
}
foreach ($value['value'] as $item) {
$params[] = $item;
$in[] = '?';
}
$wheres[] = $key . ' IN (' . implode(', ', $in) . ') ';
}
else
{
$ors = array();
foreach($value['value'] as $item)
{
if($item == 'null')
{
switch($value['operator'])
{
case '!=':
$ors[] = $key . ' IS NOT NULL';
break;
$wheres[] = $key . ' IN (' . implode(', ', $in) . ') ';
} else {
$ors = [];
foreach ($value['value'] as $item) {
if ($item == 'null') {
switch ($value['operator']) {
case '!=':
$ors[] = $key . ' IS NOT NULL';
break;
case '==':
default:
$ors[] = $key . ' IS NULL';
break;
}
}
else
{
$params[] = $item;
$ors[] = $this->fieldCheck($key) . ' ' . $value['operator'] . ' ?';
}
}
$wheres[] = '(' . implode(' OR ', $ors) . ')';
}
}
else
{
if($value['operator'] == 'like')
{
$params[] = '%' . $value['value'] . '%';
$wheres[] = $key . ' ' . $value['operator'] . ' ?';
}
else
{
if($value['value'] === 'null')
{
switch($value['operator'])
{
case '!=':
$wheres[] = $key . ' IS NOT NULL';
break;
case '==':
default:
$ors[] = $key . ' IS NULL';
break;
}
} else {
$params[] = $item;
$ors[] = $this->fieldCheck($key) . ' ' . $value['operator'] . ' ?';
}
}
$wheres[] = '(' . implode(' OR ', $ors) . ')';
}
} else {
if ($value['operator'] == 'like') {
$params[] = '%' . $value['value'] . '%';
$wheres[] = $key . ' ' . $value['operator'] . ' ?';
} else {
if ($value['value'] === 'null') {
switch ($value['operator']) {
case '!=':
$wheres[] = $key . ' IS NOT NULL';
break;
case '==':
default:
$wheres[] = $key . ' IS NULL';
break;
}
}
else
{
$params[] = $value['value'];
$wheres[] = $key . ' ' . $value['operator'] . ' ?';
}
}
}
}
else
{
$wheres[] = $key . ' IN (' . implode(', ', array_map(array(Database::getConnection('read'), 'quote'), $value)) . ')';
}
}
}
case '==':
default:
$wheres[] = $key . ' IS NULL';
break;
}
} else {
$params[] = $value['value'];
$wheres[] = $key . ' ' . $value['operator'] . ' ?';
}
}
}
} else {
$wheres[] = $key . ' IN (' . implode(', ',
array_map([Database::getConnection('read'), 'quote'], $value)) . ')';
}
}
}
if(count($joins))
{
foreach($joins as $table => $join)
{
$query .= ' LEFT JOIN ' . $table . ' ' . $join['alias'] . ' ON ' . $join['on'] . ' ';
$countQuery .= ' LEFT JOIN ' . $table . ' ' . $join['alias'] . ' ON ' . $join['on'] . ' ';
}
}
if (count($joins)) {
foreach ($joins as $table => $join) {
$query .= ' LEFT JOIN ' . $table . ' ' . $join['alias'] . ' ON ' . $join['on'] . ' ';
$countQuery .= ' LEFT JOIN ' . $table . ' ' . $join['alias'] . ' ON ' . $join['on'] . ' ';
}
}
if(count($manualJoins))
{
foreach($manualJoins as $join)
{
$query .= ' ' . $join . ' ';
$countQuery .= ' ' . $join . ' ';
}
}
if (count($manualJoins)) {
foreach ($manualJoins as $join) {
$query .= ' ' . $join . ' ';
$countQuery .= ' ' . $join . ' ';
}
}
$hasWhere = false;
if(count($wheres))
{
$hasWhere = true;
$query .= ' WHERE (' . implode(' ' . $whereType . ' ', $wheres) . ')';
$countQuery .= ' WHERE (' . implode(' ' . $whereType . ' ', $wheres) . ')';
}
$hasWhere = false;
if (count($wheres)) {
$hasWhere = true;
$query .= ' WHERE (' . implode(' ' . $whereType . ' ', $wheres) . ')';
$countQuery .= ' WHERE (' . implode(' ' . $whereType . ' ', $wheres) . ')';
}
if(count($manualWheres))
{
foreach($manualWheres as $where)
{
if(!$hasWhere)
{
$hasWhere = true;
$query .= ' WHERE ';
$countQuery .= ' WHERE ';
}
else
{
$query .= ' ' . $where['type'] . ' ';
$countQuery .= ' ' . $where['type'] . ' ';
}
if (count($manualWheres)) {
foreach ($manualWheres as $where) {
if (!$hasWhere) {
$hasWhere = true;
$query .= ' WHERE ';
$countQuery .= ' WHERE ';
} else {
$query .= ' ' . $where['type'] . ' ';
$countQuery .= ' ' . $where['type'] . ' ';
}
$query .= ' ' . $where['query'];
$countQuery .= ' ' . $where['query'];
$query .= ' ' . $where['query'];
$countQuery .= ' ' . $where['query'];
if(isset($where['params']))
{
foreach($where['params'] as $param)
{
$params[] = $param;
}
}
}
}
if (isset($where['params'])) {
foreach ($where['params'] as $param) {
$params[] = $param;
}
}
}
}
if(!is_null($group))
{
$query .= ' GROUP BY ' . $group . ' ';
}
if (!is_null($group)) {
$query .= ' GROUP BY ' . $group . ' ';
}
if(count($order))
{
$orders = array();
if(is_string($order) && $order == 'rand')
{
$query .= ' ORDER BY RAND() ';
}
else
{
foreach($order as $key => $value)
{
$orders[] = $this->fieldCheck($key) . ' ' . $value;
}
if (count($order)) {
$orders = [];
if (is_string($order) && $order == 'rand') {
$query .= ' ORDER BY RAND() ';
} else {
foreach ($order as $key => $value) {
$orders[] = $this->fieldCheck($key) . ' ' . $value;
}
$query .= ' ORDER BY ' . implode(', ', $orders);
}
}
$query .= ' ORDER BY ' . implode(', ', $orders);
}
}
if($limit)
{
$query .= ' LIMIT ' . $limit;
}
if ($limit) {
$query .= ' LIMIT ' . $limit;
}
if($offset)
{
$query .= ' OFFSET ' . $offset;
}
if ($offset) {
$query .= ' OFFSET ' . $offset;
}
try
{
$stmt = Database::getConnection('read')->prepare($countQuery);
$stmt->execute($params);
$res = $stmt->fetch(\PDO::FETCH_ASSOC);
$count = (int)$res['cnt'];
}
catch(\PDOException $ex)
{
$count = 0;
}
try {
$stmt = Database::getConnection('read')->prepare($countQuery);
$stmt->execute($params);
$res = $stmt->fetch(\PDO::FETCH_ASSOC);
$count = (int)$res['cnt'];
} catch (\PDOException $ex) {
$count = 0;
}
try
{
$stmt = Database::getConnection('read')->prepare($query);
$stmt->execute($params);
$res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$rtn = array();
try {
$stmt = Database::getConnection('read')->prepare($query);
$stmt->execute($params);
$res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$rtn = [];
foreach($res as $data)
{
$rtn[] = new $this->modelName($data);
}
foreach ($res as $data) {
$rtn[] = new $this->modelName($data);
}
return array('items' => $rtn, 'count' => $count);
}
catch(\PDOException $ex)
{
throw $ex;
}
}
return ['items' => $rtn, 'count' => $count];
} catch (\PDOException $ex) {
throw $ex;
}
}
public function save(Model $obj, $saveAllColumns = false)
{
if(!isset($this->primaryKey))
{
throw new HttpException\BadRequestException('Save not implemented for this store.');
}
public function save(Model $obj, $saveAllColumns = false)
{
if (!isset($this->primaryKey)) {
throw new HttpException\BadRequestException('Save not implemented for this store.');
}
if(!($obj instanceof $this->modelName))
{
throw new HttpException\BadRequestException(get_class($obj) . ' is an invalid model type for this store.');
}
if (!($obj instanceof $this->modelName)) {
throw new HttpException\BadRequestException(get_class($obj) . ' is an invalid model type for this store.');
}
$data = $obj->getDataArray();
if(isset($data[$this->primaryKey]))
{
$rtn = $this->saveByUpdate($obj, $saveAllColumns);
}
else
{
$rtn = $this->saveByInsert($obj, $saveAllColumns);
}
if (isset($data[$this->primaryKey])) {
$rtn = $this->saveByUpdate($obj, $saveAllColumns);
} else {
$rtn = $this->saveByInsert($obj, $saveAllColumns);
}
return $rtn;
}
return $rtn;
}
public function saveByUpdate(Model $obj, $saveAllColumns = false)
{
@ -274,23 +224,18 @@ abstract class Store
$data = $obj->getDataArray();
$modified = ($saveAllColumns) ? array_keys($data) : $obj->getModified();
$updates = array();
$update_params = array();
foreach($modified as $key)
{
$updates[] = $key . ' = :' . $key;
$update_params[] = array($key, $data[$key]);
$updates = [];
$update_params = [];
foreach ($modified as $key) {
$updates[] = $key . ' = :' . $key;
$update_params[] = [$key, $data[$key]];
}
if(count($updates))
{
$qs = 'UPDATE ' . $this->tableName . '
SET ' . implode(', ', $updates) . '
WHERE ' . $this->primaryKey . ' = :primaryKey';
$q = Database::getConnection('write')->prepare($qs);
if (count($updates)) {
$qs = 'UPDATE ' . $this->tableName . 'SET ' . implode(', ', $updates) . 'WHERE ' . $this->primaryKey . ' = :primaryKey';
$q = Database::getConnection('write')->prepare($qs);
foreach($update_params as $update_param)
{
foreach ($update_params as $update_param) {
$q->bindValue(':' . $update_param[0], $update_param[1]);
}
@ -298,9 +243,7 @@ abstract class Store
$q->execute();
$rtn = $this->getByPrimaryKey($data[$this->primaryKey], 'write');
}
else
{
} else {
$rtn = $obj;
}
@ -313,23 +256,21 @@ abstract class Store
$data = $obj->getDataArray();
$modified = ($saveAllColumns) ? array_keys($data) : $obj->getModified();
$cols = array();
$values = array();
$qParams = array();
foreach($modified as $key)
{
$cols[] = $key;
$values[] = ':' . $key;
$cols = [];
$values = [];
$qParams = [];
foreach ($modified as $key) {
$cols[] = $key;
$values[] = ':' . $key;
$qParams[':' . $key] = $data[$key];
}
if(count($cols))
{
$qs = 'INSERT INTO ' . $this->tableName . ' (' . implode(', ', $cols) . ') VALUES (' . implode(', ', $values) . ')';
$q = Database::getConnection('write')->prepare($qs);
if (count($cols)) {
$qs = 'INSERT INTO ' . $this->tableName . ' (' . implode(', ', $cols) . ') VALUES (' . implode(', ',
$values) . ')';
$q = Database::getConnection('write')->prepare($qs);
if($q->execute($qParams))
{
if ($q->execute($qParams)) {
$id = !empty($data[$this->primaryKey]) ? $data[$this->primaryKey] : Database::getConnection('write')->lastInsertId();
$rtn = $this->getByPrimaryKey($id, 'write');
}
@ -338,42 +279,38 @@ abstract class Store
return $rtn;
}
public function delete(Model $obj)
{
if(!isset($this->primaryKey))
{
throw new HttpException\BadRequestException('Delete not implemented for this store.');
}
public function delete(Model $obj)
{
if (!isset($this->primaryKey)) {
throw new HttpException\BadRequestException('Delete not implemented for this store.');
}
if(!($obj instanceof $this->modelName))
{
throw new HttpException\BadRequestException(get_class($obj) . ' is an invalid model type for this store.');
}
if (!($obj instanceof $this->modelName)) {
throw new HttpException\BadRequestException(get_class($obj) . ' is an invalid model type for this store.');
}
$data = $obj->getDataArray();
$data = $obj->getDataArray();
$q = Database::getConnection('write')->prepare('DELETE FROM ' . $this->tableName . ' WHERE ' . $this->primaryKey . ' = :primaryKey');
$q->bindValue(':primaryKey', $data[$this->primaryKey]);
$q->execute();
$q = Database::getConnection('write')->prepare('DELETE FROM ' . $this->tableName . ' WHERE ' . $this->primaryKey . ' = :primaryKey');
$q->bindValue(':primaryKey', $data[$this->primaryKey]);
$q->execute();
return true;
}
return true;
}
/**
*
*/
protected function fieldCheck($field)
{
if(empty($field))
{
throw new HttpException('You cannot have an empty field name.');
}
/**
*
*/
protected function fieldCheck($field)
{
if (empty($field)) {
throw new HttpException('You cannot have an empty field name.');
}
if(strpos($field, '.') === false)
{
return $this->tableName . '.' . $field;
}
if (strpos($field, '.') === false) {
return $this->tableName . '.' . $field;
}
return $field;
}
return $field;
}
}

View file

@ -1,86 +1,84 @@
<?php
namespace b8;
use b8\Exception\HttpException;
class View
{
protected $_vars = array();
protected static $_helpers = array();
protected $_vars = [];
protected static $_helpers = [];
protected static $extension = 'phtml';
public function __construct($file, $path = null)
{
if (!self::exists($file, $path)) {
throw new \Exception('View file does not exist: ' . $file);
}
public function __construct($file, $path = null)
{
if (!self::exists($file, $path)) {
throw new \Exception('View file does not exist: ' . $file);
}
$this->viewFile = self::getViewFile($file, $path);
}
$this->viewFile = self::getViewFile($file, $path);
}
protected static function getViewFile($file, $path = null)
{
$viewPath = is_null($path) ? Config::getInstance()->get('b8.view.path') : $path;
$fullPath = $viewPath . $file . '.' . static::$extension;
protected static function getViewFile($file, $path = null)
{
$viewPath = is_null($path) ? Config::getInstance()->get('b8.view.path') : $path;
$fullPath = $viewPath . $file . '.' . static::$extension;
return $fullPath;
}
}
public static function exists($file, $path = null)
{
if (!file_exists(self::getViewFile($file, $path))) {
return false;
}
public static function exists($file, $path = null)
{
if (!file_exists(self::getViewFile($file, $path))) {
return false;
}
return true;
}
return true;
}
public function __isset($var)
{
return isset($this->_vars[$var]);
}
public function __isset($var)
{
return isset($this->_vars[$var]);
}
public function __get($var)
{
return $this->_vars[$var];
}
public function __get($var)
{
return $this->_vars[$var];
}
public function __set($var, $val)
{
$this->_vars[$var] = $val;
}
public function __set($var, $val)
{
$this->_vars[$var] = $val;
}
public function __call($method, $params = array())
{
if(!isset(self::$_helpers[$method]))
{
$class = '\\' . Config::getInstance()->get('b8.app.namespace') . '\\Helper\\' . $method;
public function __call($method, $params = [])
{
if (!isset(self::$_helpers[$method])) {
$class = '\\' . Config::getInstance()->get('b8.app.namespace') . '\\Helper\\' . $method;
if(!class_exists($class))
{
$class = '\\b8\\View\\Helper\\' . $method;
}
if (!class_exists($class)) {
$class = '\\b8\\View\\Helper\\' . $method;
}
if(!class_exists($class))
{
throw new HttpException('Helper class does not exist: ' . $class);
}
if (!class_exists($class)) {
throw new HttpException('Helper class does not exist: ' . $class);
}
self::$_helpers[$method] = new $class();
}
self::$_helpers[$method] = new $class();
}
return self::$_helpers[$method];
}
return self::$_helpers[$method];
}
public function render()
{
extract($this->_vars);
public function render()
{
extract($this->_vars);
ob_start();
require($this->viewFile);
$html = ob_get_contents();
ob_end_clean();
ob_start();
require($this->viewFile);
$html = ob_get_contents();
ob_end_clean();
return $html;
}
}
return $html;
}
}