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

Government Bundle Laravel Package

avkluchko/government-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require avkluchko/government-bundle
    

    Ensure your Laravel project meets the PHP 7.4+ requirement (x64 recommended for checksum validation).

  2. First Use Case Validate a Russian government identifier (e.g., OGRN, INN, or SNILS) in a controller or form request:

    use AVKluchko\GovernmentBundle\Validator\OGRNValidator;
    
    public function validateOGRN(OGRNValidator $validator, Request $request) {
        $ogrn = $request->input('ogrn');
        if (!$validator->isValid($ogrn)) {
            return back()->withErrors(['ogrn' => 'Invalid OGRN']);
        }
        // Proceed with valid OGRN
    }
    
  3. Where to Look First

    • Validators: Focus on Validator/OGRNValidator.php, INNValidator.php, and SNILSValidator.php for core logic.
    • Tests: Check tests/ for edge cases (e.g., leading zeros, checksum validation).
    • Symfony Bundle Structure: If extending, review GovernmentBundle.php for service registration.

Implementation Patterns

Core Workflows

  1. Form Validation Integrate validators into Laravel’s built-in validation:

    use AVKluchko\GovernmentBundle\Validator\INNValidator;
    
    public function rules() {
        return [
            'inn' => ['required', function ($attribute, $value, $fail) {
                $validator = app(INNValidator::class);
                if (!$validator->isValid($value)) {
                    $fail('The '.$attribute.' must be a valid INN.');
                }
            }]
        ];
    }
    
  2. Service Container Binding Bind validators to Laravel’s container for reusable access:

    $this->app->bind(INNValidator::class, function ($app) {
        return new INNValidator();
    });
    
  3. API Request Validation Use in API middleware or DTOs:

    public function handle(Request $request, Closure $next) {
        $snilsValidator = app(SNILSValidator::class);
        if (!$snilsValidator->isValid($request->snils)) {
            return response()->json(['error' => 'Invalid SNILS'], 400);
        }
        return $next($request);
    }
    
  4. Database Constraints Combine with Laravel’s database validation (e.g., unique rules) for backend checks:

    $validator = Validator::make($data, [
        'ogrn' => ['required', 'string', function ($attribute, $value, $fail) {
            if (!app(OGRNValidator::class)->isValid($value)) {
                $fail('Invalid OGRN format or checksum.');
            }
        }]
    ]);
    
  5. Custom Rules Extend Laravel’s FormRequest for reusable validation:

    use AVKluchko\GovernmentBundle\Validator\INNValidator;
    
    public function rules() {
        return [
            'inn' => ['required', new ValidINN($this->app->make(INNValidator::class))]
        ];
    }
    
    class ValidINN implements Rule {
        protected $validator;
        public function __construct(INNValidator $validator) {
            $this->validator = $validator;
        }
        public function passes($attribute, $value) {
            return $this->validator->isValid($value);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Checksum Limitations

    • x32 PHP Warning: Checksum validation (e.g., for OGRN) fails on 32-bit PHP. Use x64 for full functionality.
    • False Positives: Some valid identifiers may trigger checksum errors due to edge cases (e.g., leading zeros). Test with real-world data.
  2. Input Sanitization

    • Whitespace/Non-Digit Characters: Validators assume clean input. Strip non-digits before validation:
      $cleanInput = preg_replace('/[^0-9]/', '', $input);
      $validator->isValid($cleanInput);
      
  3. Version-Specific Behavior

    • v1.1.1 Changes: Leading zeros and extra digits are normalized (e.g., 1234567890123456789). Ensure tests account for this.
  4. Symfony Dependency

    • Non-Symfony Projects: While Laravel-compatible, the package is Symfony-based. Avoid mixing with non-Symfony components (e.g., AppKernel).

Debugging Tips

  1. Validator Logic

    • Inspect isValid() methods in Validator/ for checksum algorithms. For OGRN, the checksum uses modulo-11 arithmetic.
    • Example OGRN checksum logic:
      $sum = 0;
      for ($i = 0; $i < 12; $i++) {
          $sum += $ogrn[$i] * (13 - $i);
      }
      $checksum = 11 - ($sum % 11);
      
  2. Edge Cases

    • SNILS: Must be 11 digits (e.g., 123-456-789 0X). Test with hyphens/spaces removed.
    • INN: Length varies (10 or 12 digits). Use strlen() checks if strict length is needed.
  3. Performance

    • Validators are lightweight. Cache results if validating the same ID repeatedly (e.g., in loops).

Extension Points

  1. Custom Validators Extend AbstractValidator (if exposed) or create a wrapper:

    class CustomOGRNValidator extends OGRNValidator {
        public function isValid($ogrn, bool $strict = true) {
            // Add custom logic (e.g., blacklist checks)
            return parent::isValid($ogrn) && !$this->isBlacklisted($ogrn);
        }
    }
    
  2. Localization

    • Override error messages in Laravel’s resources/lang/:
      'validation' => [
          'attributes' => [
              'ogrn' => 'ОГРН',
          ],
          'custom' => [
              'ogrn' => [
                  'invalid' => 'Некорректный ОГРН.',
              ],
          ],
      ],
      
  3. Testing

    • Mock validators in unit tests:
      $validator = $this->createMock(INNValidator::class);
      $validator->method('isValid')->willReturn(false);
      $this->app->instance(INNValidator::class, $validator);
      
  4. Configuration

    • No bundle config exists, but you can bind custom validators in AppServiceProvider:
      public function register() {
          $this->app->singleton(INNValidator::class, function () {
              return new INNValidator(['custom_rule' => true]);
          });
      }
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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