PHP code example of serhiilabs / laravel-ai-validator
1. Go to this page and download the library: Download serhiilabs/laravel-ai-validator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
serhiilabs / laravel-ai-validator example snippets
use SerhiiLabs\AiValidator\AiRule;
$request->validate([
'bio' => ['speech or personal attacks')],
'city' => ['
use SerhiiLabs\AiValidator\AiRule;
$validator = Validator::make($data, [
'company_name' => ['
use SerhiiLabs\AiValidator\AiRule;
class StoreProfileRequest extends FormRequest
{
public function rules(): array
{
return [
'bio' => ['tral sentiment, no complaints or insults')],
];
}
}
'presets' => [
'profanity-free' => 'No profanity, slurs, vulgar language, or sexually explicit content.',
'no-pii' => 'No emails, phone numbers, SSNs, credit cards, or physical addresses.',
'professional-tone' => 'Professional tone. No slang, aggression, or inappropriate humor.',
'no-spam' => 'No spam, keyword stuffing, repetitive gibberish, or promotional content.',
'bio-check' => 'Must be a professional biography, 1-3 sentences.',
],
AiRule::preset('profanity-free');
AiRule::preset('bio-check')
->timeout(30)
->errorMessage('Please write a short professional bio.');
AiRule::make('professional biography, 1-3 sentences')
->errorMessage('Please write a short professional bio.')
use Closure;
use SerhiiLabs\AiValidator\Contracts\RuleOptionInterface;
use SerhiiLabs\AiValidator\ValueObjects\ValidationContext;
use SerhiiLabs\AiValidator\ValueObjects\ValidationResult;
final readonly class LogValidation implements RuleOptionInterface
{
public function handle(ValidationContext $ctx, Closure $next): ValidationResult
{
$result = $next($ctx);
Log::info('AI validation', [
'attribute' => $ctx->attribute,
'passed' => $result->passed,
]);
return $result;
}
}
use SerhiiLabs\AiValidator\Contracts\ResultCacheInterface;
$this->app->singleton(ResultCacheInterface::class, MyCacheAdapter::class);
use SerhiiLabs\AiValidator\Exceptions\DriverException;
use SerhiiLabs\AiValidator\Exceptions\RateLimitExceededException;
try {
$result = $aiValidator->validate($ctx);
} catch (RateLimitExceededException $e) {
// Rate limit hit - $e->getMessage()
// Custom TTL (seconds)
AiRule::make('not spam')->cacheTtl(1800)
// Disable cache for this rule
AiRule::make('constructive feedback')->withoutCache()
// Disable rate limit for critical validation
AiRule::make('fraud check')->withoutRateLimit()
final readonly class PerUserRateLimit implements RuleOptionInterface
{
public function handle(ValidationContext $ctx, Closure $next): ValidationResult
{
$key = 'ai_validator:' . auth()->id();
if (! RateLimiter::attempt($key, 10, fn () => null, 60)) {
throw new RateLimitExceededException('Too many requests.');
}
return $next($ctx);
}
}
// Usage: AiRule::make('real company name')->with(new PerUserRateLimit)
use SerhiiLabs\AiValidator\Exceptions\RateLimitExceededException;
use SerhiiLabs\AiValidator\Testing\AiValidatorFake;
// All AI rules pass
AiValidatorFake::pass();
// All AI rules fail with a message
AiValidatorFake::fail('Not a real company.');
// Clean up after test
AiValidatorFake::reset();
afterEach(fn () => AiValidatorFake::reset());
use SerhiiLabs\AiValidator\ValueObjects\ValidationResult;
$fake = AiValidatorFake::pass();
$fake->expectDescription('not spam', ValidationResult::failed('Looks like spam.'));
// Rules matching "not spam" will fail, everything else passes
$fake = AiValidatorFake::pass();
// ... run your code ...
$fake->assertCalledTimes(2);
$fake->assertCalledWithDescription('real company name');
$fake->assertCalledWithValue('Acme Corp');
$fake->assertNotCalled();
// Access raw call log for custom assertions
$fake->callLog(); // [['value' => ..., 'description' => ..., 'attribute' => ..., 'options' => [...]], ...]