1
0
mirror of https://github.com/php/web-php.git synced 2026-03-23 23:02:13 +01:00

Multiple micro-optimizations

* Replace `ob_get_contents();ob_clean()` with `ob_get_clean()`

`ob_get_clean()` is equivalent to `ob_get_contents()` followed by `ob_clean()`.

* Replace `intval()` calls with `(int)` type cast

This is a micro-optimization because `intval()` is a function call, and the type cast is about 6 times fast.

* Replace `preg_replace` call that could be done with an `rtrim()` call

In `./error.php`, there is a `preg_replace('!/+$!', '', $URI);` call that essentially is equivalent to `rtrim()`, that both calls removing trailing slash characters in `$URI`.
The `rtim()` call is more legible and faster.

* Combine consecutive `str_replace` calls to a single `str_replace` call

* Use short ternary operator where possible

Improves code readability.

* Cascade various `else` statements where possible

Cleans up the code by removing unnecessary `else` blocks and moving the code to the parent context if the previous `if` block exits the function by either terminating the script, or with a `return` statement.

* Combine multiple `isset()` calls to a single `isset()`

`isset()` accepts multiple parameters and returns `true` only if all of the parameters are `isset`. It makes sense to combine multiple individual `isset` calls to a single call for better readability.

* Replace `for` loop with a `foreach` loop

* Remove unnecessary character escapes in regular expressions

Regular expression special characters are context-sensitive. For example, special characters such as `.` are not considered special within square braces (`[]`).
This removes several of such instances that certain characters are escaped, but it is not strictly necessary within the context. This improves the readability of the expression.

See more information at [PHP.Watch: Writing better Regular Expressions in PHP](https://php.watch/articles/php-regex-readability#reduce-escape)

* Remove unnecessary break statement

* Remove unnecessary PHP close tags

* Remove redundant JSON_ERROR_NONE check

Remove unnecessary `json_last_error() == JSON_ERROR_NONE` where the decoded object is inspected already.

Closes GH-603.
This commit is contained in:
Ayesh Karunaratne
2022-07-03 15:54:14 +05:30
committed by GitHub
parent 38d4e0721c
commit 1b83fd7ab7
25 changed files with 76 additions and 86 deletions

View File

@@ -11,9 +11,9 @@ if ($_SERVER['argc'] < 1) {
exit(1);
}
$major = intval($_SERVER['argv'][1]);
$major = (int) $_SERVER['argv'][1];
isset($RELEASES[$major]) or die("Unkown major version $major");
$minor = isset($_SERVER['argv'][2]) ? intval($_SERVER['argv'][2]) : null;
$minor = isset($_SERVER['argv'][2]) ? (int) $_SERVER['argv'][2] : null;
$version = get_current_release_for_branch($major, $minor);
$info = $RELEASES[$major][$version] ?? null;

View File

@@ -84,8 +84,7 @@ foreach($entries as $module => $items) {
echo "</ul>\n<!-- }}} --></section>\n\n";
if ($changelog) {
$contents = ob_get_contents();
ob_end_clean();
$contents = ob_get_clean();
$log = file_get_contents($changelog);
if (empty($log)) {

View File

@@ -222,11 +222,10 @@ function date_for_recur($recur, $day, $bom, $eom)
}
// ${recur}th to last $day of the month
else {
$eomd = date("w",$eom) + 1;
$days = (($eomd - $day + 7) % 7) + ((abs($recur) - 1) * 7);
return mktime(0,0,1, date("m",$bom)+1, -$days, date("Y",$bom));
}
$eomd = date("w",$eom) + 1;
$days = (($eomd - $day + 7) % 7) + ((abs($recur) - 1) * 7);
return mktime(0, 0, 1, date("m", $bom)+1, -$days, date("Y", $bom));
}
// Display a <div> for each of the events that are on a given day

View File

@@ -5,8 +5,7 @@ include_once __DIR__ . '/include/prepend.inc';
// Put credits information to $credits
ob_start();
phpcredits();
$credits = ob_get_contents();
ob_end_clean();
$credits = ob_get_clean();
// Strip all but the body and drop styles
preg_match('!<body.*?>(.*)</body>!ims', $credits, $m);
@@ -26,5 +25,3 @@ if ($credits) {
echo $credits;
site_footer();
}
?>

View File

@@ -116,7 +116,7 @@ if (preg_match("!^distributions/.*!", $URI, $array)) {
// ============================================================================
// The trailing slash only causes problems from now on
$URI = preg_replace('!/+$!', '', $URI);
$URI = rtrim($URI, '/');
// ============================================================================
// Some nice URLs for getting something for download
@@ -700,4 +700,3 @@ mirror_redirect(
/*
* vim: set et ts=4 sw=4 ft=php: :
*/
?>

View File

@@ -35,7 +35,7 @@ header("Expires: " . date(DATE_RSS, $future));
// determine how many images to serve.
if (isset($_REQUEST['count'])) {
$count = min(intval($_REQUEST['count']), 50);
$count = min((int) $_REQUEST['count'], 50);
} else {
header('HTTP/1.1 400', true, 400);
print json_encode(array(

View File

@@ -162,7 +162,7 @@ function get_active_branches($include_recent_eols = true) {
* must be in $RELEASES _and_ must be the full version number, not the branch:
* ie provide array('5.3.29'), not array('5.3'). */
function get_eol_branches($always_include = null) {
$always_include = $always_include ? $always_include : array();
$always_include = $always_include ?: array();
$branches = array();
$now = new DateTime;
@@ -329,13 +329,17 @@ function get_branch_support_state($branch) {
if ($now >= $security) {
return 'eol';
} elseif ($now >= $bug) {
return 'security';
} elseif ($now >= $initial) {
return 'stable';
} else {
return 'future';
}
if ($now >= $bug) {
return 'security';
}
if ($now >= $initial) {
return 'stable';
}
return 'future';
}
return null;

View File

@@ -18,7 +18,7 @@ function is_emailable_address($email)
$host = substr($email, strrpos($email, '@') + 1);
// addresses from our mailing-list servers
$host_regex = "!(lists\.php\.net|chek[^\.*]\.com)!i";
$host_regex = "!(lists\.php\.net|chek[^.*]\.com)!i";
if (preg_match($host_regex, $host)) {
return false;
}

View File

@@ -87,4 +87,3 @@ $historical_mirrors = array(
array("USA", "us3.php.net", "C7 Data Centers", "https://www.c7.com/"),
array("VNM", "vn1.php.net", "DigiStar Co., Ltd", "http://www.digistar.vn/"),
);
?>

View File

@@ -95,12 +95,12 @@ function i2c_search_in_index($ip)
// Read in granularity from index file and
// convert current IP to something useful
$granularity = intval(fgets($dbidx, 64));
$granularity = (int) fgets($dbidx, 64);
if (!$granularity) {
// The file is empty (demo file)
return false;
}
$ip_chunk = intval($ip / $granularity);
$ip_chunk = (int) ($ip / $granularity);
// Loop till we can read the file
while (!feof($dbidx)) {
@@ -217,7 +217,7 @@ function i2c_realip()
}
// Return with the found IP or the remote address
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
return $ip ?: $_SERVER['REMOTE_ADDR'];
}
/* vim: set et ts=4 sw=4 ft=php: : */

View File

@@ -102,11 +102,11 @@ function language_choose_code()
$browser_accept = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
// Go through all language preference specs
for ($i = 0; $i < count($browser_accept); $i++) {
foreach ($browser_accept as $value) {
// The language part is either a code or a code with a quality
// We cannot do anything with a * code, so it is skipped
// If the quality is missing, it is assumed to be 1 according to the RFC
if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($browser_accept[$i]), $found)) {
if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($value), $found)) {
$quality = (isset($found[3]) ? (float) $found[3] : 1.0);
$browser_langs[] = array($found[1], $quality);
}

View File

@@ -52,7 +52,7 @@ function highlight_php_trimmed($code, $return = false)
{
$code = "<?php\n" . $code;
$highlighted_code = highlight_php($code, true);
$highlighted_code = preg_replace("/\&lt;\?php(\<br \/\>)+/", '', $highlighted_code, 1);
$highlighted_code = preg_replace("!&lt;\?php(<br />)+!", '', $highlighted_code, 1);
if ($return) { return $highlighted_code; }
echo $highlighted_code;
@@ -109,7 +109,7 @@ function make_image($file, $alt = FALSE, $align = FALSE, $extras = FALSE,
return sprintf('<img src="%s/%s" alt="%s"%s%s%s>',
$webdir,
$file,
($alt ? $alt : ''),
($alt ?: ''),
$sizeparams,
$align,
($extras ? ' ' . $extras : '')
@@ -159,7 +159,7 @@ function make_link ($url, $linktext = FALSE, $target = FALSE, $extras = FALSE)
$url,
($target ? ' target="' . $target . '"' : ''),
($extras ? ' ' . $extras : ''),
($linktext ? $linktext : $url)
($linktext ?: $url)
);
}
@@ -175,12 +175,12 @@ function print_link($url, $linktext = FALSE, $target = FALSE, $extras = FALSE)
function make_popup_link ($url, $linktext=false, $target=false, $windowprops="", $extras=false) {
return sprintf("<a href=\"%s\" target=\"%s\" onclick=\"window.open('%s','%s','%s');return false;\"%s>%s</a>",
htmlspecialchars($url, ENT_QUOTES | ENT_IGNORE),
($target ? $target : "_new"),
($target ?: "_new"),
htmlspecialchars($url, ENT_QUOTES | ENT_IGNORE),
($target ? $target : "_new"),
($target ?: "_new"),
$windowprops,
($extras ? ' '.$extras : ''),
($linktext ? $linktext : $url)
($linktext ?: $url)
);
}
@@ -230,8 +230,7 @@ function download_link($file, $title)
function sect_to_file($string) {
$string = strtolower($string);
$string = str_replace(' ','-',$string);
$string = str_replace('_','-',$string);
$string = str_replace([' ', '_'], '-', $string);
$func = "function.$string.php";
$chap = "ref.$string.php";
$feat = "features.$string.php";
@@ -255,7 +254,7 @@ function clean_note($text)
// Turn urls into links
return preg_replace(
'!((mailto:|(https?|ftp|nntp|news):\/\/).*?)(\s|<|\)|"|\\\\|\'|$)!',
'!((mailto:|(https?|ftp|nntp|news)://).*?)(\s|<|\)|"|\\\\|\'|$)!',
'<a href="\1" rel="nofollow" target="_blank">\1</a>\4',
$text
);
@@ -397,7 +396,7 @@ function news_archive_sidebar()
function print_news($news, $dog, $max = 5, $onlyyear = null, $return = false) {
$retval = array();
$count = 0;
$news = $news ? $news : array(); // default to empty array (if no news)
$news = $news ?: array(); // default to empty array (if no news)
foreach($news as $item) {
$ok = false;

View File

@@ -36,5 +36,4 @@ $CONF_TEASER = array (
'http://php.net/conferences/index.php#id2015-06-19-1' => 'ZendCon 2015',
'http://php.net/conferences/index.php#id2015-06-01-1' => 'PHP Barcelona Conference 2015',
),
)
?>
);

View File

@@ -92,4 +92,3 @@ EOB;
echo '</ul></div>';
endif;
}
?>

View File

@@ -129,7 +129,7 @@ function manual_note_display($date, $name, $text, $id, $votes = array('up'=>0,'d
// Calculate note rating by up/down votes
$vote = $votes['up'] - $votes['down'];
$p = floor(($votes['up'] / (($votes['up'] + $votes['down']) ? $votes['up'] + $votes['down'] : 1)) * 100);
$p = floor(($votes['up'] / (($votes['up'] + $votes['down']) ?: 1)) * 100);
$rate = !$p && !($votes['up'] + $votes['down']) ? "no votes..." : "$p% like this...";
// Vote User Notes Div

View File

@@ -71,7 +71,9 @@ function mirror_provider($site = FALSE)
if (isset($MIRRORS[$site])) {
return $MIRRORS[$site][1];
} elseif (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) {
}
if (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) {
return $MIRRORS[$_SERVER['SERVER_ADDR']][1];
}
@@ -87,7 +89,9 @@ function mirror_provider_url($site = FALSE)
if (isset($MIRRORS[$site])) {
return $MIRRORS[$site][3];
} elseif (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) {
}
if (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) {
return $MIRRORS[$_SERVER['SERVER_ADDR']][3];
}
@@ -103,7 +107,9 @@ function mirror_type($site = FALSE)
if (isset($MIRRORS[$site])) {
return $MIRRORS[$site][4];
} elseif (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) {
}
if (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) {
return $MIRRORS[$_SERVER['SERVER_ADDR']][4];
}
@@ -138,12 +144,12 @@ function mirror_setcookie($name, $content, $exptime)
if (!headers_sent()) {
if (is_official_mirror()) {
return setcookie($name, $content, time() + $exptime, '/', '.php.net');
} else {
return setcookie($name, $content, time() + $exptime, '/');
}
} else {
return FALSE;
return setcookie($name, $content, time() + $exptime, '/');
}
return FALSE;
}
// Use this function to write out proper headers on
@@ -216,7 +222,6 @@ function get_shortname($page) {
if (strpos($shorturl, $section) === 0) {
// We can make it even shorter
return substr($shorturl, strlen($section), -4);
break;
}
}

View File

@@ -42,10 +42,9 @@ if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"]) &&
header("HTTP/1.1 304 Not Modified");
exit();
}
// Inform the user agent what is our last modification date
else {
header("Last-Modified: " . $tsstring);
}
header("Last-Modified: " . $tsstring);
$_SERVER['BASE_PAGE'] = 'index.php';
include_once 'include/prepend.inc';
@@ -186,7 +185,7 @@ if (is_array($CONF_TEASER)) {
$announcements .= ' <a href="/conferences" class="headline" title="' . $conftype[$category] . '">' . $conftype[$category] .'</a>';
$announcements .= '<div class="body"><ul>';
foreach (array_slice($entries, 0, 4) as $url => $title) {
$title = preg_replace("'([A-Za-z0-9])([\s\:\-\,]*?)call for(.*?)$'i", "$1", $title);
$title = preg_replace("'([A-Za-z0-9])([\s:\-,]*?)call for(.*?)$'i", "$1", $title);
$announcements .= "<li><a href='$url' title='$title'>$title</a></li>";
}
$announcements .= '</ul></div>';

View File

@@ -31,5 +31,3 @@ if ($function) {
// Fall back to a quick reference search
$notfound = $function;
include __DIR__ . '/quickref.php';
?>

View File

@@ -36,8 +36,7 @@ if ($process) {
// Convert all line-endings to unix format,
// and don't allow out-of-control blank lines
$note = str_replace("\r\n", "\n", $note);
$note = str_replace("\r", "\n", $note);
$note = str_replace(["\r\n", "\r"], "\n", $note);
$note = preg_replace("/\n{2,}/", "\n\n", $note);
// Don't pass through example username
@@ -135,17 +134,14 @@ if ($process) {
}
// There was an error, or a preview is needed
else {
// If there was an error, print out
if ($error) { echo "<p class=\"formerror\">$error</p>\n"; }
// If there was an error, print out
if ($error) { echo "<p class=\"formerror\">$error</p>\n"; }
// Print out preview of note
echo '<p>This is what your entry will look like, roughly:</p>';
echo '<div id="usernotes">';
manual_note_display(time(), $user, $note, FALSE);
echo '</div><br><br>';
}
// Print out preview of note
echo '<p>This is what your entry will look like, roughly:</p>';
echo '<div id="usernotes">';
manual_note_display(time(), $user, $note, FALSE);
echo '</div><br><br>';
}
// Any needed variable was missing => display instructions
@@ -345,7 +341,7 @@ else {
if (empty($_POST['user'])) { $_POST['user'] = "user@example.com"; }
// There is no section to add note to
if (!isset($_POST['sect']) || !isset($_POST['redirect'])) {
if (!isset($_POST['sect'], $_POST['redirect'])) {
echo '<p class="formerror">To add a note, you must click on the "Add Note" button (the plus sign) ',
'on the bottom of a manual page so we know where to add the note!</p>';
}

View File

@@ -1,4 +1,3 @@
<?php
include_once __DIR__ . '/../include/prepend.inc';
mirror_redirect("/manual/$LANG/index.php");
?>

View File

@@ -68,6 +68,3 @@ function test_answer($name, $an, $bn, $answer) {
return ($nums[$c[0]($a, $b)] === $answer);
}
?>

View File

@@ -39,10 +39,10 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
else {
$r = json_decode($r);
if (json_last_error() == JSON_ERROR_NONE && isset($r->status) && $r->status && isset($r->votes)) {
if (isset($r->status, $r->votes) && $r->status) {
$response["success"] = true;
$response["update"] = (int)$r->votes;
} elseif (json_last_error() == JSON_ERROR_NONE && isset($r->status, $r->message) && $r->status == false) {
} elseif (isset($r->status, $r->message) && !$r->status) {
$response["success"] = false;
$response["msg"] = $r->message;
} else {
@@ -79,7 +79,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
);
if (($r = posttohost($master_url, $data)) !== null && strpos($r,"failed to open socket to") === false) {
$r = json_decode($r);
if (json_last_error() == JSON_ERROR_NONE && isset($r->status) && $r->status && isset($r->votes)) {
if (isset($r->status, $r->votes) && $r->status) {
$thankyou = true;
} else {
$error = "Invalid request.";

View File

@@ -20,7 +20,7 @@ if (isset($_GET["serialize"]) || isset($_GET["json"])) {
if (isset($RELEASES[$ver])) {
$combinedReleases = array_replace_recursive($RELEASES, $OLDRELEASES);
$max = intval($_GET['max'] ?? 1);
$max = (int) ($_GET['max'] ?? 1);
if ($max == -1) {
$max = PHP_INT_MAX;
}

View File

@@ -130,7 +130,7 @@ if(is_resource($fp)) {
$title = ucfirst(strtr($field, "-", " "));
// Turn urls into links (stolen from master/manage/user-notes.php)
$data = preg_replace(
'!((mailto:|(http|ftp|nntp|news):\/\/).*?)(\s|<|\)|"|\\|\'|$)!',
'!((mailto:|(http|ftp|nntp|news)://).*?)(\s|<|\)|"|\\|\'|$)!',
'<a href="\1" target="_blank">\1</a>\4',
$data
);

View File

@@ -45,9 +45,9 @@ class Sorter {
private function calcRatingPriority(array $note) {
if ($note['total'] <= 2) {
return 0.5;
} else {
return $note['rating'];
}
return $note['rating'];
}
@@ -70,11 +70,13 @@ class Sorter {
private function factorSort($a, $b) {
if ($a['sort'] < $b['sort']) {
return 1;
} elseif ($a['sort'] == $b['sort']) {
return 0;
} else {
return -1;
}
if ($a['sort'] == $b['sort']) {
return 0;
}
return -1;
}