Weave 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

Spreadsheet Translator Core Laravel Package

samuelvi/spreadsheet-translator-core

Core library for spreadsheet-translator: parses and converts spreadsheet files into translation resources. Built for Laravel/PHP workflows, enabling import/export of i18n strings from Excel/CSV with a clean, reusable engine for other adapters and apps.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require samuelvi/spreadsheet-translator-core

Ensure your project uses PHP 8.4+ and Laravel 9+. This version drops support for older PHP versions (pre-8.4).

  1. Basic Usage:

    use Samuelvi\SpreadsheetTranslatorCore\Facades\SpreadsheetTranslator;
    
    // Load a CSV/Excel file
    $translator = SpreadsheetTranslator::load('path/to/file.csv');
    
    // Translate a cell (e.g., column A1)
    $translated = $translator->translate('A1');
    
  2. First Use Case:

    • CSV/Excel to Database: Import a spreadsheet, translate headers, and map to Eloquent models.
    • Example:
      $data = $translator->getData(); // Returns translated array
      User::insert($data); // Bulk insert
      

Implementation Patterns

Core Workflows

  1. Translation Pipeline:

    • Chain translators (e.g., ->translate()->format()->validate()).
    • Example:
      $translator
          ->load('file.xlsx')
          ->translate() // Apply custom rules
          ->format('array') // Output as array/object
          ->save('processed.csv'); // Export
      
  2. Dynamic Rules:

    • Register custom rules for specific columns using PHP 8.4’s named arguments (if supported):
      $translator->addRule('email', fn($value) => filter_var($value, FILTER_VALIDATE_EMAIL));
      
  3. Batch Processing:

    • Process large files in chunks:
      $translator->chunk(1000, function ($chunk) {
          // Process chunk (e.g., save to DB)
      });
      

Integration Tips

  • Laravel Filesystem: Use Storage::disk() to handle remote files (S3, etc.):

    $translator->load(Storage::disk('s3')->path('file.xlsx'));
    
  • Queue Jobs: Offload heavy translations to queues:

    TranslateSpreadsheetJob::dispatch('file.xlsx')->onQueue('translations');
    
  • Service Provider: Bind the translator to the container for dependency injection:

    $this->app->singleton(SpreadsheetTranslator::class, function ($app) {
        return new SpreadsheetTranslator(config('spreadsheet-translator'));
    });
    

Gotchas and Tips

Pitfalls

  1. PHP 8.4 Compatibility:

    • Ensure all custom translators/rules use PHP 8.4 syntax (e.g., arrow functions, named args).
    • Fix: Update legacy code to use fn() or named arguments if applicable.
  2. Memory Limits:

    • Large files may hit PHP’s memory_limit. Use chunk() or setMemoryLimit(512).
    • Fix: Stream processing with fgetcsv() for CSV or PhpSpreadsheet's iterators.
  3. Column Mapping:

    • Defaults to A1 notation. For dynamic columns, use:
      $translator->mapColumn('header_name', 'A1');
      

Debugging

  • Log Raw Data:
    $translator->debug(true)->translate(); // Logs input/output
    
  • Validate Rules: Use ->validate() to catch errors early:
    $translator->validate()->onError(function ($errors) {
        Log::error($errors);
    });
    

Extension Points

  1. Custom Translators: Extend BaseTranslator to add logic:

    class MyTranslator extends BaseTranslator {
        public function translateDate(string $value): string {
            return Carbon::parse($value)->format('Y-m-d');
        }
    }
    
  2. Event Listeners: Hook into translated or loaded events:

    SpreadsheetTranslator::addListener('translated', function (array $data) {
        // Post-process data
    });
    
  3. Configuration: Override defaults in config/spreadsheet-translator.php:

    'default_rules' => [
        'email' => 'validate_email',
        'date'  => 'parse_date',
    ],
    

Pro Tips

  • Laravel Nova Integration: Use the translator in Nova actions to import data via UI.
  • Testing: Mock the translator in unit tests:
    $mock = Mockery::mock(SpreadsheetTranslator::class);
    $mock->shouldReceive('translate')->andReturn(['data']);
    
  • PHP 8.4 Features: Leverage readonly properties or enums in custom rules if applicable:
    enum TranslationRule {
        case EMAIL;
        case DATE;
    }
    

NO_UPDATE_NEEDED would not apply here due to the PHP 8.4 upgrade requiring adjustments in the **Gotchas and Tips** section.
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator