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

Sped Common Laravel Package

nfephp-org/sped-common

Biblioteca PHP com classes utilitárias compartilhadas para os projetos SPED da nfephp-org: NFe, CTe, MDFe, e-Financeira, eSfinge e eSocial. Reúne componentes comuns para facilitar integrações e reutilização de código.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Domain-Specific Utility: The nfephp-org/sped-common package is a highly specialized library for Brazilian fiscal electronic documents (NFe, CTe, MDFe, eSocial). It aligns perfectly with Laravel applications requiring SPED compliance, particularly in:
    • Tax Document Processing: Generating, validating, and submitting NFe/CTe/MDFe to SEFAZ.
    • Regulatory Compliance: Automating cryptographic validation (e.g., digital signatures, key generation) to meet Brazilian tax laws.
    • Legacy Modernization: Replacing custom XML/XSD validation logic with standardized, maintained code.
  • Misalignment: Not suitable for non-fiscal applications (e.g., social media, generic SaaS) unless they have SPED-related features. The package’s tight coupling to Brazilian standards (e.g., UF codes, NT 2018.001 key formats) limits flexibility for global tax systems.
  • Modularity:
    • Strengths: Decoupled components (e.g., Validator, Keys, Certificate) allow selective adoption. For example, use only the Keys class for key generation without XML validation.
    • Weaknesses: Customizations for non-standard use cases (e.g., hybrid tax systems) may require forking or wrapper layers, increasing maintenance overhead.

Integration Feasibility

  • PHP/Laravel Compatibility:
    • PHP 8.0+: The package is optimized for modern PHP, with CI/CD ensuring compatibility. Laravel’s dependency injection (DI) can seamlessly integrate its classes via service providers or facades.
    • Composer: Zero-config integration with composer require nfephp-org/sped-common. No conflicts with Laravel’s core or Blade templates.
    • XML Handling: Leverages PHP’s native DOMDocument/SimpleXML, avoiding dependencies on external libraries.
  • Database/ORM:
    • No ORM Dependency: Pure PHP classes can integrate with Laravel’s Eloquent via custom accessors/mutators (e.g., getNFeKeyAttribute()). Example:
      // Model: NFe.php
      public function getKeyAttribute($value) {
          return Keys::build($this->cUF, $this->ano, $this->cnpj, ...);
      }
      
    • Storage: Certificates and private keys must not be stored in plaintext in the database. Use encrypted filesystem storage (e.g., storage/app/encrypted) or AWS KMS.
  • APIs/Webhooks:
    • SEFAZ Integration: The package aids in pre-submission validation of XML payloads. Use Laravel’s Http client to send validated XML to SEFAZ endpoints:
      $response = Http::post('https://homologacao.nfe.fazenda.gov.br/ws/nfe-ws/v3.00/autorizacao', [
          'body' => $validatedXml,
          'headers' => ['Content-Type' => 'application/xml'],
      ]);
      
    • Webhook Handling: Sanitize incoming SPED XML using Strings::clearXml() to prevent injection attacks.

Technical Risk

Risk Area Mitigation Strategy
Certificate Management Store certificates in encrypted storage (e.g., Laravel Filesystem + encryption) or hardware security modules (HSMs). Rotate keys using Laravel’s scheduler and the PrivateKey class.
XSD Schema Updates Monitor NFePHP releases for schema changes. Test updates in a staging environment before production deployment.
Performance Validate large XML files asynchronously using Laravel Queues. Example:
```php
dispatch(new ValidateXmlJob($xmlContent, $xsdPath));
```
Optimize by **caching validation results** for identical payloads.                                                                                                                                       |

| Regulatory Compliance | Implement audit logging for all SPED operations (e.g., signed_at, validator_version, user_id). Use Laravel’s log channels or a dedicated sped_audit table. | | Deprecation | Fork the package if upstream maintenance declines. The active community (106 stars, 4.8 avg score) reduces this risk, but document dependencies in composer.json to track updates. | | Cryptographic Failures | Use try-catch blocks for all PrivateKey::sign() and Validator::isValid() calls. Log failures to Sentry or Laravel Horizon for real-time alerts. |

Key Questions for TPM

  1. Regulatory Scope:

    • Does the product require multi-country SPED support (e.g., Mexico’s CFDI)? If yes, evaluate the effort to fork or extend the package.
    • Are there custom fiscal rules beyond Brazilian standards (e.g., industry-specific tax exemptions)? If so, assess whether the package’s rigid schema validation can accommodate them.
  2. Security:

    • How will private keys and certificates be stored? Options:
      • Encrypted filesystem (Laravel Encryptor).
      • AWS KMS or HashiCorp Vault for cloud deployments.
      • Hardware security modules (HSMs) for high-security environments.
    • Will key rotation be automated? If yes, design a Laravel Scheduler task to renew certificates before expiry.
  3. Performance:

    • What is the expected size of XML payloads? Test Validator::isValid() with 1MB+ files to identify bottlenecks.
    • Will batch processing be required (e.g., validating 1000+ invoices)? If yes, implement Laravel Queues with retries for failed validations.
  4. Team Skills:

    • Does the team have experience with PHP cryptography? If not, allocate training for:
      • PrivateKey::sign() and PublicKey::verify().
      • Certificate parsing and validation.
    • Is there a QA process for SPED compliance? Recommend:
      • Testing with SEFAZ’s homologation environment before production.
      • Manual reviews of validation logs for edge cases.
  5. Extensibility:

    • Will custom XSD schemas be needed (e.g., for internal extensions)? If yes, plan to:
      • Extend the Validator class or create a wrapper.
      • Maintain a fork for proprietary schemas.
    • Are there non-SPED XML validation needs? If yes, evaluate alternatives like the xmlschema PHP library for broader use cases.

Integration Approach

Stack Fit

  • Laravel Ecosystem:

    • Service Providers: Register core classes as singletons for dependency injection. Example:
      // app/Providers/SpedServiceProvider.php
      public function register() {
          $this->app->singleton(Validator::class, function ($app) {
              return new Validator();
          });
          $this->app->singleton(Keys::class);
      }
      
    • Facades: Create fluent interfaces for common operations. Example:
      // app/Facades/Sped.php
      public static function validateNFe($xml, $xsdPath = null) {
          return Validator::isValid($xml, $xsdPath ?? __DIR__.'/xsd/nfe_v4.00.xsd');
      }
      
    • Artisan Commands: Add CLI tools for key generation and certificate management. Example:
      // app/Console/Commands/GenerateNFeKey.php
      public function handle() {
          $key = Keys::build(
              $this->argument('cUF'),
              $this->argument('ano'),
              $this->argument('cnpj'),
              // ... other params
          );
          $this->info("Generated NFe Key: {$key}");
      }
      
  • Database:

    • Store metadata (e.g., keys, certificate expiry dates) in a relational database. Example schema:
      CREATE TABLE nfe_keys (
          id BIGINT AUTO_INCREMENT PRIMARY KEY,
          key_hash VARCHAR(64) UNIQUE,
          cnpj VARCHAR(14) NOT NULL,
          valid_from DATE NOT NULL,
          valid_to DATE NOT NULL,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      );
      
      CREATE TABLE certificates (
          id BIGINT AUTO_INCREMENT PRIMARY KEY,
          certificate_content TEXT NOT NULL,
          expiry_date DATE NOT NULL,
          is_active BOOLEAN DEFAULT TRUE,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
      
    • Use Eloquent models to interact with the database:
      // app/Models/NFeKey.php
      class NFeKey extends Model {
          protected $fillable = ['key_hash', 'cnpj', 'valid_from', 'valid_to'];
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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