Skip to content

Commit

Permalink
coding style
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Mar 2, 2023
1 parent 13fdf3d commit a1752e1
Show file tree
Hide file tree
Showing 20 changed files with 126 additions and 125 deletions.
2 changes: 1 addition & 1 deletion ncs.xml
Expand Up @@ -3,6 +3,6 @@
<rule ref="$presets/php72.xml"/>

<rule ref="SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly">
<severity>0</severity>
<exclude-pattern>./tests/*/*.phpt</exclude-pattern>
</rule>
</ruleset>
2 changes: 1 addition & 1 deletion src/CodeCoverage/Collector.php
Expand Up @@ -55,7 +55,7 @@ public static function start(string $file, string $engine): void

} elseif (!in_array(
$engine,
array_map(function (array $engineInfo) { return $engineInfo[0]; }, self::detectEngines()),
array_map(fn(array $engineInfo) => $engineInfo[0], self::detectEngines()),
true
)) {
throw new \LogicException("Code coverage engine '$engine' is not supported.");
Expand Down
22 changes: 12 additions & 10 deletions src/Framework/Assert.php
Expand Up @@ -121,7 +121,7 @@ public static function contains($needle, $actual, ?string $description = null):
if (!is_string($needle)) {
self::fail(self::describe('Needle %1 should be string'), $needle);

} elseif ($needle !== '' && strpos($actual, $needle) === false) {
} elseif ($needle !== '' && !str_contains($actual, $needle)) {
self::fail(self::describe('%1 should contain %2', $description), $actual, $needle);
}
} else {
Expand All @@ -146,7 +146,7 @@ public static function notContains($needle, $actual, ?string $description = null
if (!is_string($needle)) {
self::fail(self::describe('Needle %1 should be string'), $needle);

} elseif ($needle === '' || strpos($actual, $needle) !== false) {
} elseif ($needle === '' || str_contains($actual, $needle)) {
self::fail(self::describe('%1 should not contain %2', $description), $actual, $needle);
}
} else {
Expand Down Expand Up @@ -316,8 +316,8 @@ public static function type($type, $value, ?string $description = null): void
self::fail(self::describe(gettype($value) . " should be $type", $description));
}
} elseif (!$value instanceof $type) {
$actual = is_object($value) ? get_class($value) : gettype($value);
$type = is_object($type) ? get_class($type) : $type;
$actual = is_object($value) ? $value::class : gettype($value);
$type = is_object($type) ? $type::class : $type;
self::fail(self::describe("$actual should be instance of $type", $description));
}
}
Expand All @@ -331,7 +331,8 @@ public static function exception(
string $class,
?string $message = null,
$code = null
): ?\Throwable {
): ?\Throwable
{
self::$counter++;
$e = null;
try {
Expand All @@ -343,7 +344,7 @@ public static function exception(
self::fail("$class was expected, but none was thrown");

} elseif (!$e instanceof $class) {
self::fail("$class was expected but got " . get_class($e) . ($e->getMessage() ? " ({$e->getMessage()})" : ''), null, null, $e);
self::fail("$class was expected but got " . $e::class . ($e->getMessage() ? " ({$e->getMessage()})" : ''), null, null, $e);

} elseif ($message && !self::isMatching($message, $e->getMessage())) {
self::fail("$class with a message matching %2 was expected but got %1", $e->getMessage(), $message, $e);
Expand Down Expand Up @@ -506,7 +507,8 @@ public static function fail(
$expected = null,
?\Throwable $previous = null,
?string $outputName = null
): void {
): void
{
$e = new AssertException($message, $expected, $actual, $previous);
$e->outputName = $outputName;
if (self::$onFailure) {
Expand Down Expand Up @@ -587,10 +589,10 @@ public static function expandMatchingPatterns(string $pattern, $actual): array

$parts = preg_split('#(%)#', $pattern, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = count($parts); $i >= 0; $i--) {
$patternX = implode(array_slice($parts, 0, $i));
$patternX = implode('', array_slice($parts, 0, $i));
$patternY = "$patternX%A?%";
if (self::isMatching($patternY, $actual)) {
$patternZ = implode(array_slice($parts, $i));
$patternZ = implode('', array_slice($parts, $i));
break;
}
}
Expand Down Expand Up @@ -654,7 +656,7 @@ private static function isEqual($expected, $actual, int $level = 0, $objects = n
$diff = abs($expected - $actual);
return ($diff < self::Epsilon) || ($diff / max(abs($expected), abs($actual)) < self::Epsilon);

case is_object($expected) && is_object($actual) && get_class($expected) === get_class($actual):
case is_object($expected) && is_object($actual) && $expected::class === $actual::class:
$objects = $objects ? clone $objects : new \SplObjectStorage;
if (isset($objects[$expected])) {
return $objects[$expected] === $actual;
Expand Down
4 changes: 1 addition & 3 deletions src/Framework/DataProvider.php
Expand Up @@ -26,9 +26,7 @@ public static function load(string $file, string $query = ''): array
}

if (pathinfo($file, PATHINFO_EXTENSION) === 'php') {
$data = (function () {
return require func_get_arg(0);
})(realpath($file));
$data = (fn() => require func_get_arg(0))(realpath($file));

if ($data instanceof \Traversable) {
$data = iterator_to_array($data);
Expand Down
10 changes: 6 additions & 4 deletions src/Framework/DomQuery.php
Expand Up @@ -17,17 +17,19 @@ class DomQuery extends \SimpleXMLElement
{
public static function fromHtml(string $html): self
{
if (strpos($html, '<') === false) {
if (!str_contains($html, '<')) {
$html = '<body>' . $html;
}

// parse these elements as void
$html = preg_replace('#<(keygen|source|track|wbr)(?=\s|>)((?:"[^"]*"|\'[^\']*\'|[^"\'>])*+)(?<!/)>#', '<$1$2 />', $html);

// fix parsing of </ inside scripts
$html = preg_replace_callback('#(<script(?=\s|>)(?:"[^"]*"|\'[^\']*\'|[^"\'>])*+>)(.*?)(</script>)#s', function (array $m): string {
return $m[1] . str_replace('</', '<\/', $m[2]) . $m[3];
}, $html);
$html = preg_replace_callback(
'#(<script(?=\s|>)(?:"[^"]*"|\'[^\']*\'|[^"\'>])*+>)(.*?)(</script>)#s',
fn(array $m): string => $m[1] . str_replace('</', '<\/', $m[2]) . $m[3],
$html
);

$dom = new \DOMDocument;
$old = libxml_use_internal_errors(true);
Expand Down
12 changes: 6 additions & 6 deletions src/Framework/Dumper.php
Expand Up @@ -72,7 +72,7 @@ public static function toLine($var): string
return "[$out]";

} elseif ($var instanceof \Throwable) {
return 'Exception ' . get_class($var) . ': ' . ($var->getCode() ? '#' . $var->getCode() . ' ' : '') . $var->getMessage();
return 'Exception ' . $var::class . ': ' . ($var->getCode() ? '#' . $var->getCode() . ' ' : '') . $var->getMessage();

} elseif ($var instanceof Expect) {
return $var->dump();
Expand All @@ -95,7 +95,7 @@ public static function toLine($var): string
*/
private static function objectToLine($object): string
{
$line = get_class($object);
$line = $object::class;
if ($object instanceof \DateTime || $object instanceof \DateTimeInterface) {
$line .= '(' . $object->format('Y-m-d H:i:s O') . ')';
}
Expand Down Expand Up @@ -128,7 +128,7 @@ private static function _toPhp(&$var, array &$list = [], int $level = 0, int &$l
{
if (is_float($var)) {
$var = str_replace(',', '.', "$var");
return strpos($var, '.') === false ? $var . '.0' : $var;
return !str_contains($var, '.') ? $var . '.0' : $var;

} elseif (is_bool($var)) {
return $var ? 'true' : 'false';
Expand Down Expand Up @@ -173,7 +173,7 @@ private static function _toPhp(&$var, array &$list = [], int $level = 0, int &$l
}

unset($var[$marker]);
if (strpos($outShort, "\n") === false && strlen($outShort) < self::$maxLength) {
if (!str_contains($outShort, "\n") && strlen($outShort) < self::$maxLength) {
$line = $oldLine;
$out = $outShort;
}
Expand All @@ -192,7 +192,7 @@ private static function _toPhp(&$var, array &$list = [], int $level = 0, int &$l

$arr = (array) $var;
$space = str_repeat("\t", $level);
$class = get_class($var);
$class = $var::class;
$used = &$list[spl_object_hash($var)];

if (empty($arr)) {
Expand Down Expand Up @@ -356,7 +356,7 @@ public static function dumpException(\Throwable $e): string
'%2' => self::color('yellow') . self::toLine($expected) . self::color('white'),
]);
} else {
$message = ($e instanceof \ErrorException ? Helpers::errorTypeToString($e->getSeverity()) : get_class($e))
$message = ($e instanceof \ErrorException ? Helpers::errorTypeToString($e->getSeverity()) : $e::class)
. ': ' . preg_replace('#[\x00-\x09\x0B-\x1F]+#', ' ', $e->getMessage());
}

Expand Down
10 changes: 6 additions & 4 deletions src/Framework/Environment.php
Expand Up @@ -85,9 +85,11 @@ public static function setupColors(): void
: @stream_isatty(STDOUT)) // @ may trigger error 'cannot cast a filtered stream on this system'
);

ob_start(function (string $s): string {
return self::$useColors ? $s : Dumper::removeColors($s);
}, 1, PHP_OUTPUT_HANDLER_FLUSHABLE);
ob_start(
fn(string $s): string => self::$useColors ? $s : Dumper::removeColors($s),
1,
PHP_OUTPUT_HANDLER_FLUSHABLE
);
}


Expand Down Expand Up @@ -191,7 +193,7 @@ public static function getTestAnnotations(): array
public static function bypassFinals(): void
{
FileMutator::addMutator(function (string $code): string {
if (strpos($code, 'final') !== false) {
if (str_contains($code, 'final')) {
$tokens = token_get_all($code, TOKEN_PARSE);
$code = '';
foreach ($tokens as $token) {
Expand Down
13 changes: 7 additions & 6 deletions src/Framework/TestCase.php
Expand Up @@ -36,9 +36,10 @@ public function run(): void
throw new \LogicException('Calling TestCase::run($method) is deprecated. Use TestCase::runTest($method) instead.');
}

$methods = array_values(preg_grep(self::MethodPattern, array_map(function (\ReflectionMethod $rm): string {
return $rm->getName();
}, (new \ReflectionObject($this))->getMethods())));
$methods = array_values(preg_grep(
self::MethodPattern,
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']))) {
$method = reset($tmp);
Expand Down Expand Up @@ -153,7 +154,7 @@ public function runTest(string $method, ?array $args = null): void
*/
protected function getData(string $provider)
{
if (strpos($provider, '.') === false) {
if (!str_contains($provider, '.')) {
return $this->$provider();
} else {
$rc = new \ReflectionClass($this);
Expand Down Expand Up @@ -183,7 +184,7 @@ protected function tearDown()

private function silentTearDown(): void
{
set_error_handler(function () {});
set_error_handler(fn() => null);
try {
$this->tearDown();
} catch (\Throwable $e) {
Expand Down Expand Up @@ -247,7 +248,7 @@ private function prepareTestData(\ReflectionMethod $method, array $dataprovider)

foreach ($res as $k => $set) {
if (!is_array($set)) {
$type = is_object($set) ? get_class($set) : gettype($set);
$type = is_object($set) ? $set::class : gettype($set);
throw new TestCaseException("Data provider $provider() item '$k' must be an array, $type given.");
}

Expand Down
114 changes: 58 additions & 56 deletions src/Runner/CliTester.php
Expand Up @@ -98,64 +98,66 @@ private function loadOptions(): CommandLine
$outputFiles = [];

echo <<<'XX'
_____ ___ ___ _____ ___ ___
|_ _/ __)( __/_ _/ __)| _ )
|_| \___ /___) |_| \___ |_|_\ v2.5
XX;

$cmd = new CommandLine(<<<'XX'
Usage:
tester [options] [<test file> | <directory>]...
Options:
-p <path> Specify PHP interpreter to run (default: php).
-c <path> Look for php.ini file (or look in directory) <path>.
-C Use system-wide php.ini.
-d <key=value>... Define INI entry 'key' with value 'value'.
-s Show information about skipped tests.
--stop-on-fail Stop execution upon the first failure.
-j <num> Run <num> jobs in parallel (default: 8).
-o <console|tap|junit|log|none> (e.g. -o junit:output.xml)
Specify one or more output formats with optional file name.
-w | --watch <path> Watch directory.
-i | --info Show tests environment info and exit.
--setup <path> Script for runner setup.
--temp <path> Path to temporary directory. Default by sys_get_temp_dir().
--colors [1|0] Enable or disable colors.
--coverage <path> Generate code coverage report to file.
--coverage-src <path> Path to source code.
-h | --help This help.
XX
, [
'-c' => [CommandLine::Realpath => true],
'--watch' => [CommandLine::Repeatable => true, CommandLine::Realpath => true],
'--setup' => [CommandLine::Realpath => true],
'--temp' => [CommandLine::Realpath => true],
'paths' => [CommandLine::Repeatable => true, CommandLine::Value => getcwd()],
'--debug' => [],
'--cider' => [],
'--coverage-src' => [CommandLine::Realpath => true, CommandLine::Repeatable => true],
'-o' => [CommandLine::Repeatable => true, CommandLine::Normalizer => function ($arg) use (&$outputFiles) {
[$format, $file] = explode(':', $arg, 2) + [1 => null];

if (isset($outputFiles[$file])) {
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."
);
} elseif ($file === null) {
$this->stdoutFormat = $format;
}
_____ ___ ___ _____ ___ ___
|_ _/ __)( __/_ _/ __)| _ )
|_| \___ /___) |_| \___ |_|_\ v2.5
XX;

$cmd = new CommandLine(
<<<'XX'
Usage:
tester [options] [<test file> | <directory>]...
Options:
-p <path> Specify PHP interpreter to run (default: php).
-c <path> Look for php.ini file (or look in directory) <path>.
-C Use system-wide php.ini.
-d <key=value>... Define INI entry 'key' with value 'value'.
-s Show information about skipped tests.
--stop-on-fail Stop execution upon the first failure.
-j <num> Run <num> jobs in parallel (default: 8).
-o <console|tap|junit|log|none> (e.g. -o junit:output.xml)
Specify one or more output formats with optional file name.
-w | --watch <path> Watch directory.
-i | --info Show tests environment info and exit.
--setup <path> Script for runner setup.
--temp <path> Path to temporary directory. Default by sys_get_temp_dir().
--colors [1|0] Enable or disable colors.
--coverage <path> Generate code coverage report to file.
--coverage-src <path> Path to source code.
-h | --help This help.
XX,
[
'-c' => [CommandLine::Realpath => true],
'--watch' => [CommandLine::Repeatable => true, CommandLine::Realpath => true],
'--setup' => [CommandLine::Realpath => true],
'--temp' => [CommandLine::Realpath => true],
'paths' => [CommandLine::Repeatable => true, CommandLine::Value => getcwd()],
'--debug' => [],
'--cider' => [],
'--coverage-src' => [CommandLine::Realpath => true, CommandLine::Repeatable => true],
'-o' => [CommandLine::Repeatable => true, CommandLine::Normalizer => function ($arg) use (&$outputFiles) {
[$format, $file] = explode(':', $arg, 2) + [1 => null];

if (isset($outputFiles[$file])) {
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."
);
} elseif ($file === null) {
$this->stdoutFormat = $format;
}

$outputFiles[$file] = true;
$outputFiles[$file] = true;

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

if (isset($_SERVER['argv'])) {
if (($tmp = array_search('-l', $_SERVER['argv'], true))
Expand Down
2 changes: 1 addition & 1 deletion src/Runner/Output/ConsolePrinter.php
Expand Up @@ -85,7 +85,7 @@ public function prepare(Test $test): void
{
if ($this->baseDir === null) {
$this->baseDir = dirname($test->getFile()) . DIRECTORY_SEPARATOR;
} elseif (strpos($test->getFile(), $this->baseDir) !== 0) {
} elseif (!str_starts_with($test->getFile(), $this->baseDir)) {
$common = array_intersect_assoc(
explode(DIRECTORY_SEPARATOR, $this->baseDir),
explode(DIRECTORY_SEPARATOR, $test->getFile())
Expand Down
2 changes: 1 addition & 1 deletion src/Runner/PhpInterpreter.php
Expand Up @@ -50,7 +50,7 @@ public function __construct(string $path, array $args = [])
proc_close($proc);

$args = ' ' . implode(' ', array_map([Helpers::class, 'escapeArg'], $args));
if (strpos($output, 'phpdbg') !== false) {
if (str_contains($output, 'phpdbg')) {
$args = ' -qrrb -S cli' . $args;
}

Expand Down

0 comments on commit a1752e1

Please sign in to comment.