PHP code example of yavor-ivanov / csv-importer

1. Go to this page and download the library: Download yavor-ivanov/csv-importer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yavor-ivanov / csv-importer example snippets

 composer.phar 
 artisan config:publish yavor-ivanov/csv-importer
 artisan csv:import categories
 artisan csv:import expenses validate

'providers' => array(
    'YavorIvanov\CsvImporter\CsvImporterServiceProvider',
)

    'import' => [
        'file_match' => '*Importer.php',
        'register_path' => '\\csv\\importers\\',
        'class_match_pattern' => '/^(?!CSV)(.*)Importer$/',
        'default_csv_path' => '/csv/files/',
    ],
    'export' => [
        'file_match' = '*Exporter.php',
        'register_path' => '\\csv\\exporters\\',
        'class_match_pattern' => '/^(?!CSV)(.*)Exporter$/',
        'default_csv_path' => '/csv/files/',
    ],


use YavorIvanov\CsvImporter\CSVImporter;
class UserRolesImporter extends CSVImporter
{
    // Defualt name for the CSV to import.
    public $file = 'user_roles.csv';

    // Eloquent model name to create/update (case sensitive)
    protected $model = 'UserRole';

    // Maps an id field in the csv to a database id field. Format ['csv_column_name' => 'db_column_name']
    protected $primary_key = ['id' => 'csv_id'];

    // Maps an id field in the csv to a database id field. Format ['csv_column_name' => 'db_column_name']
    protected $cache_key = ['id' => 'csv_id'];

    protected function update($row, $o)
    {
        $o->csv_id = $row['id'];
        $o->role_name = $row['role_name'];
        $o->save();
    }

    protected function import_row($row)
    {
        return UserRole::create([
            'role_name' => $row['role_name'],
            'csv_id' => $row['id'],
        ]);
    }
}

protected $column_mapping = [
    'csv_column' => 'modelPropertyName',
];

protected function get_processors()
{
    return [
            'integer' => function ($v) { return intval($v); },

            'to_datetime' => function ($v, $fmt='d/m/y H:i')
            {
                $created_at = DateTime::createFromFormat($fmt, $v);
                return $created_at->format('Y-m-d H:i:s');
            },
    ];
}

protected $column_mapping = [
    'csv_column' => 'table_column',
];

protected function get_processors()
{
    return [
        'null_or_datetime' => function ($v, $fmt='Y-m-d')
        {
            $v = $this->process('string_to_null', $v);
            if ($v == Null)
                return $v;
            return $this->process('to_datetime', [$v, $fmt]);
        },
    ];
}

protected function get_processors()
{
    return [
        'null_or_datetime' => my_datetime_function
    ];
}

protected function get_validators()
{
    return [
        'unique' => function ($col, $row)
        {
            $val = $row[$col];
            $current_obj = $this->get_from_cache($row);
            $model_col = array_get($this->column_mapping, "$col.name", $col);
            $occurrences = $this->cache->reduce(function($carry, $o) use ($current_obj, $model_col, $val) {
                if ($o != $current_obj && strtolower($o->$model_col) == strtolower($val))
                    return $carry + 1;
                return $carry;
            }, 0);

            if ($occurrences > 0)
            {
                Log::error("A $this->name with $col = $val already exists in $this->file.");
                die;
            }
        },
    ];
}

protected function pivot_row($row)
{
    $pivoted_row = [];
    $book_id = $row['book'];

    // Loops over the genre columns only, as there is only one book column.
    foreach (array_filter(array_slice($row, 1)) as $genre_id)
    {
        array_push($pivoted_row, [
            'book_id'  => $book_id,
            'genre_id' => $genre_id,
        ]);
    }
    return $pivoted_row;
}


use YavorIvanov\CsvImporter\CSVExporter;
class UserRolesImporter extends CSVExporter
{
    // Defualt name for the CSV to export.
    public $file = 'user_roles.csv';

    // Eloquent model to select from (case sensitive)
    protected $model = 'UserRole';

    protected $column_mapping = [
        'csv_id' => 'id',
        'role_name',
    ];
}

    protected $column_mapping = [
        ['authors()->first()->csv_id' => 'author'],
        // ...
    ];

protected function get_processors()
{
    return [
            'null_to_zero' => function ($v)
            {
                if ($v == Null)
                    return 0;
                return $v;
            },
    ];
}

protected function generate_row($o)
{
    $row = parent::generate_row($o);
    $heading = 'genre';
    $current = 1;
    foreach ($o->genres as $genre)
    {
        $col_name = $heading . $current;
        $current += 1;
        $row[$col_name] = $genre->csv_id;
    }
    return $row;
}