Skip to content

Commit

Permalink
coding style
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jan 7, 2024
1 parent 925b93b commit 9c163d8
Show file tree
Hide file tree
Showing 54 changed files with 1,039 additions and 725 deletions.
2 changes: 1 addition & 1 deletion ncs.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<ruleset name="Custom" namespace="Nette">
<rule ref="$presets/php72.xml"/>
<rule ref="$presets/php80.xml"/>

<rule ref="SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly">
<exclude-pattern>./tests/*/*.phpt</exclude-pattern>
Expand Down
2 changes: 1 addition & 1 deletion src/CodeCoverage/Collector.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static function start(string $file, string $engine): void
} elseif (!in_array(
$engine,
array_map(fn(array $engineInfo) => $engineInfo[0], self::detectEngines()),
true
true,
)) {
throw new \LogicException("Code coverage engine '$engine' is not supported.");
}
Expand Down
15 changes: 7 additions & 8 deletions src/CodeCoverage/Generators/AbstractGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ public function __construct(string $file, array $sources = [])
throw new \Exception("Content of file '$file' is invalid.");
}

$this->data = array_filter($this->data, function (string $path): bool {
return @is_file($path); // @ some files or wrappers may not exist, i.e. mock://
}, ARRAY_FILTER_USE_KEY);
$this->data = array_filter($this->data, fn(string $path): bool => @is_file($path), ARRAY_FILTER_USE_KEY);

if (!$sources) {
$sources = [Helpers::findCommonDirectory(array_keys($this->data))];
Expand Down Expand Up @@ -102,14 +100,15 @@ protected function getSourceIterator(): \Iterator
$iterator->append(
is_dir($source)
? new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source))
: new \ArrayIterator([new \SplFileInfo($source)])
: new \ArrayIterator([new \SplFileInfo($source)]),
);
}

return new \CallbackFilterIterator($iterator, function (\SplFileInfo $file): bool {
return $file->getBasename()[0] !== '.' // . or .. or .gitignore
&& in_array($file->getExtension(), $this->acceptFiles, true);
});
return new \CallbackFilterIterator(
$iterator,
fn(\SplFileInfo $file): bool => $file->getBasename()[0] !== '.' // . or .. or .gitignore
&& in_array($file->getExtension(), $this->acceptFiles, true)
);
}


Expand Down
12 changes: 6 additions & 6 deletions src/Framework/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ public static function exception(
callable $function,
string $class,
?string $message = null,
$code = null
$code = null,
): ?\Throwable
{
self::$counter++;
Expand Down Expand Up @@ -332,7 +332,7 @@ public static function throws(
callable $function,
string $class,
?string $message = null,
mixed $code = null
mixed $code = null,
): ?\Throwable
{
return self::exception($function, $class, $message, $code);
Expand All @@ -346,7 +346,7 @@ public static function throws(
public static function error(
callable $function,
int|string|array $expectedType,
?string $expectedMessage = null
?string $expectedMessage = null,
): ?\Throwable
{
if (is_string($expectedType) && !preg_match('#^E_[A-Z_]+$#D', $expectedType)) {
Expand Down Expand Up @@ -474,7 +474,7 @@ public static function fail(
$actual = null,
$expected = null,
?\Throwable $previous = null,
?string $outputName = null
?string $outputName = null,
): void
{
$e = new AssertException($message, $expected, $actual, $previous);
Expand Down Expand Up @@ -584,7 +584,7 @@ public static function expandMatchingPatterns(string $pattern, string $actual):
$high = strlen($actual);
while ($low <= $high) {
$mid = ($low + $high) >> 1;
if (!self::isMatching($patternX, substr($actual, 0, $mid), true)) {
if (!self::isMatching($patternX, substr($actual, 0, $mid), strict: true)) {
$high = $mid - 1;
} else {
$low = $mid + 1;
Expand All @@ -611,7 +611,7 @@ private static function isEqual(
bool $matchOrder,
bool $matchIdentity,
int $level = 0,
?\SplObjectStorage $objects = null
?\SplObjectStorage $objects = null,
): bool
{
switch (true) {
Expand Down
2 changes: 1 addition & 1 deletion src/Framework/DataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static function load(string $file, string $query = ''): array
throw new \Exception("Data provider '$file' did not return array or Traversable.");
}
} else {
$data = @parse_ini_file($file, true); // @ is escalated to exception
$data = @parse_ini_file($file, process_sections: true); // @ is escalated to exception
if ($data === false) {
throw new \Exception("Cannot parse data provider file '$file'.");
}
Expand Down
36 changes: 19 additions & 17 deletions src/Framework/DomQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static function fromHtml(string $html): self
$html = preg_replace_callback(
'#(<script(?=\s|>)(?:"[^"]*"|\'[^\']*\'|[^"\'>])*+>)(.*?)(</script>)#s',
fn(array $m): string => $m[1] . str_replace('</', '<\/', $m[2]) . $m[3],
$html
$html,
);

$dom = new \DOMDocument;
Expand Down Expand Up @@ -79,22 +79,24 @@ public function has(string $selector): bool
public static function css2xpath(string $css): string
{
$xpath = '//*';
preg_match_all('/
([#.:]?)([a-z][a-z0-9_-]*)| # id, class, pseudoclass (1,2)
\[
([a-z0-9_-]+)
(?:
([~*^$]?)=(
"[^"]*"|
\'[^\']*\'|
[^\]]+
)
)?
\]| # [attr=val] (3,4,5)
\s*([>,+~])\s*| # > , + ~ (6)
(\s+)| # whitespace (7)
(\*) # * (8)
/ix', trim($css), $matches, PREG_SET_ORDER);
preg_match_all(<<<'XX'
/
([#.:]?)([a-z][a-z0-9_-]*)| # id, class, pseudoclass (1,2)
\[
([a-z0-9_-]+)
(?:
([~*^$]?)=(
"[^"]*"|
'[^']*'|
[^\]]+
)
)?
\]| # [attr=val] (3,4,5)
\s*([>,+~])\s*| # > , + ~ (6)
(\s+)| # whitespace (7)
(\*) # * (8)
/ix
XX, trim($css), $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
if ($m[1] === '#') { // #ID
$xpath .= "[@id='$m[2]']";
Expand Down
34 changes: 15 additions & 19 deletions src/Framework/Dumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static function toLine(mixed $var): string
return "$var";

} elseif (is_float($var)) {
return var_export($var, true);
return var_export($var, return: true);

} elseif (is_string($var)) {
if (preg_match('#^(.{' . self::$maxLength . '}).#su', $var, $m)) {
Expand Down Expand Up @@ -138,7 +138,7 @@ private static function _toPhp(mixed &$var, array &$list = [], int $level = 0, i

static $marker;
if ($marker === null) {
$marker = uniqid("\x00", true);
$marker = uniqid("\x00", more_entropy: true);
}

if (empty($var)) {
Expand Down Expand Up @@ -221,7 +221,7 @@ private static function _toPhp(mixed &$var, array &$list = [], int $level = 0, i
return '/* resource ' . get_resource_type($var) . ' */';

} else {
return var_export($var, true);
return var_export($var, return: true);
}
}

Expand All @@ -238,12 +238,10 @@ private static function encodeStringPhp(string $s): string
$utf8 = preg_match('##u', $s);
$escaped = preg_replace_callback(
$utf8 ? '#[\p{C}\\\\]#u' : '#[\x00-\x1F\x7F-\xFF\\\\]#',
function ($m) use ($special) {
return $special[$m[0]] ?? (strlen($m[0]) === 1
? '\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT) . ''
: '\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}');
},
$s
fn($m) => $special[$m[0]] ?? (strlen($m[0]) === 1
? '\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT) . ''
: '\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}'),
$s,
);
return $s === str_replace('\\\\', '\\', $escaped)
? "'" . preg_replace('#\'|\\\\(?=[\'\\\\]|$)#D', '\\\\$0', $s) . "'"
Expand All @@ -263,14 +261,12 @@ private static function encodeStringLine(string $s): string
$utf8 = preg_match('##u', $s);
$escaped = preg_replace_callback(
$utf8 ? '#[\p{C}\']#u' : '#[\x00-\x1F\x7F-\xFF\']#',
function ($m) use ($special) {
return "\e[22m"
. ($special[$m[0]] ?? (strlen($m[0]) === 1
? '\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT)
: '\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}'))
. "\e[1m";
},
$s
fn($m) => "\e[22m"
. ($special[$m[0]] ?? (strlen($m[0]) === 1
? '\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT)
: '\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}'))
. "\e[1m",
$s,
);
return "'" . $escaped . "'";
}
Expand Down Expand Up @@ -326,7 +322,7 @@ public static function dumpException(\Throwable $e): string
for (; $i && $i < strlen($actual) && $actual[$i - 1] >= "\x80" && $actual[$i] >= "\x80" && $actual[$i] < "\xC0"; $i--);
$i = max(0, min(
$i - (int) (self::$maxLength / 3), // try to display 1/3 of shorter string
max(strlen($actual), strlen($expected)) - self::$maxLength + 3 // 3 = length of ...
max(strlen($actual), strlen($expected)) - self::$maxLength + 3, // 3 = length of ...
));
if ($i) {
$expected = substr_replace($expected, '...', 0, $i);
Expand Down Expand Up @@ -370,7 +366,7 @@ public static function dumpException(\Throwable $e): string
($item['file'] === $testFile ? self::color('white') : '')
. implode(
self::$pathSeparator ?? DIRECTORY_SEPARATOR,
array_slice(explode(DIRECTORY_SEPARATOR, $item['file']), -self::$maxPathSegments)
array_slice(explode(DIRECTORY_SEPARATOR, $item['file']), -self::$maxPathSegments),
)
. "($item[line])" . self::color('gray') . ' '
)
Expand Down
2 changes: 1 addition & 1 deletion src/Framework/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public static function setupColors(): void
ob_start(
fn(string $s): string => self::$useColors ? $s : Dumper::removeColors($s),
1,
PHP_OUTPUT_HANDLER_FLUSHABLE
PHP_OUTPUT_HANDLER_FLUSHABLE,
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Framework/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function run(): void

$methods = array_values(preg_grep(
self::MethodPattern,
array_map(fn(\ReflectionMethod $rm): string => $rm->getName(), (new \ReflectionObject($this))->getMethods())
array_map(fn(\ReflectionMethod $rm): string => $rm->getName(), (new \ReflectionObject($this))->getMethods()),
));

if (isset($_SERVER['argv']) && ($tmp = preg_filter('#--method=([\w-]+)$#Ai', '$1', $_SERVER['argv']))) {
Expand Down Expand Up @@ -145,7 +145,7 @@ public function runTest(string $method, ?array $args = null): void
$e->origMessage,
$method->getName(),
substr(Dumper::toLine($params), 1, -1),
is_string($k) ? (" (data set '" . explode('-', $k, 2)[1] . "')") : ''
is_string($k) ? (" (data set '" . explode('-', $k, 2)[1] . "')") : '',
));
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/Runner/CliTester.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ private function loadOptions(): CommandLine
throw new \Exception(
$file === null
? 'Option -o <format> without file name parameter can be used only once.'
: "Cannot specify output by -o into file '$file' more then once."
: "Cannot specify output by -o into file '$file' more then once.",
);
} elseif ($file === null) {
$this->stdoutFormat = $format;
Expand All @@ -150,19 +150,19 @@ private function loadOptions(): CommandLine

return [$format, $file];
}],
]
],
);

if (isset($_SERVER['argv'])) {
if (($tmp = array_search('-l', $_SERVER['argv'], true))
|| ($tmp = array_search('-log', $_SERVER['argv'], true))
|| ($tmp = array_search('--log', $_SERVER['argv'], true))
if (($tmp = array_search('-l', $_SERVER['argv'], strict: true))
|| ($tmp = array_search('-log', $_SERVER['argv'], strict: true))
|| ($tmp = array_search('--log', $_SERVER['argv'], strict: true))
) {
$_SERVER['argv'][$tmp] = '-o';
$_SERVER['argv'][$tmp + 1] = 'log:' . $_SERVER['argv'][$tmp + 1];
}

if ($tmp = array_search('--tap', $_SERVER['argv'], true)) {
if ($tmp = array_search('--tap', $_SERVER['argv'], strict: true)) {
unset($_SERVER['argv'][$tmp]);
$_SERVER['argv'] = array_merge($_SERVER['argv'], ['-o', 'tap']);
}
Expand Down Expand Up @@ -223,7 +223,7 @@ private function createRunner(): Runner
$runner,
(bool) $this->options['-s'],
'php://output',
(bool) $this->options['--cider']
(bool) $this->options['--cider'],
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Runner/Job.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public function run(bool $async = false): void
$pipes,
dirname($this->test->getFile()),
null,
['bypass_shell' => true]
['bypass_shell' => true],
);

foreach (array_keys($this->envVars) as $name) {
Expand All @@ -124,7 +124,7 @@ public function run(bool $async = false): void
}

if ($async) {
stream_set_blocking($this->stdout, false); // on Windows does not work with proc_open()
stream_set_blocking($this->stdout, enable: false); // on Windows does not work with proc_open()
} else {
while ($this->isRunning()) {
usleep(self::RunSleep); // stream_select() doesn't work with proc_open()
Expand Down
4 changes: 2 additions & 2 deletions src/Runner/Output/ConsolePrinter.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct(
Runner $runner,
bool $displaySkipped = false,
?string $file = null,
bool $ciderMode = false
bool $ciderMode = false,
) {
$this->runner = $runner;
$this->displaySkipped = $displaySkipped;
Expand Down Expand Up @@ -74,7 +74,7 @@ public function prepare(Test $test): void
} elseif (!str_starts_with($test->getFile(), $this->baseDir)) {
$common = array_intersect_assoc(
explode(DIRECTORY_SEPARATOR, $this->baseDir),
explode(DIRECTORY_SEPARATOR, $test->getFile())
explode(DIRECTORY_SEPARATOR, $test->getFile()),
);
$this->baseDir = '';
$prev = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/Runner/Output/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function end(): void
. ($this->results[Test::Failed] ? ", {$this->results[Test::Failed]} failures" : '')
. ($this->results[Test::Skipped] ? ", {$this->results[Test::Skipped]} skipped" : '')
. ($this->count !== $run ? ', ' . ($this->count - $run) . ' not run' : '')
. ')'
. ')',
);
}
}
6 changes: 3 additions & 3 deletions src/Runner/PhpInterpreter.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function __construct(string $path, array $args = [])
$pipes,
null,
null,
['bypass_shell' => true]
['bypass_shell' => true],
);
if ($proc === false) {
throw new \Exception("Cannot run PHP interpreter $path. Use -p option.");
Expand All @@ -55,7 +55,7 @@ public function __construct(string $path, array $args = [])
$pipes,
null,
null,
['bypass_shell' => true]
['bypass_shell' => true],
);
$output = stream_get_contents($pipes[1]);
$this->error = trim(stream_get_contents($pipes[2]));
Expand All @@ -66,7 +66,7 @@ public function __construct(string $path, array $args = [])
$parts = explode("\r\n\r\n", $output, 2);
$this->cgi = count($parts) === 2;
$this->info = @unserialize((string) strstr($parts[$this->cgi], 'O:8:"stdClass"'));
$this->error .= strstr($parts[$this->cgi], 'O:8:"stdClass"', true);
$this->error .= strstr($parts[$this->cgi], 'O:8:"stdClass"', before_needle: true);
if (!$this->info) {
throw new \Exception("Unable to detect PHP version (output: $output).");

Expand Down
Loading

0 comments on commit 9c163d8

Please sign in to comment.