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

campanda/commons-ensure-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require campanda/commons-ensure-bundle
    

    Add to config/bundles.php (Symfony) or ensure autoloading is configured in composer.json:

    "autoload": {
        "psr-4": {
            "campanda\\Commons\\EnsureBundle\\": "vendor/campanda/commons-ensure-bundle"
        }
    }
    
  2. First Use Case: Validate input in a controller or service method:

    use campanda\Commons\EnsureBundle\Ensure;
    
    public function update(Request $request, $id) {
        $name = $request->input('name');
        Ensure::isNotEmpty($name, 'Name cannot be empty');
        // Proceed with logic...
    }
    
  3. Key Classes:

    • Ensure: Static facade for assertions.
    • EnsureException: Thrown on failed checks (extends \RuntimeException).

Implementation Patterns

Common Workflows

  1. Input Validation:

    // Validate required fields
    Ensure::isNotEmpty($userInput, 'Field "%s" is required', $fieldName);
    Ensure::isTrue($isValid, 'Invalid %s provided', $fieldName);
    
    // Validate ranges
    Ensure::isGreaterThan(0, $age, 'Age must be positive');
    Ensure::isLessThan(120, $age, 'Age must be realistic');
    
  2. Pre-Conditions in Methods:

    public function processOrder(Order $order) {
        Ensure::isInstanceOf($order, Order::class, 'Order must be an instance of Order');
        Ensure::isTrue($order->isValid(), 'Order is not valid for processing');
        // Process...
    }
    
  3. Post-Conditions:

    public function save(): bool {
        $result = $this->repository->save();
        Ensure::isTrue($result, 'Failed to save entity');
        return true;
    }
    
  4. Collection Checks:

    Ensure::isNotEmpty($items, 'No items provided');
    Ensure::isArray($items, 'Items must be an array');
    Ensure::isTrue(count($items) <= 100, 'Max 100 items allowed');
    

Integration Tips

  • Symfony Forms: Use in form type validators:
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();
            Ensure::isTrue(isset($data['required_field']), 'Required field missing');
        });
    }
    
  • API Controllers: Centralize validation in a base controller:
    abstract class ApiController extends Controller {
        protected function validateRequest(array $rules) {
            foreach ($rules as $field => $message) {
                Ensure::isNotEmpty(request($field), $message);
            }
        }
    }
    
  • Domain Services: Enforce invariants:
    public function transfer(Account $from, Account $to, float $amount) {
        Ensure::isTrue($from->hasSufficientFunds($amount), 'Insufficient funds');
        // Transfer logic...
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Avoid overusing in hot paths (e.g., loops). Benchmark critical sections.
    • Example: Validate collections once before iteration:
      Ensure::isNotEmpty($users); // Do this once, not per loop iteration
      foreach ($users as $user) { ... }
      
  2. Message Formatting:

    • Use sprintf-style placeholders carefully. Malformed messages may cause errors:
      // ❌ Avoid unmatched placeholders
      Ensure::isTrue($valid, 'User %s is invalid', $user->name); // Throws if $valid is true
      
    • Fix: Use consistent placeholders or separate logic:
      Ensure::isTrue($valid, 'User "%s" is invalid', $user->name);
      
  3. Exception Handling:

    • EnsureException extends \RuntimeException. Handle globally if needed:
      // In AppServiceProvider@boot()
      app()->error(function (EnsureException $e, $request) {
          return response()->json(['error' => $e->getMessage()], 400);
      });
      
  4. Legacy Code:

    • The package is unmaintained (last release: 2018). Test thoroughly in production.
    • Consider forking if critical bugs arise (e.g., edge-case message formatting).

Debugging Tips

  1. Stack Traces:

    • Ensure exceptions include context. Add custom data to messages:
      Ensure::isTrue($condition, 'Failed at step "%s" with data: %s', $step, json_encode($data));
      
  2. Logging:

    • Log failed assertions in development:
      try {
          Ensure::isTrue($condition, 'Critical check failed');
      } catch (EnsureException $e) {
          \Log::error($e->getMessage(), ['trace' => $e->getTraceAsString()]);
          throw $e;
      }
      
  3. Testing:

    • Mock Ensure in unit tests to simulate failures:
      $this->partialMock(Ensure::class, 'isTrue')
           ->method('isTrue')
           ->with($this->equalTo(false), $this->anything())
           ->willThrowException(new EnsureException('Test failure'));
      

Extension Points

  1. Custom Assertions:

    • Extend the bundle by creating a subclass:
      class CustomEnsure extends Ensure {
          public static function isValidEmail(string $email): void {
              Ensure::isNotEmpty($email, 'Email cannot be empty');
              Ensure::isTrue(filter_var($email, FILTER_VALIDATE_EMAIL), 'Invalid email format');
          }
      }
      
  2. Global Configuration:

    • Override default behavior by binding a custom Ensure class in Laravel’s service container:
      $this->app->bind(Ensure::class, function () {
          return new CustomEnsure();
      });
      
  3. Localization:

    • Translate messages using Laravel’s translation system:
      Ensure::isNotEmpty($name, __('validation.required', ['attribute' => 'name']));
      
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