Skip to content

Commit

Permalink
Added larex:import command
Browse files Browse the repository at this point in the history
  • Loading branch information
Lukasss93 committed Jul 18, 2020
1 parent f18dce4 commit 1223787
Show file tree
Hide file tree
Showing 18 changed files with 339 additions and 31 deletions.
7 changes: 4 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
## v1.2 - 2020-07-18
### Added
- Added `larex:import` command
- Added PHPUnit tests

## [1.1] - 2020-07-07
## v1.1 - 2020-07-07
### Added
- Added line validation

### Fixed
- Failed to parse some rows

## [1.0] - 2020-07-04
## v1.0 - 2020-07-04
### Added
- First release
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ This step *can be skipped* if package auto-discovery is enabled.

## Usage
1. First, you must create the initial CSV file with `php artisan larex:init`.<br>
Or you can use `php artisan larex:init --base` to init the CSV file with default Laravel entries.<br>
Or you can use `php artisan larex:import` to import entries from resources/lang files.<br>
The csv file has the following columns:
* group (basically the file name)
* key (the array key)
Expand All @@ -42,6 +42,8 @@ This step *can be skipped* if package auto-discovery is enabled.
3. Finally, you can use `php artisan larex` to translate your entries from the csv file to the laravel php files.

### Tips
* You can import existing laravel php files with `php artisan larex:import`.
* You can use `php artisan larex:init --base` to init the CSV file with default Laravel entries.
* The **key** column inside the CSV file supports the **dot notation** for nested arrays.
* You can watch your CSV file with `php artisan larex --watch`
* You can use `php artisan larex:sort` to sort the CSV file by group and key.
Expand Down
2 changes: 1 addition & 1 deletion src/Console/LarexCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class LarexCommand extends Command
{
protected $file = 'resources' . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'localization.csv';
protected $file = 'resources/lang/localization.csv';

/**
* The name and signature of the console command.
Expand Down
128 changes: 128 additions & 0 deletions src/Console/LarexImportCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

namespace Lukasss93\Larex\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Keboola\Csv\Exception;
use Keboola\Csv\InvalidArgumentException;
use Lukasss93\Larex\Utils;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;

class LarexImportCommand extends Command
{
protected $file = 'resources/lang/localization.csv';

/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'larex:import {--f|force : Overwrite csv file if already exists}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Import entries from resources/lang files';

/**
* Execute the console command.
*
* @return void
* @throws Exception
* @throws InvalidArgumentException
*/
public function handle(): void
{
$languages = collect([]);
$rawValues = collect([]);

$this->warn('Importing entries...');

//get all php files
$files = File::glob(resource_path('lang/**/*.php'));

foreach($files as $file) {
$array = include $file;
$group = pathinfo($file, PATHINFO_FILENAME);
$lang = basename(dirname($file));

if(!$languages->contains($lang)) {
$languages->push($lang);
}

//loop through array recursive
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST
);
$path = [];
foreach($iterator as $key => $value) {
$path[$iterator->getDepth()] = $key;
if(!is_array($value)) {
$rawValues->push([
'group' => $group,
'key' => implode('.', array_slice($path, 0, $iterator->getDepth() + 1)),
'lang' => $lang,
'value' => $value
]);
}
}
}

//creating the csv file
$header = collect(['group', 'key'])->merge($languages);
$data = collect([]);

foreach($rawValues as $rawValue) {
$index = $data->search(function($item, $key) use ($rawValue) {
return $item[0] === $rawValue['group'] && $item[1] === $rawValue['key'];
});

if($index === false) {
$output = [
$rawValue['group'],
$rawValue['key']
];

for($i = 2; $i < $header->count(); $i++) {
$real = $rawValue['lang'] === $header->get($i) ? $rawValue['value'] : '';
$output[$i] = $real;
}

$data->push($output);
} else {
for($i = 2; $i < $header->count(); $i++) {
$code = $rawValue['lang'] === $header->get($i) ? $rawValue['value'] : null;

if($code !== null) {
$new = $data->get($index);
$new[$i] = $rawValue['value'];
$data->put($index, $new);
}
}
}
}

//add header
$data->prepend($header->toArray());
$data = $data->values();


$force = $this->option('force');


//check file exists
if(File::exists(base_path($this->file)) && !$force) {
$this->error("The '{$this->file}' already exists.");
return;
}


Utils::collectionToCsv($data, base_path($this->file));
$this->info('Files imported successfully.');
}
}
2 changes: 1 addition & 1 deletion src/Console/LarexInitCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class LarexInitCommand extends Command
{
protected $file = 'resources' . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'localization.csv';
protected $file = 'resources/lang/localization.csv';

/**
* The name and signature of the console command.
Expand Down
9 changes: 8 additions & 1 deletion src/Console/LarexSortCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
namespace Lukasss93\Larex\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Keboola\Csv\Exception;
use Keboola\Csv\InvalidArgumentException;
use Lukasss93\Larex\Utils;

class LarexSortCommand extends Command
{
protected $file = 'resources' . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'localization.csv';
protected $file = 'resources/lang/localization.csv';

/**
* The name and signature of the console command.
Expand All @@ -36,6 +37,12 @@ public function handle(): void
{
$this->warn('Sorting che CSV rows...');

if(!File::exists(base_path($this->file))) {
$this->error("The '$this->file' does not exists.");
$this->line('Please create it with: php artisan larex:init');
return;
}

[$header, $rows] = Utils::csvToCollection(base_path($this->file))->partition(function($item, $key) {
return $key === 0;
});
Expand Down
4 changes: 3 additions & 1 deletion src/LarexServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Support\ServiceProvider;
use Lukasss93\Larex\Console\LarexCommand;
use Lukasss93\Larex\Console\LarexImportCommand;
use Lukasss93\Larex\Console\LarexInitCommand;
use Lukasss93\Larex\Console\LarexSortCommand;

Expand All @@ -19,7 +20,8 @@ public function register(): void
$this->commands([
LarexCommand::class,
LarexInitCommand::class,
LarexSortCommand::class
LarexSortCommand::class,
LarexImportCommand::class
]);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static function collectionToCsv(Collection $array, string $filename): voi

public static function getStub(string $name): string
{
$content = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Stubs' . DIRECTORY_SEPARATOR . $name . '.stub');
$content = file_get_contents(__DIR__ . '/Stubs/' . $name . '.stub');
return self::normalizeEOLs($content);
}

Expand Down
81 changes: 81 additions & 0 deletions tests/LarexImportTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace Lukasss93\Larex\Tests;

use Illuminate\Support\Facades\File;

class LarexImportTest extends TestCase
{
/**
* @param string $firstFile
* @param string $secondFile
* @param string $outputFile
* @dataProvider providerImportCommand
*/
public function test_larex_import_command(string $firstFile, string $secondFile, string $outputFile): void
{
File::makeDirectory(resource_path('lang/en'), 0755, true, true);
File::makeDirectory(resource_path('lang/it'), 0755, true, true);
File::put(resource_path('lang/en/app.php'), $this->getTestStub($firstFile));
File::put(resource_path('lang/it/app.php'), $this->getTestStub($secondFile));

$this->artisan('larex:import')
->expectsOutput('Importing entries...')
->expectsOutput('Files imported successfully.')
->run();

self::assertFileExists(resource_path('lang/localization.csv'));
self::assertEquals($this->getTestStub($outputFile),
File::get(resource_path('lang/localization.csv')));
}

public function test_larex_import_command_with_no_force(): void
{
$this->artisan('larex:init')->run();

File::makeDirectory(resource_path('lang/en'), 0755, true, true);
File::makeDirectory(resource_path('lang/it'), 0755, true, true);
File::put(resource_path('lang/en/app.php'), $this->getTestStub('import-input-en-simple'));
File::put(resource_path('lang/it/app.php'), $this->getTestStub('import-input-it-simple'));

$this->artisan('larex:import')
->expectsOutput('Importing entries...')
->expectsOutput("The '{$this->file}' already exists.")
->run();

self::assertFileExists(resource_path('lang/localization.csv'));
self::assertNotEquals(
$this->getTestStub('import-output-simple'),
File::get(resource_path('lang/localization.csv'))
);
}

public function test_larex_import_command_with_force(): void
{
$this->artisan('larex:init')->run();

File::makeDirectory(resource_path('lang/en'), 0755, true, true);
File::makeDirectory(resource_path('lang/it'), 0755, true, true);
File::put(resource_path('lang/en/app.php'), $this->getTestStub('import-input-en-simple'));
File::put(resource_path('lang/it/app.php'), $this->getTestStub('import-input-it-simple'));

$this->artisan('larex:import -f')
->expectsOutput('Importing entries...')
->expectsOutput('Files imported successfully.')
->run();

self::assertFileExists(resource_path('lang/localization.csv'));
self::assertEquals(
$this->getTestStub('import-output-simple'),
File::get(resource_path('lang/localization.csv'))
);
}

public function providerImportCommand(): array
{
return [
'simple' => ['import-input-en-simple', 'import-input-it-simple', 'import-output-simple'],
'complex' => ['import-input-en-complex', 'import-input-it-complex', 'import-output-complex']
];
}
}
9 changes: 9 additions & 0 deletions tests/LarexSortTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,13 @@ public function test_sort_command(): void

self::assertEquals($this->getTestStub('sort-output'), File::get(base_path($this->file)));
}

public function test_sort_command_if_file_does_not_exists(): void
{
$this->artisan('larex:sort')
->expectsOutput('Sorting che CSV rows...')
->expectsOutput("The '$this->file' does not exists.")
->expectsOutput('Please create it with: php artisan larex:init')
->run();
}
}
Loading

0 comments on commit 1223787

Please sign in to comment.