Add slugify Method to Str Class and toBeSlug Assertion to Expectation Class
This pull request introduces a new slugify method to the Str class and a corresponding toBeSlug assertion method to the Expectation class in the PestPHP framework. Additionally, it includes comprehensive tests for the toBeSlug method to ensure its functionality.
Changes:
-
StrClass
Added slugify method to convert a string into a URL-friendly slug.
<?php
/**
* Converts the given `$target` to a URL-friendly "slug".
*/
public static function slugify(string $target): string
{
$target = preg_replace('/[^a-zA-Z0-9]+/', '-', $target);
return strtolower(trim($target, '-'));
}
-
ExpectationClass:
Added toBeSlug method to assert that a value can be converted to a slug.
<?php
/**
* Asserts that the value can be converted to a slug
*
* @return self<TValue>
*/
public function toBeSlug(string $message = ''): self
{
if ($message === '') {
$message = "Failed asserting that {$this->value} can be converted to a slug.";
}
$slug = Str::slugify((string) $this->value);
Assert::assertNotEmpty($slug, $message);
return $this;
}
- Tests
<?php
use PHPUnit\Framework\ExpectationFailedException;
test('pass', function () {
expect('This is a Test String!')->toBeSlug()
->and('Another Test String')->toBeSlug();
});
test('failures', function () {
expect('')->toBeSlug();
})->throws(ExpectationFailedException::class);
test('failures with custom message', function () {
expect('')->toBeSlug('oh no!');
})->throws(ExpectationFailedException::class, 'oh no!');
test('failures with default message', function () {
expect('')->toBeSlug();
})->throws(ExpectationFailedException::class, 'Failed asserting that can be converted to a slug.');
test('not failures', function () {
expect('This is a Test String!')->not->toBeSlug();
})->throws(ExpectationFailedException::class);
This PR enhances the PestPHP framework by adding useful string manipulation and assertion functionalities. Please review the changes and provide feedback. Thank you!
Personally, I think this would be better as a plugin (although, it's fairly small). 🤔 But will leave it for another core team member. 👍🏻
@owenvoke Thanks for sharing your thoughts! I'll make a note of it and await the decision from the core team member :).
I think using the toBeSlug method in tests could lead to false positives. There are different ways to create slugs, and having toBeSlug only verify slugs generated by slugify doesn’t quite make sense to me.
This feels more like something that should be in pest-plugin-laravel. If it’s going to be included there, it’d make more sense to use Laravel’s Str::slug() method instead of writing a whole new slugify function.
i like it.