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

Cpf Cnpj Bundle Laravel Package

dancos/cpf-cnpj-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require dancos/cpf-cnpj-bundle
    

    For non-Flex projects, manually enable the bundle in config/bundles.php:

    Dancos\Bundle\CpfCnpjBundle\CpfCnpjBundle::class => ['all' => true],
    
  2. First Use Case: Validate a CPF or CNPJ in a controller or form:

    use Dancos\Bundle\CpfCnpjBundle\Validator\Constraints as CpfCnpjAssert;
    
    // In a controller or entity
    $validator = $this->get('validator');
    $constraint = new CpfCnpjAssert\ValidCpf();
    $errors = $validator->validate('123.456.789-09', $constraint);
    
  3. Where to Look First:

    • Validator Constraints: src/Validator/Constraints/ for ValidCpf and ValidCnpj.
    • Validator Service: dancos_cpf_cnpj.validator (auto-registered).
    • Documentation: Check the Symfony Validator docs for constraint usage.

Implementation Patterns

Core Workflows

  1. Form Validation: Use the constraints in Symfony forms:

    use Symfony\Component\Form\AbstractType;
    use Dancos\Bundle\CpfCnpjBundle\Validator\Constraints as CpfCnpjAssert;
    
    class UserType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder
                ->add('cpf', TextType::class, [
                    'constraints' => [new CpfCnpjAssert\ValidCpf()]
                ]);
        }
    }
    
  2. Manual Validation: Validate strings in controllers/services:

    $validator = $this->container->get('dancos_cpf_cnpj.validator');
    $isValid = $validator->validateCpf('123.456.789-09'); // Returns bool
    $isValid = $validator->validateCnpj('12.345.678/0001-95'); // Returns bool
    
  3. Cleaning Input: Remove non-numeric characters before validation:

    $cleanedCpf = preg_replace('/[^0-9]/', '', $rawInput);
    $validator->validateCpf($cleanedCpf);
    
  4. API Request Validation: Use Symfony’s ValidatorInterface in API platforms:

    use ApiPlatform\Core\Validator\ValidatorInterface;
    
    public function __construct(ValidatorInterface $validator) {
        $this->validator = $validator;
    }
    
    public function validateCpf($cpf) {
        $constraint = new CpfCnpjAssert\ValidCpf();
        return $this->validator->validate($cpf, $constraint);
    }
    

Integration Tips

  • Translation: Customize error messages in config/validator/validation.yaml:
    constraints:
        Dancos\Bundle\CpfCnpjBundle\Validator\Constraints\ValidCpf:
            message: 'O CPF "{{ string }}" é inválido.'
    
  • Dependency Injection: Inject the validator service directly where needed (e.g., services, commands).
  • Testing: Mock the validator in unit tests:
    $validator = $this->createMock(ValidatorInterface::class);
    $validator->method('validate')->willReturn([]);
    

Gotchas and Tips

Pitfalls

  1. Input Formatting:

    • The validator expects raw digits (e.g., 12345678909) or standard formats (e.g., 123.456.789-09).
    • Gotcha: Passing 123.456.789-09 directly may fail if the validator expects only digits. Clean input first:
      $cleaned = preg_replace('/[^0-9]/', '', $input);
      
  2. CNPJ Validation Edge Cases:

    • The validator may reject CNPJs with leading zeros (e.g., 00.000.000/0000-00). Ensure input is normalized:
      $cnpj = str_pad($cnpj, 14, '0', STR_PAD_LEFT); // Pad with zeros if needed
      
  3. Symfony Version Compatibility:

    • The bundle assumes Symfony 4.4+ (due to Flex support). For older versions, manually register the validator service in services.yaml:
      services:
          dancos_cpf_cnpj.validator:
              class: Dancos\Bundle\CpfCnpjBundle\Validator\CpfCnpjValidator
              tags: [validator.constraint_validator]
      
  4. Performance:

    • Avoid validating the same CPF/CNPJ multiple times in loops. Cache results if validation is repeated:
      $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
      $key = 'cpf_'.$cleanedCpf;
      if (!$cache->has($key)) {
          $isValid = $validator->validateCpf($cleanedCpf);
          $cache->set($key, $isValid, 3600); // Cache for 1 hour
      }
      

Debugging Tips

  1. Validator Output: Use Symfony’s debug tool to inspect validation errors:

    php bin/console debug:validator
    

    Or dump errors in a controller:

    $errors = $validator->validate($cpf, new CpfCnpjAssert\ValidCpf());
    dump($errors); // Check for constraint violations
    
  2. Custom Logic: Extend the validator for business rules (e.g., check if CPF is active in a database):

    use Dancos\Bundle\CpfCnpjBundle\Validator\CpfCnpjValidator;
    
    class CustomCpfValidator extends CpfCnpjValidator {
        public function validateCpf($cpf, Constraint $constraint) {
            $isValid = parent::validateCpf($cpf, $constraint);
            if (!$isValid) return $isValid;
    
            // Add custom logic (e.g., DB check)
            return $this->isCpfActiveInDatabase($cpf);
        }
    }
    

    Register the custom validator in services.yaml:

    services:
        App\Validator\CustomCpfValidator:
            tags: [validator.constraint_validator]
    
  3. Configuration Quirks:

    • The bundle does not expose configurable options (e.g., strict mode). If needed, override the validator class or use a decorator pattern.

Extension Points

  1. Add Custom Constraints: Extend the bundle’s constraints for domain-specific rules:

    namespace App\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraint;
    
    class ValidCpfWithDatabase extends Constraint {
        public $message = 'CPF não encontrado no banco de dados.';
    }
    

    Implement the validator logic in a separate class tagged as a constraint validator.

  2. Event Listeners: Trigger actions on validation (e.g., log invalid CPFs):

    use Symfony\Component\EventDispatcher\GenericEvent;
    
    class CpfValidationListener {
        public function onCpfValidation(GenericEvent $event) {
            $cpf = $event->getSubject();
            $isValid = $event->getArgument('is_valid');
            if (!$isValid) {
                // Log or notify
            }
        }
    }
    

    Register the listener in services.yaml:

    services:
        App\EventListener\CpfValidationListener:
            tags:
                - { name: kernel.event_listener, event: cpf.validation, method: onCpfValidation }
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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