Skip to content

Commit

Permalink
Merge StringUtil into ScalarComparator
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Oct 30, 2024
1 parent 191fc8d commit 6a8ffd1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 51 deletions.
33 changes: 32 additions & 1 deletion src/ScalarComparator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@
use function mb_strtolower;
use function method_exists;
use function sprintf;
use function strlen;
use function substr;
use SebastianBergmann\Exporter\Exporter;

/**
* Compares scalar or NULL values for equality.
*/
class ScalarComparator extends Comparator
{
private const OVERLONG_PREFIX_THRESHOLD = 40;
private const KEEP_PREFIX_CHARS = 15;

public function accepts(mixed $expected, mixed $actual): bool
{
return ((is_scalar($expected) xor null === $expected) &&
Expand Down Expand Up @@ -57,7 +62,7 @@ public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0,
}

if ($expectedToCompare !== $actualToCompare && is_string($expected) && is_string($actual)) {
[$expected, $actual] = StringUtil::removeOverlongCommonPrefix($expected, $actual);
[$expected, $actual] = self::removeOverlongCommonPrefix($expected, $actual);

throw new ComparisonFailure(
$expected,
Expand All @@ -83,4 +88,30 @@ public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0,
);
}
}

/**
* @return array{string, string}
*/
private static function removeOverlongCommonPrefix(string $string1, string $string2): array
{
$commonPrefix = self::findCommonPrefix($string1, $string2);

if (strlen($commonPrefix) > self::OVERLONG_PREFIX_THRESHOLD) {
$string1 = '...' . substr($string1, strlen($commonPrefix) - self::KEEP_PREFIX_CHARS);
$string2 = '...' . substr($string2, strlen($commonPrefix) - self::KEEP_PREFIX_CHARS);
}

return [$string1, $string2];
}

private static function findCommonPrefix(string $string1, string $string2): string
{
for ($i = 0; $i < strlen($string1); $i++) {
if (!isset($string2[$i]) || $string1[$i] != $string2[$i]) {
break;
}
}

return substr($string1, 0, $i);
}
}
50 changes: 0 additions & 50 deletions src/StringUtil.php

This file was deleted.

0 comments on commit 6a8ffd1

Please sign in to comment.