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/ * @link https://www.phptesting.org/
*/ */
return array( return [
/** Loggers attached to every command */ /** Loggers attached to every command */
"_" => function() { "_" => function() {
return array( return [
new \Monolog\Handler\StreamHandler(__DIR__ . DIRECTORY_SEPARATOR . 'errors.log', \Monolog\Logger::ERROR), new \Monolog\Handler\StreamHandler(__DIR__ . DIRECTORY_SEPARATOR . 'errors.log', \Monolog\Logger::ERROR),
); ];
}, },
/** Loggers for the RunCommand */ /** Loggers for the RunCommand */
'RunCommand' => function() { 'RunCommand' => function() {
return array( return [
new \Monolog\Handler\RotatingFileHandler(__DIR__ . DIRECTORY_SEPARATOR . 'everything', 3, \Monolog\Logger::DEBUG), 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'); $writeServers = $config->get('b8.database.servers.write');
if (!is_array($writeServers)) { if (!is_array($writeServers)) {
$writeServers = array($writeServers); $writeServers = [$writeServers];
} }
$conf = array( $conf = [
'paths' => array( 'paths' => [
'migrations' => 'PHPCI/Migrations', 'migrations' => 'PHPCI/Migrations',
), ],
'environments' => [
'environments' => array(
'default_migration_table' => 'migration', 'default_migration_table' => 'migration',
'default_database' => 'phpci', 'default_database' => 'phpci',
'phpci' => array( 'phpci' => [
'adapter' => 'mysql', 'adapter' => 'mysql',
'host' => end($writeServers), 'host' => end($writeServers),
'name' => $config->get('b8.database.name'), 'name' => $config->get('b8.database.name'),
'user' => $config->get('b8.database.username'), 'user' => $config->get('b8.database.username'),
'pass' => $config->get('b8.database.password'), 'pass' => $config->get('b8.database.password'),
), ],
), ],
); ];
return $conf; return $conf;

View file

@ -4,10 +4,10 @@ return function (PHPCI\Plugin\Util\Factory $factory) {
$factory->registerResource( $factory->registerResource(
// This function will be called when the resource is needed. // This function will be called when the resource is needed.
function() { function() {
return array( return [
'Foo' => "Stuff", 'Foo' => "Stuff",
'Bar' => "More Stuff" 'Bar' => "More Stuff"
); ];
}, },
// In addition to the function for building the resource the system // 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: // Load configuration if present:
$conf = array(); $conf = [];
$conf['b8']['app']['namespace'] = 'PHPCI'; $conf['b8']['app']['namespace'] = 'PHPCI';
$conf['b8']['app']['default_controller'] = 'Home'; $conf['b8']['app']['default_controller'] = 'Home';
$conf['b8']['view']['path'] = dirname(__FILE__) . '/src/PHPCI/View/'; $conf['b8']['view']['path'] = dirname(__FILE__) . '/src/PHPCI/View/';
$conf['using_custom_file'] = $usingCustomConfigFile; $conf['using_custom_file'] = $usingCustomConfigFile;
$config = new b8\Config($conf); $config = new b8\Config($conf);

View file

@ -9,21 +9,25 @@ namespace b8;
class Cache class Cache
{ {
const TYPE_APC = 'ApcCache'; const TYPE_APC = 'ApcCache';
const TYPE_REQUEST = 'RequestCache'; const TYPE_REQUEST = 'RequestCache';
protected static $instance = array(); protected static $instance = [];
/** /**
* Get a cache object of a specified type. * Get a cache object of a specified type.
*/ *
public static function getCache($type = self::TYPE_REQUEST) * @param string $type
{ *
if (!isset(self::$instance[$type])) { * @return mixed
$class = '\\b8\\Cache\\' . $type; */
self::$instance[$type] = new $class(); public static function getCache($type = self::TYPE_REQUEST)
} {
if (!isset(self::$instance[$type])) {
return 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; $rtn = false;
$apcCli = ini_get('apc.enable_cli'); $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; $rtn = true;
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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