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

Commons Ensure Bundle Laravel Package

20steps/commons-ensure-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require 20steps/commons-ensure-bundle
    

    Add the bundle to config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel):

    'providers' => [
        // ...
        Twentysteps\Commons\EnsureBundle\TwentystepsCommonsEnsureBundle::class,
    ],
    
  2. First Use Case: Validate input early in a controller or service method:

    use Twentysteps\Commons\Ensure\Ensure;
    
    public function update(Request $request, $id)
    {
        Ensure::state($request->has('name'), 'Name is required.');
        Ensure::state($id > 0, 'ID must be positive.');
        // Proceed with logic...
    }
    

Where to Look First

  • Core Methods: Focus on Ensure::state(), Ensure::notNull(), Ensure::true(), and Ensure::false() in the source.
  • Exceptions: Review EnsureException for error handling (e.g., logging, custom responses).
  • Symfony Integration: Check TwentystepsCommonsEnsureBundle for service registration.

Implementation Patterns

Usage Patterns

  1. Input Validation:

    // Validate request data
    Ensure::state($request->filled('email'), 'Email is required.');
    Ensure::state(filter_var($request->email, FILTER_VALIDATE_EMAIL), 'Invalid email.');
    
  2. Pre-Conditions in Services:

    public function processOrder(Order $order)
    {
        Ensure::state($order->isPaid(), 'Order must be paid before processing.');
        Ensure::state($order->hasItems(), 'Order must contain items.');
        // Process...
    }
    
  3. Post-Conditions:

    public function deleteUser(User $user)
    {
        $deleted = $user->delete();
        Ensure::state($deleted, 'Failed to delete user.');
    }
    
  4. Custom Assertions:

    Ensure::state(
        strlen($password) >= 8,
        'Password must be at least 8 characters.'
    );
    

Workflows

  • Early Failure: Use in constructors or method entry points to fail fast.

  • Logging: Wrap Ensure calls in try-catch to log EnsureException details:

    try {
        Ensure::state($condition, 'Error message.');
    } catch (EnsureException $e) {
        \Log::error($e->getMessage());
        abort(400, $e->getMessage());
    }
    
  • API Responses: Return JSON errors for API endpoints:

    catch (EnsureException $e) {
        return response()->json(['error' => $e->getMessage()], 400);
    }
    

Integration Tips

  • Laravel Form Requests: Combine with Laravel’s FormRequest validation for layered checks:

    public function rules()
    {
        return ['email' => 'required|email'];
    }
    
    public function withValidator($validator)
    {
        Ensure::state($validator->passes(), 'Validation failed.');
    }
    
  • Dependency Injection: Inject Ensure as a service (if extended):

    public function __construct(private Ensure $ensure) {}
    
  • Testing: Use EnsureException in unit tests to verify pre-conditions:

    $this->expectException(EnsureException::class);
    $this->expectExceptionMessage('ID must be positive.');
    $service->process(-1);
    

Gotchas and Tips

Pitfalls

  1. Always-On Assertions: Unlike PHP’s assert(), these checks never disable. Avoid using them for non-critical logic (e.g., performance-sensitive paths).

  2. Exception Handling:

    • Uncaught EnsureException will terminate execution. Always wrap in try-catch for APIs or CLI.
    • Default exception messages may leak internal logic. Customize messages for security:
      Ensure::state($user->exists(), 'User not found.');
      
  3. Performance:

    • Heavy checks (e.g., database queries) in Ensure calls can slow down validation. Offload to lighter checks where possible.
  4. Outdated Package:

    • Last release in 2018. Verify compatibility with your PHP/Laravel version (tested up to PHP 7.1).
    • Fork or extend if missing features (e.g., Laravel-specific integrations).

Debugging

  • Stack Traces: EnsureException includes the failing condition and message. Use for debugging:

    catch (EnsureException $e) {
        \Log::debug('Failed condition: ' . $e->getCondition());
    }
    
  • Custom Exceptions: Extend EnsureException for domain-specific errors:

    class ValidationException extends EnsureException {}
    Ensure::state($condition, 'Error.', new ValidationException());
    

Tips

  1. Consistent Messaging: Use consistent error formats (e.g., "Field {field} is required.") for API responses.

  2. Localization: Store messages in language files (e.g., Laravel’s resources/lang) and pass them dynamically:

    Ensure::state($condition, __('validation.required', ['field' => 'email']));
    
  3. Combine with Laravel:

    • Use Ensure for business logic and Laravel’s validator for input sanitization.
    • Example:
      $validator = Validator::make($request->all(), ['email' => 'required|email']);
      Ensure::state($validator->passes(), 'Invalid input.');
      
  4. Extending the Bundle:

    • Add custom methods to Ensure by extending the class:
      class CustomEnsure extends Ensure {
          public static function isActive(User $user) {
              self::state($user->active, 'User must be active.');
          }
      }
      
    • Override the bundle’s service in Laravel’s AppServiceProvider:
      $this->app->bind(Ensure::class, function () {
          return new CustomEnsure();
      });
      
  5. Testing Edge Cases:

    • Test Ensure with null, false, and edge values (e.g., 0, empty strings) to ensure robust validation.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope