Skip to content

Commit

Permalink
Improve string asserts that assume some othe property besides being a…
Browse files Browse the repository at this point in the history
… non-empty-string
  • Loading branch information
ondrejmirtes committed Aug 19, 2024
1 parent ae758a2 commit be3dcd8
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/Type/WebMozartAssert/AssertTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -757,12 +757,22 @@ private function getExpressionResolvers(): array
];

foreach (['contains', 'startsWith', 'endsWith'] as $name) {
$this->resolvers[$name] = function (Scope $scope, Arg $value, Arg $subString) use ($name): array {
$this->resolvers[$name] = static function (Scope $scope, Arg $value, Arg $subString) use ($name): array {
if ($scope->getType($subString->value)->isNonEmptyString()->yes()) {
return self::createIsNonEmptyStringAndSomethingExprPair($name, [$value, $subString]);
}

return [$this->resolvers['string']($scope, $value), null];
$expr = new FuncCall(
new Name('is_string'),
[$value]
);

$rootExpr = new BooleanAnd(
$expr,
new FuncCall(new Name('FAUX_FUNCTION_ ' . $name), [$value, $subString])
);

return [$expr, $rootExpr];
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ public function testExtension(): void
'Call to static method Webmozart\Assert\Assert::isInstanceOf() with Exception and class-string<Exception> will always evaluate to true.',
119,
],
[
'Call to static method Webmozart\Assert\Assert::startsWith() with \'value\' and string will always evaluate to true.',
126,
],
]);
}

Expand Down
8 changes: 8 additions & 0 deletions tests/Type/WebMozartAssert/data/impossible-check.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ public function testInstanceOfClassString(\Exception $e, string $name): void
Assert::isInstanceOf($e, $name);
}

public function testStartsWith(string $a): void
{
Assert::startsWith("value", "val");
Assert::startsWith("value", $a);
Assert::startsWith("value", $a);
Assert::startsWith("value", "bix");
}

}

interface Bar {};
Expand Down
7 changes: 7 additions & 0 deletions tests/Type/WebMozartAssert/data/string.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,11 @@ public function notWhitespaceOnly(string $a): void
assertType('non-empty-string', $a);
}

public function testStartsWithMixedHaystack($haystack, string $a): void
{
assertType('mixed', $haystack);
Assert::startsWith($haystack, $a);
assertType('string', $haystack);
}

}

0 comments on commit be3dcd8

Please sign in to comment.