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

Italia Bundle Laravel Package

antonioturdo/italia-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require antonioturdo/italia-bundle
    

    Ensure your composer.json meets the PHP/Symfony version requirements (^7.0.8, Symfony 3.4/4.0).

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        AntonioTurdo\Bundle\ItaliaBundle\ItaliaBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Validate an Italian tax code (codice fiscale) in a Symfony form:

    use AntonioTurdo\Bundle\ItaliaBundle\Constraints\CodiceFiscale;
    
    // In your entity or DTO
    use Symfony\Component\Validator\Constraints as Assert;
    
    /**
     * @Assert\NotBlank
     * @CodiceFiscale
     */
    private $codiceFiscale;
    

Implementation Patterns

Validation in Forms

Symfony Form Integration:

use AntonioTurdo\Bundle\ItaliaBundle\Constraints\PartitaIVA;

$builder->add('partitaIva', TextType::class, [
    'constraints' => [
        new PartitaIVA(['method' => 'formal']),
    ],
]);

Programmatic Validation

Inject the services via dependency injection:

use AntonioTurdo\Bundle\ItaliaBundle\Service\CodiceFiscale;

class MyService {
    private $codiceFiscaleValidator;

    public function __construct(CodiceFiscale $validator) {
        $this->codiceFiscaleValidator = $validator;
    }

    public function validateCodiceFiscale(string $codice): bool {
        return $this->codiceFiscaleValidator->validate($codice);
    }
}

Reverse Calculations

Generate a codice fiscale from personal data:

use AntonioTurdo\Bundle\ItaliaBundle\Service\CodiceFiscale;

$service = $container->get('antonio_turdo_italia.codice_fiscale');
$codice = $service->generateFromData('Rossi', 'Mario', '1980', '01', '01', 'M', 'Roma', 'RM');

CAP Validation

Validate Italian postal codes (CAP):

use AntonioTurdo\Bundle\ItaliaBundle\Service\CAP;

$capValidator = $container->get('antonio_turdo_italia.cap');
$isValid = $capValidator->validate('00100'); // Returns true for valid CAP

Partita IVA Checks

Check if a VAT number exists (requires external API):

use AntonioTurdo\Bundle\ItaliaBundle\Service\PartitaIVA;

$partitaIVA = $container->get('antonio_turdo_italia.partita_iva');
$exists = $partitaIVA->exists('12345678901'); // May throw exception if API fails

Gotchas and Tips

Pitfalls

  1. Partita IVA API Dependencies:

    • The exists() method relies on external APIs (sorciulus/check-partita-iva or fdisotto/partita-iva). Network issues or API rate limits may cause failures.
    • Tip: Wrap calls in a try-catch block and handle exceptions gracefully:
      try {
          $exists = $partitaIVA->exists('12345678901');
      } catch (\RuntimeException $e) {
          // Log and fallback (e.g., assume valid or mark as unverified)
      }
      
  2. Codice Fiscale Generation Edge Cases:

    • The generateFromData() method assumes valid input (e.g., correct gender, province codes). Invalid data may produce incorrect or invalid codes.
    • Tip: Validate inputs before generation or use a library like davidepastore/codice-fiscale directly for stricter control.
  3. CAP Validation Strictness:

    • The CAP validator checks format but not physical existence (e.g., '99999' is technically valid but not a real CAP).
    • Tip: For production, consider supplementing with a geocoding API (e.g., OpenStreetMap Nominatim).
  4. Symfony Version Mismatches:

    • The bundle supports Symfony 3.4/4.0 but may not work with newer versions (e.g., Symfony 5+). Test thoroughly if upgrading.
    • Tip: Check the underlying dependencies (davidepastore/codice-fiscale, sorciulus/check-partita-iva) for compatibility.

Debugging

  • Validator Errors: Use Symfony’s validator component to debug constraint failures:

    $validator = $this->container->get('validator');
    $errors = $validator->validate($entity);
    foreach ($errors as $error) {
        dump($error->getPropertyPath(), $error->getMessage());
    }
    
  • Partita IVA API Logs: Enable debug mode for the sorciulus/check-partita-iva or fdisotto/partita-iva packages to inspect API responses:

    # config/packages/antonio_turdo_italia.yaml
    antonio_turdo_italia:
        partita_iva:
            debug: true
    

Extension Points

  1. Custom CAP Rules: Override the CAP validator by extending the service:

    use AntonioTurdo\Bundle\ItaliaBundle\Service\CAP;
    
    class CustomCAPValidator extends CAP {
        public function validate(string $cap): bool {
            if ($cap === '99999') {
                return false; // Block fake CAPs
            }
            return parent::validate($cap);
        }
    }
    

    Register it as a service in config/services.yaml:

    services:
        AntonioTurdo\Bundle\ItaliaBundle\Service\CAP:
            alias: App\Service\CustomCAPValidator
    
  2. Partita IVA Fallback: Implement a fallback for API failures (e.g., cache results or use a local database):

    use AntonioTurdo\Bundle\ItaliaBundle\Service\PartitaIVA;
    
    class ResilientPartitaIVA extends PartitaIVA {
        public function exists(string $partita): bool {
            try {
                return parent::exists($partita);
            } catch (\RuntimeException $e) {
                // Check cache or local DB
                return $this->checkLocalCache($partita);
            }
        }
    }
    
  3. Codice Fiscale Custom Logic: Extend the CodiceFiscale service to add business-specific rules (e.g., block certain prefixes):

    use AntonioTurdo\Bundle\ItaliaBundle\Service\CodiceFiscale;
    
    class BusinessCodiceFiscale extends CodiceFiscale {
        public function validate(string $codice): bool {
            if (str_starts_with($codice, 'ABC')) {
                return false; // Block internal test codes
            }
            return parent::validate($codice);
        }
    }
    

Performance Tips

  • Cache Partita IVA Results: Cache API responses to avoid repeated calls (e.g., using Symfony’s cache component):

    use Symfony\Component\Cache\Adapter\FilesystemAdapter;
    
    $cache = new FilesystemAdapter();
    $key = 'partita_iva_' . $partita;
    if ($cache->has($key)) {
        return $cache->get($key);
    }
    $exists = $partitaIVA->exists($partita);
    $cache->set($key, $exists, 3600); // Cache for 1 hour
    return $exists;
    
  • Batch Validation: For bulk validation (e.g., importing data), process codici fiscali or CAPs in batches to avoid memory issues:

    $batchSize = 100;
    foreach (array_chunk($data, $batchSize) as $batch) {
        foreach ($batch as $item) {
            $validator->validate($item);
        }
    }
    
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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views