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

Easy Rest Bundle Laravel Package

domtomproject/easy-rest-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require domtomproject/easy-rest-bundle "dev-master"
    composer update
    

    Register the bundle in AppKernel.php:

    new DomTomProject\EasyRestBundle\DomtomEasyRestBundle(),
    

    Add minimal config in config.yml:

    domtom_easy_rest: ~
    
  2. Define Validation Rules Create a YAML file (e.g., app/Resources/validation/User.yml) with validation rules:

    default:
        name:
            - notEmpty
            - stringType
        email:
            - notEmpty
            - email
    
  3. First Use Case Use the bundle in a controller to validate incoming data:

    use DomTomProject\EasyRestBundle\Validator\Validator;
    
    public function createAction(Request $request)
    {
        $validator = new Validator('User'); // 'User' refers to User.yml
        $data = $request->request->all();
        $errors = $validator->validate($data);
    
        if (count($errors) > 0) {
            return new JsonResponse(['errors' => $errors], 400);
        }
    
        // Proceed with data processing
        return new JsonResponse(['success' => true]);
    }
    

Implementation Patterns

Common Workflows

  1. Validation in Controllers Reuse the Validator class for all REST endpoints:

    $validator = new Validator('User');
    $errors = $validator->validate($request->request->all());
    
  2. Dynamic Rule Selection Pass different rule sets dynamically:

    $validator = new Validator('User', 'default'); // 'default' is the key in YAML
    
  3. Integration with Forms Use alongside Symfony Forms for hybrid validation:

    $form = $this->createForm(UserType::class, $user);
    $form->submit($request->request->all());
    
    if (!$form->isValid()) {
        $validator = new Validator('User');
        $errors = $validator->validate($request->request->all());
        // Merge form and validator errors
    }
    
  4. API Resource Handling Validate nested data (e.g., for POST /users/{id}/addresses):

    # app/Resources/validation/Address.yml
    default:
        street:
            - notEmpty
        city:
            - notEmpty
    
    $validator = new Validator('Address');
    $addressData = $request->request->get('address');
    $errors = $validator->validate($addressData);
    
  5. Custom Validation Logic Extend the validator for business rules:

    $validator = new Validator('User');
    $validator->addCustomRule('age', function ($age) {
        return $age >= 18;
    }, 'Age must be 18+');
    

Integration Tips

  • Symfony Events: Trigger validation in kernel.request or kernel.controller events.
  • API Platform: Use with API Platform for automatic validation in collections/items.
  • Doctrine: Combine with Doctrine validation for database-level constraints.
  • Testing: Mock Validator in PHPUnit tests:
    $validator = $this->createMock(Validator::class);
    $validator->method('validate')->willReturn([]);
    

Gotchas and Tips

Pitfalls

  1. YAML Syntax Quirks

    • The $ symbol is required for dynamic keys in keySet:
      # Correct
      keySet:
          - $key: pl
            - in: [intermediate, basic]
      
    • Incorrect (will fail):
      keySet:
          - key: pl
            - in: [intermediate, basic]
      
  2. Rule File Caching

    • Validation rules are not cached by default. For production, implement a cache layer (e.g., Symfony Cache component) to load YAML files once.
  3. Deprecated Dependencies

    • The bundle relies on Respect/Validation (v0.x), which is abandoned. Expect compatibility issues with newer PHP/Symfony versions.
    • Workaround: Fork the bundle and update dependencies or use alternatives like Symfony Validator.
  4. Error Handling

    • Errors return a flat array of messages. For nested data, manually structure responses:
      $errors = [
          'name' => ['The name is required.'],
          'address.street' => ['Street is required.']
      ];
      
  5. Case Sensitivity


Debugging Tips

  1. Validate YAML Syntax Use a YAML linter (e.g., yamllint) to catch syntax errors early.

  2. Log Validation Rules Dump the parsed rules for debugging:

    $validator = new Validator('User');
    $rules = $validator->getRules(); // Hypothetical method; inspect internals if needed
    var_dump($rules);
    
  3. Test Edge Cases Validate with:

    • Empty arrays/objects.
    • null or undefined values.
    • Non-standard data types (e.g., float vs. int).

Extension Points

  1. Custom Validators Extend DomTomProject\EasyRestBundle\Validator\Validator to add reusable logic:

    class CustomValidator extends Validator
    {
        public function validateEmailFormat($email)
        {
            return v::email()->validate($email);
        }
    }
    
  2. Override Rule Files Use Symfony’s parameter system to override the default validation path:

    # config.yml
    domtom_easy_rest:
        validation_path: "%kernel.project_dir%/config/validation"
    
  3. Event Dispatching Trigger events before/after validation (e.g., for logging or metrics):

    $validator->addListener('preValidate', function ($data) {
        // Pre-validation logic
    });
    
  4. Alternative Validation Libraries Replace Respect/Validation with Symfony Validator by:

    • Forking the bundle.
    • Creating a wrapper service to delegate to Symfony’s validator.

Performance Considerations

  • Avoid Re-parsing YAML: Cache the parsed validation rules in a service:
    $cache = new FilesystemCache();
    $rules = $cache->get('validation_rules', function () {
        return $this->parseYamlRules();
    });
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui