Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Assert Laravel Package

simplesamlphp/assert

Fork of webmozart/assert that lets every assertion throw your chosen exception (or a default AssertionFailedException) instead of always InvalidArgumentException. Adds a few custom assertions aimed at XML/SAML2 use cases.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require simplesamlphp/assert:^1.5.0
    

    No additional configuration is required—it’s a drop-in wrapper around webmozart/assert with minor enhancements.

  2. First Use Case Replace basic PHP assertions with fluent, expressive checks. Example:

    use SimpleSAML\Assert\Assert;
    
    $userInput = ['name' => 'John', 'age' => 30, 'role' => UserRole::Admin];
    
    // Validate structure
    Assert::keyExists($userInput, 'name');
    Assert::keyExists($userInput, 'age');
    
    // Validate types (including enums)
    Assert::string($userInput['name']);
    Assert::numeric($userInput['age']);
    Assert::enum($userInput['role'], [UserRole::Admin, UserRole::User]); // New in 1.5.0
    
    // Validate constraints
    Assert::minLength($userInput['name'], 2);
    Assert::max($userInput['age'], 120);
    
  3. Where to Look First

    • API Docs: Browse the webmozart/assert docs for core functionality.
    • SimpleSAML Extensions: Check the SimpleSAMLPHP Assert package for Laravel-specific extensions.
    • Laravel Integration: Use in Form Requests, Service Providers, or Middleware for validation.
    • New Features: Review v1.5.0 release notes for enum support and stricter regex handling.

Implementation Patterns

1. Validation in Form Requests

Replace Laravel’s validate() with Assert for granular control:

use SimpleSAML\Assert\Assert;
use Illuminate\Http\Request;

public function rules()
{
    return [
        'email' => 'required|email',
        'age'   => 'required|integer',
        'role'  => 'required|string',
    ];
}

public function withValidator($validator)
{
    $data = $validator->getData();

    Assert::email($data['email']);
    Assert::min($data['age'], 18);
    Assert::max($data['age'], 99);
    Assert::enum($data['role'], [UserRole::Admin, UserRole::User]); // New enum check
}

2. Middleware for API Contracts

Enforce API input contracts in middleware:

use SimpleSAML\Assert\Assert;
use Closure;

public function handle($request, Closure $next)
{
    $payload = $request->json()->all();

    Assert::keyExists($payload, 'user_id');
    Assert::uuid($payload['user_id']);
    Assert::array($payload['metadata']);
    Assert::enum($payload['status'], [OrderStatus::Pending, OrderStatus::Completed]); // New enum check

    return $next($request);
}

3. Service Layer Validation

Validate method arguments in services:

use SimpleSAML\Assert\Assert;

class UserService {
    public function updateProfile(array $data, string $userId, UserRole $role)
    {
        Assert::keyExists($data, 'email');
        Assert::notEmpty($data['email']);
        Assert::uuid($userId);
        Assert::enum($role, [UserRole::Admin, UserRole::User]); // New enum check

        // Business logic...
    }
}

4. Laravel Service Providers

Validate config or dependencies:

public function register()
{
    $this->app->singleton(QueueWorker::class, function ($app) {
        $config = config('queue.worker');

        Assert::keyExists($config, 'connections');
        Assert::array($config['connections']);
        Assert::enum($config['connections']['default'], ['database', 'redis']); // New enum check

        return new QueueWorker($config);
    });
}

5. Custom Assertions with Enums

Extend with custom logic, including enum validation:

use SimpleSAML\Assert\Assert;

Assert::custom(function ($value, $message = 'Value is invalid') {
    if (!preg_match('/^[A-Z0-9]{8,}$/', $value)) {
        throw new \InvalidArgumentException($message);
    }
}, $value, 'Custom validation failed');

Assert::enum($value, [UserRole::Admin, UserRole::User]); // Built-in enum check

Gotchas and Tips

Pitfalls

  1. Overuse in Controllers

    • Avoid mixing Assert with Laravel’s built-in validation. Use Assert for low-level checks (e.g., method arguments) and Laravel’s Validator for user input.
    • Example: Use Assert in a UserRepository but Validator in a StoreUserRequest.
  2. Performance in Loops

    • Assert throws exceptions on failure. Use sparingly in performance-critical loops (e.g., bulk operations).
    • Workaround: Batch assertions or use try-catch blocks.
  3. Type Juggling

    • Assert::numeric() may behave unexpectedly with strings like "123" vs. 123. Explicitly cast if needed:
      Assert::numeric((int) $value);
      
  4. Laravel’s validate() vs. Assert

    • Laravel’s validate() returns a Validator object, while Assert throws exceptions. Combine them:
      $validator = Validator::make($data, $rules);
      if ($validator->fails()) {
          throw new \InvalidArgumentException($validator->errors()->first());
      }
      Assert::minLength($data['name'], 3); // Extra check
      
  5. New Regex Stricter in v1.5.0

    • The package now disallows newlines at the end of strings in regex checks. If you rely on multiline strings, ensure they are trimmed or handled explicitly:
      $value = trim($value); // Ensure no trailing newlines
      Assert::regex($value, '/pattern/');
      

Debugging Tips

  1. Custom Error Messages Pass custom messages to Assert:

    Assert::minLength($name, 3, 'Name must be at least 3 characters.');
    Assert::enum($role, [UserRole::Admin, UserRole::User], 'Invalid user role.');
    
  2. Stack Traces Exceptions include stack traces. For cleaner logs, wrap assertions:

    try {
        Assert::enum($role, [UserRole::Admin, UserRole::User]);
    } catch (\InvalidArgumentException $e) {
        \Log::error("Validation failed: {$e->getMessage()}");
        throw new \HttpException(422, $e->getMessage());
    }
    
  3. Testing Mock Assert in PHPUnit:

    $this->expectException(\InvalidArgumentException::class);
    Assert::enum($invalidRole, [UserRole::Admin, UserRole::User]);
    

Extension Points

  1. Custom Assertion Classes Create reusable validators, including enum checks:

    use SimpleSAML\Assert\Assert;
    
    class RoleAssert {
        public static function isValid(UserRole $role): void
        {
            Assert::enum($role, [UserRole::Admin, UserRole::User]);
        }
    }
    
  2. Laravel Service Provider Extensions Register global assertions, including enum validation:

    public function boot()
    {
        Assert::extend('active', function ($attribute, $value, $fail) {
            if (!$value) {
                $fail('The '.$attribute.' must be active.');
            }
        });
    
        // Add enum validation for a custom field
        Assert::extend('valid_status', function ($attribute, $value, $fail) {
            Assert::enum($value, [OrderStatus::Pending, OrderStatus::Completed]);
        });
    }
    
  3. Integration with Laravel Packages Use Assert in packages to enforce contracts, including enums:

    // In a package's service class
    public function __construct(array $config)
    {
        Assert::keyExists($config, 'api_key');
        Assert::string($config['api_key']);
        Assert::enum($config['timeout'], [Timeout::Short, Timeout::Long]); // New enum check
    }
    

Config Quirks

  • No Configuration: Unlike some Laravel packages, simplesamlphp/assert requires zero config.
  • Dependency Conflicts: Ensure webmozart/assert is not duplicated in composer.json (use replace if needed).
  • Enum Support: The new enum() method requires PHP 8.1+ for full functionality (backward compatibility is maintained for older PHP versions).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky