Skip to content

Commit

Permalink
Merge pull request #407 from AntonShevchuk/master
Browse files Browse the repository at this point in the history
Refactoring. Season 01
  • Loading branch information
Anton committed Apr 13, 2017
2 parents aef2edf + 1dd2879 commit 4402384
Show file tree
Hide file tree
Showing 20 changed files with 172 additions and 173 deletions.
13 changes: 8 additions & 5 deletions src/Application/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ public function init($environment = 'production')
$this->environment = $environment;

try {
// first log message
Logger::info('app:init');

// initial default helper path
$this->addHelperPath(__DIR__ . '/Helper/');

// init Config
$this->initConfig();

// first log message
Logger::info('app:init');

// init Session, start inside class (if needed)
Session::getInstance();

Expand Down Expand Up @@ -288,7 +288,7 @@ protected function preProcess()
}

// switch to JSON response based on Accept header
if (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON) {
if (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON) {
$this->layoutFlag = false;
Response::switchType('JSON');
}
Expand Down Expand Up @@ -383,8 +383,11 @@ protected function preDispatch($module, $controller, $params = [])
*
* @param string $module
* @param string $controller
* @param array $params
* @param array $params
* @return Controller
* @throws \Bluz\Application\Exception\ForbiddenException
* @throws \Bluz\Application\Exception\NotAllowedException
* @throws \Bluz\Application\Exception\NotAcceptableException
*/
protected function doDispatch($module, $controller, $params = [])
{
Expand Down
12 changes: 1 addition & 11 deletions src/Application/Helper/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,9 @@ function ($exception) {
Response::removeHeaders();
Response::clearBody();

// cast to valid HTTP error code
// 500 - Internal Server Error
$statusCode = (
StatusCode::CONTINUE <= $exception->getCode()
&& $exception->getCode() < 600
)
? $exception->getCode()
: StatusCode::INTERNAL_SERVER_ERROR;
Response::setStatusCode($statusCode);

$module = Router::getErrorModule();
$controller = Router::getErrorController();
$params = ['code' => $exception->getCode(), 'message' => $exception->getMessage()];
$params = ['code' => $exception->getCode(), 'exception' => $exception];

return $this->dispatch($module, $controller, $params);
};
4 changes: 2 additions & 2 deletions src/Config/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ public function getModuleData($module, $section = null)

if (!is_null($section)) {
return $this->modules[$module][$section] ?? null;
} else {
return $this->modules[$module];
}

return $this->modules[$module];
}
}
60 changes: 30 additions & 30 deletions src/Controller/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ class Controller implements \JsonSerializable
protected $file;

/**
* @var Reflection
* @var Meta
*/
protected $reflection;
protected $meta;

/**
* @var Data
Expand Down Expand Up @@ -105,7 +105,7 @@ public function __construct($module, $controller)
*/
public function checkPrivilege()
{
if ($privilege = $this->getReflection()->getPrivilege()) {
if ($privilege = $this->getMeta()->getPrivilege()) {
if (!Acl::isAllowed($this->module, $privilege)) {
throw new ForbiddenException;
}
Expand All @@ -119,10 +119,9 @@ public function checkPrivilege()
*/
public function checkMethod()
{
if ($this->getReflection()->getMethod()
&& !in_array(Request::getMethod(), $this->getReflection()->getMethod())) {
Response::setHeader('Allow', join(',', $this->getReflection()->getMethod()));
throw new NotAllowedException;
if ($this->getMeta()->getMethod()
&& !in_array(Request::getMethod(), $this->getMeta()->getMethod())) {
throw new NotAllowedException(implode(',', $this->getMeta()->getMethod()));
}
}

Expand All @@ -134,11 +133,11 @@ public function checkMethod()
public function checkAccept()
{
// all ok for CLI
if (PHP_SAPI == 'cli') {
if (PHP_SAPI === 'cli') {
return;
}

$allowAccept = $this->getReflection()->getAccept();
$allowAccept = $this->getMeta()->getAccept();

// some controllers hasn't @accept tag
if (!$allowAccept) {
Expand Down Expand Up @@ -181,18 +180,18 @@ public function checkAccept()
* @return Data
* @throws ControllerException
*/
public function run($params = []) // : array
public function run(array $params = [])
{
// initial variables for use inside controller
$module = $this->module;
$controller = $this->controller;

$cacheKey = 'data.' . Cache::prepare($this->module . '.' . $this->controller)
. '.' . md5(http_build_query($params));
$cacheKey = "data.$module.$controller." . md5(http_build_query($params));

$cacheTime = $this->getReflection()->getCache();
$cacheTime = $this->getMeta()->getCache();

if ($cacheTime && $cached = Cache::get($cacheKey)) {
$this->data = $cached;
return $cached;
}

Expand All @@ -206,7 +205,7 @@ public function run($params = []) // : array
}

// process params
$params = $this->getReflection()->params($params);
$params = $this->getMeta()->params($params);

// call Closure or Controller
$result = $controllerClosure(...$params);
Expand Down Expand Up @@ -236,7 +235,7 @@ public function run($params = []) // : array
$cacheKey,
$this->getData(),
$cacheTime,
['system', 'data', Cache::prepare($this->module . '.' . $this->controller)]
['system', 'data', Cache::prepare("$module.$controller")]
);
}

Expand All @@ -252,7 +251,7 @@ public function run($params = []) // : array
protected function setFile()
{
$path = Application::getInstance()->getPath();
$file = $path . '/modules/' . $this->module . '/controllers/' . $this->controller . '.php';
$file = "$path/modules/{$this->module}/controllers/{$this->controller}.php";

if (!file_exists($file)) {
throw new ControllerException("Controller file not found '{$this->module}/{$this->controller}'", 404);
Expand All @@ -278,34 +277,35 @@ protected function getFile() // : string
* @return void
* @throws \Bluz\Common\Exception\ComponentException
*/
protected function setReflection()
protected function setMeta()
{
// cache for reflection data
$cacheKey = 'reflection.' . Cache::prepare($this->module . '.' . $this->controller);
if (!$reflection = Cache::get($cacheKey)) {
$reflection = new Reflection($this->getFile());
$reflection->process();
$cacheKey = "meta.{$this->module}.{$this->controller}";

if (!$meta = Cache::get($cacheKey)) {
$meta = new Meta($this->getFile());
$meta->process();

Cache::set(
$cacheKey,
$reflection,
$meta,
Cache::TTL_NO_EXPIRY,
['system', 'reflection', Cache::prepare($this->module . '.' . $this->controller)]
['system', 'meta', Cache::prepare($this->module . '.' . $this->controller)]
);
}
$this->reflection = $reflection;
$this->meta = $meta;
}

/**
* Get Reflection
* @return Reflection
* Get meta information
* @return Meta
*/
public function getReflection() // : Reflection
public function getMeta()
{
if (!$this->reflection) {
$this->setReflection();
if (!$this->meta) {
$this->setMeta();
}
return $this->reflection;
return $this->meta;
}

/**
Expand Down
17 changes: 8 additions & 9 deletions src/Controller/Reflection.php → src/Controller/Meta.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
use Bluz\Proxy\Request;

/**
* Reflection
* Meta information from reflection of the function
*
* @package Bluz\Controller
* @author Anton Shevchuk
*/
class Reflection
class Meta
{
use Options;

Expand Down Expand Up @@ -83,11 +83,11 @@ public function __construct($file)
* Set state required for working with var_export (used inside PHP File cache)
*
* @param $array
* @return Reflection
* @return Meta
*/
public static function __set_state($array)
{
$instance = new Reflection($array['file']);
$instance = new Meta($array['file']);
foreach ($array as $key => $value) {
$instance->{$key} = $value;
}
Expand Down Expand Up @@ -228,11 +228,10 @@ public function setCache($ttl)
protected function prepareCache($cache)
{
$num = (int)$cache;
$time = 'min';

if ($pos = strpos($cache, ' ')) {
$time = substr($cache, $pos);
} else {
$time = 'min';
}

switch ($time) {
Expand Down Expand Up @@ -419,16 +418,16 @@ protected function prepareRoutePattern($route)
switch ($type) {
case 'int':
case 'integer':
$pattern = str_replace("{\$" . $param . "}", "(?P<$param>[0-9]+)", $pattern);
$pattern = str_replace("{\$$param}", "(?P<$param>[0-9]+)", $pattern);
break;
case 'float':
$pattern = str_replace("{\$" . $param . "}", "(?P<$param>[0-9.,]+)", $pattern);
$pattern = str_replace("{\$$param}", "(?P<$param>[0-9.,]+)", $pattern);
break;
case 'string':
case 'module':
case 'controller':
$pattern = str_replace(
"{\$" . $param . "}",
"{\$$param}",
"(?P<$param>[a-zA-Z0-9-_.]+)",
$pattern
);
Expand Down
2 changes: 1 addition & 1 deletion src/Db/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public function getModel()
public function getColumns()
{
if (empty($this->columns)) {
$cacheKey = 'db.table.'. $this->name;
$cacheKey = "db.table.{$this->name}";
$columns = Cache::get($cacheKey);
if (!$columns) {
$connect = DbProxy::getOption('connect');
Expand Down
6 changes: 5 additions & 1 deletion src/Proxy/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ public static function get($key)
return false;
}

$key = self::prepare($key);

if ($cache->hasItem($key)) {
$item = $cache->getItem($key);
if ($item->isHit()) {
Expand All @@ -122,6 +124,8 @@ public static function set($key, $data, $ttl = self::TTL_NO_EXPIRY, $tags = [])
return false;
}

$key = self::prepare($key);

$item = $cache->getItem($key);
$item->set($data);

Expand All @@ -143,7 +147,7 @@ public static function set($key, $data, $ttl = self::TTL_NO_EXPIRY, $tags = [])
*/
public static function prepare($key)
{
return str_replace(['-', '/'], '_', $key);
return str_replace(['-', '/', '\\', '@', ':'], '_', $key);
}

/**
Expand Down
5 changes: 2 additions & 3 deletions src/Proxy/HttpCacheControl.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,9 @@ class HttpCacheControl
*/
protected static function initInstance()
{
if ('cli' === PHP_SAPI) {
if (PHP_SAPI === 'cli') {
return new Nil();
} else {
return new Instance(Response::getInstance());
}
return new Instance(Response::getInstance());
}
}
3 changes: 1 addition & 2 deletions src/Proxy/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ protected static function initInstance()
{
if (Config::getData('logger')) {
return new Instance();
} else {
return new Nil();
}
return new Nil();
}
}
3 changes: 1 addition & 2 deletions src/Proxy/ProxyTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ public static function __callStatic($method, $args)
{
if ($instance = static::getInstance()) {
return $instance->$method(...$args);
} else {
return false;
}
return false;
}
}
6 changes: 2 additions & 4 deletions src/Proxy/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -261,9 +261,7 @@ public static function getAccept($allowTypes = [])
// check if there is a different quality
if (strpos($a, ';q=') or strpos($a, '; q=')) {
// divide "mime/type;q=X" into two parts: "mime/type" i "X"
$res = preg_split('/;([ ]?)q=/', $a);
$a = $res[0];
$q = $res[1];
list($a, $q) = preg_split('/;([ ]?)q=/', $a);
}
// remove other extension
if (strpos($a, ';')) {
Expand Down Expand Up @@ -362,6 +360,6 @@ public static function isDelete()
*/
public static function isXmlHttpRequest()
{
return (self::getHeader('X-Requested-With') == 'XMLHttpRequest');
return (self::getHeader('X-Requested-With') === 'XMLHttpRequest');
}
}
3 changes: 2 additions & 1 deletion src/Proxy/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,9 @@ public static function redirect($url)
* @param string $controller
* @param array $params
* @return void
* @throws RedirectException
*/
public static function redirectTo($module = 'index', $controller = 'index', $params = [])
public static function redirectTo($module = 'index', $controller = 'index', array $params = [])
{
$url = Router::getUrl($module, $controller, $params);
self::redirect($url);
Expand Down
2 changes: 1 addition & 1 deletion src/Response/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ abstract public function __toString();
* Render object as HTML or JSON
*
* @param string $type
* @return mixed
* @return string
*/
public function render($type = 'HTML')
{
Expand Down
Loading

0 comments on commit 4402384

Please sign in to comment.