Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nerg4l committed Jan 15, 2024
0 parents commit 017585e
Show file tree
Hide file tree
Showing 17 changed files with 963 additions and 0 deletions.
56 changes: 56 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
name: run-tests

on:
push:
branches:
- 'main'
pull_request:
branches:
- 'main'

jobs:
test:
runs-on: ubuntu-latest

strategy:
fail-fast: false
matrix:
php: [ 8.0, 8.1, 8.2 ]
laravel: [ '^9.0', '^10.0' ]
dependency-version: [prefer-lowest, prefer-stable]
exclude:
- php: 8.0
laravel: '^10.0'

name: PHP ${{ matrix.php }} - Laravel ${{ matrix.laravel }} - ${{ matrix.dependency-version }}

steps:
- name: Update apt
run: sudo apt-get update --fix-missing

- name: Checkout code
uses: actions/checkout@v4

- name: Cache dependencies
uses: actions/cache@v3
with:
path: ~/.composer/cache/files
key: laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
coverage: none

- name: Validate composer.json
run: composer validate

- name: Install dependencies
run: |
composer require "illuminate/support:${{ matrix.laravel }}" "illuminate/http:${{ matrix.laravel }}" --no-interaction --no-update
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
- name: Execute tests
run: vendor/bin/phpunit --verbose
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/vendor
.DS_Store
Thumbs.db
/.idea
/.vscode
.phpunit.result.cache
composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Coding Socks

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Lost in Translation

This package helps to find missing translation strings in your Laravel blade files.

## Installation

You can easily install this package using Composer, by running the following command:

```
composer install coding-socks/lost-in-translation
```

## Usage

You can list all missing translation for a specific location using the command below.

```
php artisan lost-in-translation:find {locale}
```

Example:

```
php artisan lost-in-translation:find nl
```

## Implementation

This implementation reads all your blade files, compiles them to PHP ([illuminate/view]), parses them as PHP ([nikic/php-parser]), and then finds the relevant nodes in the AST.

This, in my opinion, is a cleaner and less error-prone than using regular expressions.

[illuminate/view]: https://github.com/illuminate/view
[nikic/php-parser]: https://github.com/nikic/PHP-Parser
48 changes: 48 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "coding-socks/lost-in-translation",
"description": "This package helps to find missing translation strings in your Laravel blade files",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "László Görög",
"homepage": "https://github.com/nerg4l"
}
],
"require": {
"php": "^8.0",
"illuminate/console": "^9.0 || ^10.0",
"illuminate/filesystem": "^9.0 || ^10.0",
"illuminate/support": "^9.0 || ^10.0",
"illuminate/translation": "^9.0 || ^10.0",
"illuminate/view": "^9.0 || ^10.0",
"nikic/php-parser": "^4.18 || ^5.0"
},
"require-dev": {
"orchestra/testbench": "^7.3 || ^8.0",
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"CodingSocks\\LostInTranslation\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"CodingSocks\\LostInTranslation\\Tests\\": "tests/"
}
},
"config": {
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-main": "1.0.x-dev"
},
"laravel": {
"providers": [
"CodingSocks\\LostInTranslation\\LostInTranslationServiceProvider"
]
}
}
}
62 changes: 62 additions & 0 deletions config/lost-in-translation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

return [

/*
|--------------------------------------------------------------------------
| Lost in Translation locale
|--------------------------------------------------------------------------
|
| Here you may specify the locale that should be used by the service.
| The locale will be considered the origin language of
| all translation strings.
|
*/

'locale' => config('app.locale', 'en'),

/*
|--------------------------------------------------------------------------
| Lost in Translation path
|--------------------------------------------------------------------------
|
| Here you may specify the path that should be used by the service.
| The path tells where the blade files are located.
|
*/

'path' => resource_path('views'),

/*
|--------------------------------------------------------------------------
| Lost in Translation detection
|--------------------------------------------------------------------------
|
| Here you may specify the different nodes that should be detected
| by the service. These methods, functions, and static calls
| will be detected in your **complied** blade files.
|
*/

'detect' => [
'function' => [
'__', // __('key')
'trans', // trans('key')
],

'method-function' => [
["app('translator')", 'get'], // app('translator')->get('key')
],

'method-static' => [
["\App::make('translator')", 'get'], // App::make('translator')->get('key')
["\Illuminate\Support\Facades\App::make('translator')", 'get'],
],

'static' => [
['\Lang', 'get'], // Lang::get('key')
['\Illuminate\Support\Facades\Lang', 'get'],
],
],

];
90 changes: 90 additions & 0 deletions src/Console/Commands/FindMissingTranslationStrings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

namespace CodingSocks\LostInTranslation\Console\Commands;

use CodingSocks\LostInTranslation\LostInTranslation;
use CodingSocks\LostInTranslation\NonStringArgumentException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Output\OutputInterface;

class FindMissingTranslationStrings extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'lost-in-translation:find
{locale : The locale to be checked}
{--sorted : Sorts the values before printing}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Find missing translation strings in your Laravel blade files';

/**
* Execute the console command.
*/
public function handle(LostInTranslation $lit)
{
$locale = $this->argument('locale');

$files = File::allFiles(config('lost-in-translation.path'));

$reported = [];
$keys = [];

$this->withProgressBar($files, function ($file) use ($lit, $locale, &$reported, &$keys) {
if (!Str::endsWith($file->getFilename(), '.blade.php')) {
return;
}

$nodes = $lit->findInFile($file);

$translationKeys = $this->resolveFirstArgs($lit, $nodes);

foreach ($translationKeys as $key) {
if (!Lang::has($key, $locale) && !array_key_exists($key, $reported)) {
// TODO: find a better way to check uniqueness
$reported[$key] = true;
$keys[] = $key;
}
}
});

if ($this->option('sorted')) {
sort($keys);
}

foreach ($keys as $key) {
$this->line(OutputFormatter::escape($key));
}
}

/**
* @param \CodingSocks\LostInTranslation\LostInTranslation $lit
* @param array $nodes
* @return array
*/
protected function resolveFirstArgs(LostInTranslation $lit, array $nodes): array
{
$translationKeys = [];
foreach ($nodes as $node) {
try {
if (($key = $lit->resolveFirstArg($node)) !== null) {
$translationKeys[] = $key;
}
} catch (NonStringArgumentException $e) {
$this->warn("skipping dynamic language key: `{$e->argument}`", OutputInterface::VERBOSITY_VERBOSE);
}
}
return array_unique($translationKeys);
}
}
66 changes: 66 additions & 0 deletions src/FirstArgumentResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace CodingSocks\LostInTranslation;

use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Scalar\String_;
use PhpParser\PrettyPrinter\Standard;

class FirstArgumentResolver
{
/** @var \PhpParser\PrettyPrinter */
private $printer;

/**
* @param \PhpParser\PrettyPrinter|null $printer
*/
public function __construct($printer = null)
{
$this->printer = $printer ?? new Standard();
}

/**
* Resolve the first argument of a node.
*
* @param $node
* @return string|null
* @throws \CodingSocks\LostInTranslation\NonStringArgumentException
*/
public function resolve($node): ?string
{
if (empty($node->args)) {
return null;
}
$firstArg = $node->args[0]->value;
if ($firstArg instanceof Concat) {
$firstArg = $this->tryConcat($firstArg);
}
if (!($firstArg instanceof String_)) {
$code = $this->printer->prettyPrint([$firstArg]);
throw new NonStringArgumentException($code);
}
return $firstArg->value;
}

/**
* Concatenates String_ scalars recursively.
*
* @param \PhpParser\Node\Expr\BinaryOp\Concat $concat
* @return \PhpParser\Node\Expr
*/
protected function tryConcat(Concat $concat): Expr
{
if ($concat->left instanceof Concat) {
$concat->left = $this->tryConcat($concat->left);
}
if ($concat->right instanceof Concat) {
$concat->right = $this->tryConcat($concat->right);
}

if (!($concat->left instanceof String_) || !($concat->right instanceof String_)) {
return $concat;
}
return new String_($concat->left->value . $concat->right->value);
}
}
Loading

0 comments on commit 017585e

Please sign in to comment.