Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Moamen Eltouny committed May 19, 2021
0 parents commit b9a2aba
Show file tree
Hide file tree
Showing 9 changed files with 687 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2021 Pharaonic. https://pharaonic.io

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.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#### Beta Version

##### Command
```bash
php artisan make:translatable Post --migrations
```

##### Relationship
- translations

##### Scopes
- translated(string $locale = null)
- notTranslated(string $locale = null)
- translatedSorting(string $locale, string $field, string $method = 'asc')
- whereTranslation(string $field, $value, string $locale = null, string $action = 'whereHas', string $op = '=')
- orWhereTranslation(string $field, $value, string $locale = null)
- whereTranslationLike(string $field, $value, string $locale = null)
- orWhereTranslationLike(string $field, $value, string $locale = null)

##### Actions
- translate(string $locale = null)
- translateOrFail(string $locale)
- translateOrNew(string $locale)
- translateOrDefault(string $locale = null)
- hasTranslation(string $locale = null)

##### Attributes
- locales
44 changes: 44 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "pharaonic/laravel-translatable",
"description": "Simplest Translatable for Laravel Eloquent/Model",
"keywords": [
"php",
"laravel",
"multilingual",
"languages",
"translate",
"translation",
"translations",
"eloquent",
"model"
],
"license": "MIT",
"authors": [
{
"name": "Moamen Eltouny",
"email": "raggi@pharaonic.io"
}
],
"require": {
"php": ">=7.2",
"laravel/framework": ">=6.0",
"pharaonic/laravel-helpers": ">=2.3"
},
"config": {
"sort-packages": true
},
"extra": {
"laravel": {
"providers": [
"Pharaonic\\Laravel\\Translatable\\TranslatableServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Pharaonic\\Laravel\\Translatable\\": "src"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
155 changes: 155 additions & 0 deletions src/Commands/Transtable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
<?php

namespace Pharaonic\Laravel\Translatable\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class Transtable extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:translatable {name} {--migrations}?';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Create translatable Models & Migrations';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->info(':: Pharaonic - Translatable ::');

$name = $this->argument('name');
$migrations = $this->option('migrations');

$path = File::exists(app_path('/Models')) ? app_path('/Models/') : app_path('/');
$mainName = explode('/', $name);
$mainName = ucfirst(array_pop($mainName));

$mainTable = Str::snake(Str::pluralStudly($mainName));
$mainKey = Str::snake(Str::studly($mainName)) . '_id';
$transTable = Str::snake(Str::pluralStudly($mainName . 'Translation'));

// MAIN FILE
$this->call('make:model', ['name' => $name, '--migration' => $migrations]);
if (File::exists($path . $name . '.php')) {
$content = str_replace(
[
"\n //\n",
'}',
'{',
"\nclass $mainName"
],
[
'',
PHP_EOL . ' /**' . PHP_EOL .
' * The table associated with the model.' . PHP_EOL .
' *' . PHP_EOL .
' * @var string' . PHP_EOL .
' */' . PHP_EOL .
' protected $table = \'' . $mainTable . '\';' . PHP_EOL . PHP_EOL .
' /**' . PHP_EOL .
' * The attributes that are mass assignable.' . PHP_EOL .
' *' . PHP_EOL .
' * @var array' . PHP_EOL .
' */' . PHP_EOL .
' protected $fillable = [];' . PHP_EOL .
PHP_EOL . ' /**' . PHP_EOL .
' * Translatable attributes names.' . PHP_EOL .
' *' . PHP_EOL .
' * @var array' . PHP_EOL .
' */' . PHP_EOL .
' protected $translatableAttributes = [];' . PHP_EOL .
'}',
'{' . PHP_EOL . ' use Translatable;' . PHP_EOL,
"use Pharaonic\Laravel\Translatable\Translatable;\n\nclass $mainName"
],
File::get($path . $name . '.php')
);

File::put($path . $name . '.php', $content);
}

sleep(2);

// TRANSLATION FILE
$this->call('make:model', ['name' => $name . 'Translation', '--migration' => $migrations]);
if (File::exists($path . $name . 'Translation.php')) {
$content = str_replace(
[
"\n //\n",
'}',
],
[
'',
PHP_EOL . ' /**' . PHP_EOL .
' * The table associated with the model.' . PHP_EOL .
' *' . PHP_EOL .
' * @var string' . PHP_EOL .
' */' . PHP_EOL .
' protected $table = \'' . $transTable . '\';' . PHP_EOL . PHP_EOL .
' /**' . PHP_EOL .
' * The attributes that are mass assignable.' . PHP_EOL .
' *' . PHP_EOL .
' * @var array' . PHP_EOL .
' */' . PHP_EOL .
' protected $fillable = [\'locale\', \'' . $mainKey . '\'];' . PHP_EOL .
PHP_EOL . ' /**' . PHP_EOL .
' * Indicates if the model should be timestamped.' . PHP_EOL .
' *' . PHP_EOL .
' * @var bool' . PHP_EOL .
' */' . PHP_EOL .
' public $timestamps = false;' . PHP_EOL .
'}',
],
File::get($path . $name . 'Translation.php')
);

File::put($path . $name . 'Translation.php', $content);
}

// MIGRATIONS
if ($migrations) {
$file = File::glob(database_path('migrations/') . '*create_' . $transTable . '_table.php');
if (!empty($file)) {
$file = $file[0];
$content = File::get($file);
$hasId = strpos($content, '$table->id()') !== false;

$content = str_replace(
'$table->timestamps();',
PHP_EOL . ' $table->string(\'locale\')->index();' . PHP_EOL .
' $table->unsigned' . ($hasId ? 'Big' : '') . 'Integer(\'' . $mainKey . '\');' . PHP_EOL .
' $table->unique([\'' . $mainKey . '\', \'locale\']);' . PHP_EOL .
' $table->foreign(\'' . $mainKey . '\')->references(\'id\')->on(\'' . $mainTable . '\')->onDelete(\'cascade\');' . PHP_EOL,
$content
);
File::put($file, $content);
}
}

return true;
}
}
129 changes: 129 additions & 0 deletions src/Traits/Actions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php

namespace Pharaonic\Laravel\Translatable\Traits;

use Illuminate\Database\Eloquent\Model;

trait Actions
{
/**
* Translations Relationship
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function translations()
{
return $this->hasMany($this->getTranslatableModel(), $this->getTranslatableField());
}

/**
* Set Translations
*
* @param string $locale
* @param Model $model
* @return void
*/
protected function addTranslatableWithLocale(string $locale, Model $model)
{
$list = $this->relationLoaded('translations') ? $this->getRelation('translations') : [];
$list[$locale] = $model;
$this->setRelation('translations', $list);
}

/**
* Getting Translation
*
* @param string|null $locale
* @return Model
*/
protected function getTranslation(?string $locale = null): ?Model
{
$locale = $locale ?? $this->currentTranslatableLocale;

$this->hasTranslation($locale);

if (isset($this->translations[$locale]))
return $this->translations[$locale];

return null;
}

/**
* Getting Translation
*
* @param string $locale
* @return Model|null
*/
public function translate(string $locale = null): ?Model
{
return $this->getTranslation($locale);
}

/**
* Getting Translation or Abort
*
* @param string $locale
* @return Model
*/
public function translateOrFail(string $locale): Model
{
return $this->getTranslation($locale) ?? abort(404);
}

/**
* Getting Translation or Creating a new one
*
* @param string $locale
* @return Model
*/
public function translateOrNew(string $locale): Model
{
$item = $this->translate($locale) ?? null;

if (!$item) {
$item = $this->getTranslatableModel();
$item = new $item();
$item->locale = $locale;
$item->{$this->getTranslatableField()} = $this->getKey();
$this->addTranslatableWithLocale($locale, $item);
}

return $item;
}

/**
* Getting Translation with current Locale or Default Locale
*
* @param string $locale
* @return Model
*/
public function translateOrDefault(string $locale = null): Model
{
return $this->getTranslation($locale) ?? $this->getTranslation(config('Pharaonic.translatable.default'));
}

/**
* Check has been translated
*
* @param string $locale
* @return boolean
*/
public function hasTranslation(string $locale = null)
{
if (!$this->relationLoaded('translations'))
$this->translations;

return $locale ? isset($this->getRelation('translations')[$locale]) : $this->getRelation('translations')->isNotEmpty();
}

/**
* Getting Locales List
*
* @return array
*/
public function getLocalesAttribute()
{
if (!$this->hasTranslation()) return [];
return array_keys($this->translations->toArray());
}
}

0 comments on commit b9a2aba

Please sign in to comment.