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

List Generator Laravel Package

umpirsky/list-generator

Exports datasets to many formats: text, JSON, YAML, XML, HTML, CSV, SQL (MySQL/PostgreSQL/SQLite), PHP and XLIFF. Used to generate shared lists like countries, currencies, languages, locales and TLDs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require umpirsky/list-generator
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Umpirsky\\": "vendor/umpirsky/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Generate a simple CSV from an array:

    use Umpirsky\ListGenerator\ListGenerator;
    
    $data = [
        ['name' => 'John', 'age' => 30],
        ['name' => 'Jane', 'age' => 25],
    ];
    
    $generator = new ListGenerator();
    echo $generator->generate('csv', $data);
    
  3. Key Classes:

    • ListGenerator: Main class for generating lists.
    • ListGenerator\Format\*: Format-specific classes (e.g., Csv, Json, Xml).
    • ListGenerator\List\*: Predefined lists (e.g., CountryList, CurrencyList).

Implementation Patterns

Common Workflows

1. Generating Custom Lists

Use the ListGenerator to export Eloquent collections or arrays:

// From Eloquent models
$users = User::all();
$generator = new ListGenerator();
$html = $generator->generate('html', $users->toArray());

// With custom headers (CSV example)
$csv = $generator->generate('csv', $users->toArray(), ['headers' => ['ID', 'Name', 'Email']]);

2. Predefined Lists

Leverage built-in lists (e.g., countries, currencies) without manual data entry:

use Umpirsky\ListGenerator\List\CountryList;

$countryList = new CountryList();
$json = $generator->generate('json', $countryList->getList());

3. SQL Dump Generation

Export data as SQL for databases (e.g., MySQL, PostgreSQL):

$sql = $generator->generate('sql:mysql', $data, [
    'table' => 'users',
    'columns' => ['id', 'name', 'email'],
]);

4. Integration with Laravel

  • Service Provider: Bind the generator to the container in AppServiceProvider:
    $this->app->singleton(ListGenerator::class, function ($app) {
        return new ListGenerator();
    });
    
  • Facade (Optional): Create a facade for cleaner syntax:
    // app/Facades/ListGeneratorFacade.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class ListGeneratorFacade extends Facade {
        protected static function getFacadeAccessor() { return 'list-generator'; }
    }
    
    Register in AppServiceProvider:
    $this->app->bind('list-generator', function () {
        return new ListGenerator();
    });
    

5. Dynamic Format Selection

Use a config file or environment variable to switch formats:

$format = config('app.list_format', 'csv');
$result = $generator->generate($format, $data);

Integration Tips

Laravel Blade Directives

Create a Blade directive for inline list generation:

// app/Providers/BladeServiceProvider.php
use Illuminate\Support\Facades\Blade;
Blade::directive('list', function ($expression) {
    $format = explode(',', $expression)[0] ?? 'html';
    return "<?php echo app('list-generator')->generate('{$format}', {$expression}); ?>";
});

Usage in Blade:

@list($users)

Queue Jobs for Large Exports

Offload heavy exports to a queue job:

// app/Jobs/GenerateListJob.php
use Umpirsky\ListGenerator\ListGenerator;
class GenerateListJob implements ShouldQueue {
    protected $data;
    protected $format;
    public function handle() {
        $generator = new ListGenerator();
        Storage::put("exports/{$this->format}.{$this->extension}", $generator->generate($this->format, $this->data));
    }
}

Custom Format Extensions

Extend the package by creating a custom format class:

// app/Extensions/JsonApiFormat.php
namespace App\Extensions;
use Umpirsky\ListGenerator\Format\JsonFormat;
class JsonApiFormat extends JsonFormat {
    protected function getOptions() {
        return array_merge(parent::getOptions(), ['jsonapi' => true]);
    }
    public function generate($data) {
        return $this->encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
}

Register the extension in ListGenerator:

$generator->addFormat('jsonapi', new JsonApiFormat());

Gotchas and Tips

Pitfalls

1. Memory Limits for Large Datasets

  • Issue: Generating large CSV/JSON/XML files may hit PHP memory limits.
  • Fix: Use chunking or stream the output:
    $generator->stream('csv', $data, function ($chunk) {
        echo $chunk;
    });
    

2. SQL Injection Risks

  • Issue: Directly passing user input to SQL generation can be unsafe.
  • Fix: Sanitize data or use parameterized queries:
    $safeData = array_map(function ($item) {
        return array_map('addslashes', $item);
    }, $data);
    $sql = $generator->generate('sql:mysql', $safeData);
    

3. Encoding Issues

  • Issue: Special characters (e.g., é, ü) may corrupt output in CSV/HTML.
  • Fix: Specify encoding explicitly:
    $generator->generate('csv', $data, ['encoding' => 'UTF-8']);
    

4. Deprecated Formats

  • Issue: Some formats (e.g., XLIFF) may not be actively maintained.
  • Fix: Check the GitHub issues for updates.

5. Namespace Conflicts

  • Issue: The package uses Umpirsky\ListGenerator, which might conflict with other umpirsky packages.
  • Fix: Use fully qualified class names or aliases:
    use Umpirsky\ListGenerator\ListGenerator as UmpirskyListGenerator;
    

Debugging Tips

1. Validate Input Data

Ensure data is an array or iterable:

if (!is_array($data) && !$data instanceof \Iterator) {
    throw new \InvalidArgumentException('Data must be an array or iterable.');
}

2. Check Format Availability

Verify the format exists before generating:

if (!$generator->hasFormat('jsonapi')) {
    throw new \RuntimeException('Format not supported.');
}

3. Log Errors

Wrap generation in a try-catch block:

try {
    $result = $generator->generate('csv', $data);
} catch (\Exception $e) {
    Log::error("List generation failed: " . $e->getMessage());
    throw $e;
}

4. Inspect Generated Output

Use var_dump() or dd() to debug:

$options = $generator->getOptions('csv');
dd($options); // Check available options

Configuration Quirks

1. Default Options

Some formats (e.g., CSV) have default options like headers or delimiters:

$csv = $generator->generate('csv', $data, [
    'headers' => ['ID', 'Name'],
    'delimiter' => ';',
]);

2. SQL-Specific Options

SQL formats require additional parameters:

$sql = $generator->generate('sql:postgresql', $data, [
    'table' => 'users',
    'columns' => ['id', 'name'],
    'if_not_exists' => true,
]);

3. HTML Template Customization

Override the default HTML template:

$generator->setTemplate('html', '<table>{rows}</table>');

4. YAML Indentation

Control YAML indentation for readability:

$yaml = $generator->generate('yaml', $data, ['indent' => 2]);

Extension Points

1. Custom Lists

Create reusable list classes:

// app/Lists/CustomList.php
namespace
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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