Skip to content

Commit

Permalink
Optimizing PHP performance by using
Browse files Browse the repository at this point in the history
fully-qualified function calls
  • Loading branch information
eldadfux committed Jun 20, 2020
1 parent e4f6c7d commit ca2ebe3
Show file tree
Hide file tree
Showing 20 changed files with 94 additions and 94 deletions.
48 changes: 24 additions & 24 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,13 @@ class App
*/
public function __construct($timezone, $mode = self::MODE_TYPE_PRODUCTION)
{
date_default_timezone_set($timezone);
\date_default_timezone_set($timezone);

// Turn errors on when not in production or stage
if($mode != self::MODE_TYPE_PRODUCTION && $mode != self::MODE_TYPE_STAGE) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
\ini_set('display_errors', 1);
\ini_set('display_startup_errors', 1);
\error_reporting(E_ALL);
}

$this->mode = $mode;
Expand Down Expand Up @@ -356,7 +356,7 @@ public function match(Request $request) {
return $this->route;
}

$url = parse_url($request->getServer('REQUEST_URI', ''), PHP_URL_PATH);
$url = \parse_url($request->getServer('REQUEST_URI', ''), PHP_URL_PATH);
$method = $request->getServer('REQUEST_METHOD', '');
$method = (self::REQUEST_METHOD_HEAD == $method) ? self::REQUEST_METHOD_GET : $method;

Expand All @@ -370,26 +370,26 @@ public function match(Request $request) {
* For route to work with similar links where one is shorter than other
* but both might match given pattern
*/
uksort($this->routes[$method], function($a, $b) {
return strlen($b) - strlen($a);
\uksort($this->routes[$method], function($a, $b) {
return \strlen($b) - \strlen($a);
});

uksort($this->routes[$method], function($a, $b) {
return count(explode('/', $b)) - count(explode('/', $a));
\uksort($this->routes[$method], function($a, $b) {
return \count(\explode('/', $b)) - \count(\explode('/', $a));
});

foreach($this->routes[$method] as $route) {
/* @var $route Route */

// convert urls like '/users/:uid/posts/:pid' to regular expression
$regex = '@' . preg_replace('@:[^/]+@', '([^/]+)', $route->getURL()) . '@';
$regex = '@' . \preg_replace('@:[^/]+@', '([^/]+)', $route->getURL()) . '@';

// Check if the current request matches the expression
if (!preg_match($regex, $url, $this->matches)) {
if (!\preg_match($regex, $url, $this->matches)) {
continue;
}

array_shift($this->matches);
\array_shift($this->matches);
$this->route = $route;
break;
}
Expand Down Expand Up @@ -424,18 +424,18 @@ public function run(Request $request, Response $response)

if(null !== $route) {
// Extract keys from URL
$keyRegex = '@^' . preg_replace('@:[^/]+@', ':([^/]+)', $route->getURL()) . '$@';
preg_match($keyRegex, $route->getURL(), $keys);
$keyRegex = '@^' . \preg_replace('@:[^/]+@', ':([^/]+)', $route->getURL()) . '$@';
\preg_match($keyRegex, $route->getURL(), $keys);

// Remove the first key and value ( corresponding to full regex match )
array_shift($keys);
\array_shift($keys);

// combine keys and values to one array
$values = array_combine($keys, $this->matches);
$values = \array_combine($keys, $this->matches);

try {
foreach($this->init as $init) {
call_user_func_array($init, []);
\call_user_func_array($init, []);
}

foreach($route->getParams() as $key => $param) {
Expand All @@ -449,30 +449,30 @@ public function run(Request $request, Response $response)
}

// Call the callback with the matched positions as params
call_user_func_array($route->getAction(), $params);
\call_user_func_array($route->getAction(), $params);

foreach($this->shutdown as $shutdown) {
call_user_func_array($shutdown, []);
\call_user_func_array($shutdown, []);
}
}
catch (\Exception $e) {
call_user_func_array($this->error, [$e]);
\call_user_func_array($this->error, [$e]);
}

return $this;
}
elseif(self::REQUEST_METHOD_OPTIONS == $method) {
try {
foreach($this->options as $option) {
call_user_func_array($option, []);
\call_user_func_array($option, []);
}
}
catch (\Exception $e) {
call_user_func_array($this->error, [$e]);
\call_user_func_array($this->error, [$e]);
}
}
else {
call_user_func_array($this->error, [new Exception('Not Found', 404)]);
\call_user_func_array($this->error, [new Exception('Not Found', 404)]);
}

return $this;
Expand All @@ -494,7 +494,7 @@ protected function validate($key, $param, $value)
// checking whether the class exists
$validator = $param['validator'];

if(is_callable($validator)) {
if(\is_callable($validator)) {
$validator = $validator();
}

Expand Down
16 changes: 8 additions & 8 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ public function getHeader(string $key, string $default = ''): string
*/
public function getSize(): int
{
return mb_strlen(implode("\n", $this->generateHeaders()), '8bit') + mb_strlen(file_get_contents('php://input'), '8bit');
return \mb_strlen(\implode("\n", $this->generateHeaders()), '8bit') + \mb_strlen(\file_get_contents('php://input'), '8bit');
}

/**
Expand All @@ -229,13 +229,13 @@ protected function generateInput(): array
$contentType = $this->getHeader('Content-Type');

// Get content-type without the charset
$length = strpos($contentType, ';');
$length = (empty($length)) ? strlen($contentType) : $length;
$contentType = substr($contentType, 0, $length);
$length = \strpos($contentType, ';');
$length = (empty($length)) ? \strlen($contentType) : $length;
$contentType = \substr($contentType, 0, $length);

switch ($contentType) {
case 'application/json':
$this->payload = json_decode(file_get_contents('php://input'), true);
$this->payload = \json_decode(\file_get_contents('php://input'), true);
break;

default:
Expand Down Expand Up @@ -265,12 +265,12 @@ protected function generateHeaders(): array
* Fallback for older PHP versions
* that do not support generateHeaders
*/
if (!function_exists('getallheaders')) {
if (!\function_exists('getallheaders')) {
$headers = [];

foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
if (\substr($name, 0, 5) == 'HTTP_') {
$headers[\str_replace(' ', '-', \ucwords(\strtolower(\str_replace('_', ' ', \substr($name, 5)))))] = $value;
}
}

Expand Down
28 changes: 14 additions & 14 deletions src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class Response
*/
public function __construct()
{
$this->startTime = microtime(true);
$this->startTime = \microtime(true);
}

/**
Expand Down Expand Up @@ -193,7 +193,7 @@ public function setContentType(string $type): self
*/
public function setStatusCode(int $code = 200): self
{
if (!array_key_exists($code, $this->statusCodes)) {
if (!\array_key_exists($code, $this->statusCodes)) {
throw new Exception('Unknown HTTP status code');
}

Expand Down Expand Up @@ -350,21 +350,21 @@ public function getCookies(): array
public function send(string $body = '', int $exit = null): void
{
if(!$this->disablePayload) {
$this->addHeader('X-Debug-Speed', microtime(true) - $this->startTime);
$this->addHeader('X-Debug-Speed', \microtime(true) - $this->startTime);

$this
->appendCookies()
->appendHeaders()
;

$this->size = $this->size + mb_strlen(implode("\n", headers_list())) + mb_strlen($body, '8bit');
$this->size = $this->size + \mb_strlen(\implode("\n", \headers_list())) + \mb_strlen($body, '8bit');

echo $body;

$this->disablePayload();
}

if(!is_null($exit)) {
if(!\is_null($exit)) {
exit($exit); // Exit with code
}
}
Expand All @@ -380,7 +380,7 @@ public function send(string $body = '', int $exit = null): void
protected function appendHeaders(): self
{
// Send status code header
http_response_code($this->statusCode);
\http_response_code($this->statusCode);

// Send content type header
$this
Expand All @@ -389,7 +389,7 @@ protected function appendHeaders(): self

// Set application headers
foreach ($this->headers as $key => $value) {
header($key . ': ' . $value);
\header($key . ': ' . $value);
}

return $this;
Expand All @@ -406,11 +406,11 @@ protected function appendCookies(): self
{
foreach ($this->cookies as $cookie) {

if (version_compare(PHP_VERSION, '7.3.0', '<')) {
setcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
if (\version_compare(PHP_VERSION, '7.3.0', '<')) {
\setcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
}
else {
setcookie($cookie['name'], $cookie['value'], [
\setcookie($cookie['name'], $cookie['value'], [
'expires' => $cookie['expire'],
'path' => $cookie['path'],
'domain' => $cookie['domain'],
Expand Down Expand Up @@ -445,7 +445,7 @@ protected function appendCookies(): self
public function redirect(string $url, int $statusCode = 301, int $exit = null): void
{
if (300 == $statusCode) {
trigger_error('It seems webkit based browsers have problems redirecting link with 300 status codes!', E_USER_NOTICE);
\trigger_error('It seems webkit based browsers have problems redirecting link with 300 status codes!', E_USER_NOTICE);
}

$this
Expand Down Expand Up @@ -486,7 +486,7 @@ public function json(array $data): void
{
$this
->setContentType(Response::CONTENT_TYPE_JSON)
->send(json_encode($data, JSON_UNESCAPED_UNICODE))
->send(\json_encode($data, JSON_UNESCAPED_UNICODE))
;
}

Expand All @@ -505,7 +505,7 @@ public function jsonp(string $callback, array $data): void
{
$this
->setContentType(Response::CONTENT_TYPE_JAVASCRIPT)
->send('parent.' . $callback . '(' . json_encode($data) . ');')
->send('parent.' . $callback . '(' . \json_encode($data) . ');')
;
}

Expand All @@ -521,7 +521,7 @@ public function jsonp(string $callback, array $data): void
public function iframe(string $callback, array $data): void
{
$this
->send('<script type="text/javascript">window.parent.' . $callback . '(' . json_encode($data) . ');</script>');
->send('<script type="text/javascript">window.parent.' . $callback . '(' . \json_encode($data) . ');</script>');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Validator/ArrayList.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public function getDescription()
*/
public function isValid($value)
{
if(!is_array($value)) {
if(!\is_array($value)) {
return false;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Validator/Assoc.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ public function getDescription()
*/
public function isValid($value)
{
if (!is_array($value)) {
if (!\is_array($value)) {
return false;
}

return array_keys($value) !== range(0, count($value) - 1);
return \array_keys($value) !== \range(0, \count($value) - 1);
}
}
2 changes: 1 addition & 1 deletion src/Validator/Boolean.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function getDescription()
*/
public function isValid($value)
{
if (!is_bool($value)) {
if (!\is_bool($value)) {
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Validator/Domain.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function getDescription()
*/
public function isValid($value)
{
if (filter_var($value, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) === false) {
if (\filter_var($value, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) === false) {
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Validator/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function getDescription()
*/
public function isValid($value)
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
if (!\filter_var($value, FILTER_VALIDATE_EMAIL)) {
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Validator/HexColor.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function getDescription()
*/
public function isValid($value)
{
if (is_string($value) && preg_match('/^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $value)) {
if (\is_string($value) && \preg_match('/^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $value)) {
return true;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Validator/Host.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function __construct(array $whitelist)
*/
public function getDescription()
{
return 'URL host must be one of: ' . implode(', ', $this->whitelist);
return 'URL host must be one of: ' . \implode(', ', $this->whitelist);
}

/**
Expand All @@ -62,7 +62,7 @@ public function isValid($value)
return false;
}

if(in_array(parse_url($value, PHP_URL_HOST), $this->whitelist)) {
if(\in_array(\parse_url($value, PHP_URL_HOST), $this->whitelist)) {
return true;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Validator/IP.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function getDescription()
*/
public function isValid($value)
{
if (!filter_var($value, FILTER_VALIDATE_IP)) {
if (!\filter_var($value, FILTER_VALIDATE_IP)) {
return false;
}

Expand Down
8 changes: 4 additions & 4 deletions src/Validator/JSON.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ public function getDescription()
*/
public function isValid($value)
{
if(is_array($value)) {
if(\is_array($value)) {
return true;
}

if(is_string($value)) {
json_decode($value);
return (json_last_error() == JSON_ERROR_NONE);
if(\is_string($value)) {
\json_decode($value);
return (\json_last_error() == JSON_ERROR_NONE);
}

return false;
Expand Down
Loading

0 comments on commit ca2ebe3

Please sign in to comment.