TranslationsImporter.php 1.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<?php

namespace Modules\Translation\Importers;

use League\Csv\Reader;
use Modules\Translation\Repositories\TranslationRepository;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class TranslationsImporter
{
    /**
     * @var TranslationRepository
     */
    private $translation;

    public function __construct(TranslationRepository $translation)
    {
        $this->translation = $translation;
    }

    public function import(UploadedFile $file)
    {
        $csv = Reader::createFromPath($file->getRealPath());
        $csv->detectDelimiterList(5, [',', ';']);
        $headers = $csv->fetchOne();
        $csv->setOffset(1);

        $csv->each(function ($row) use ($headers) {
            try {
                $row = array_combine($headers, $row);
            } catch (\Exception $e) {
                return true;
            }

            $key = array_get($row, 'key');
            array_shift($row);
            $data = [];
            foreach ($row as $locale => $value) {
                $data[$locale] = ['value' => $value];
            }

            $this->translation->updateFromImport($key, $data);

            return true;
        });
    }
}