Use early exits and don’t use else
Code almost never needs the else keyword. It can be written in a way to use early exits with return or continue instead. This following code could have been written with an else. This rule keeps the main/happy path of the code on the main level of the method.
<?php
public function formatQueryString(string $query): string
{
if (strlen($query) === 0) {
return '';
}
parse_str($query, $queryArgs);
$queryArgs = $this->truncateArrayValues($queryArgs);
return json_encode($queryArgs, JSON_PRETTY_PRINT);
}
For loops we continue to the next iteration for early exits:
<?php
private function parseErrorTrace(string $trace, $removeArguments = false)
{
$traceResult = [];
$parts = explode("\n", $trace);
foreach ($parts as $line) {
if (strpos($line, '{main}') !== false) {
continue;
}
if (strpos($line, '#') !== 0) {
continue;
}
// more
}
}