Skip to content

Instantly share code, notes, and snippets.

@aiphee
Created February 16, 2020 09:20
Show Gist options
  • Save aiphee/dfd7e3e788b36e2f880149188c27bdbb to your computer and use it in GitHub Desktop.
Save aiphee/dfd7e3e788b36e2f880149188c27bdbb to your computer and use it in GitHub Desktop.
Cakephp console which converts secondary language to primary for 18n table
<?php
namespace App\Command;
use App\Application;
use App\Model\Entity\I18n;
use App\Model\Table\I18nTable;
use Cake\Console\Arguments;
use Cake\Console\Command;
use Cake\Console\ConsoleIo;
use Cake\Core\Configure;
use Cake\Database\Connection;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\Table;
/**
* Když jsem zapomněl že čeština nemusí být hlavní a na slovensku byla jako hlavn jazyk
*
* Všechny řádky z 18n co byly sk hodit do svých tabulek jako primární a z těch tabulek si vzít originál
* pak jen hodit řádek jako cs
*
* @property I18nTable $I18n
*/
class ConvertDefaultTranslationsCommand extends Command
{
/**
* @var Connection
*/
private $db;
public function initialize()
{
parent::initialize();
$this->loadModel('I18n');
$this->db = ConnectionManager::get('default');
}
public function execute(Arguments $args, ConsoleIo $io)
{
$defaultLocale = Configure::read('App.defaultLocale');
$fromLang = $io->askChoice(
'From what language you want to convert',
array_keys(Application::ADDITIONAL_LOCALES)
);
$selection = $io->askChoice(
"So you want to convert translations from `$fromLang` to `$defaultLocale`, did you back up?",
['y', 'n'],
'n'
);
if ($selection !== 'y') {
$io->warning('Never mind then');
$this->abort();
}
$this->convert($fromLang, $defaultLocale, $io);
$this->removeEmpty();
$io->success('Correctly converted! (?)');
}
/**
* @param string $from
* @param string $to
* @param ConsoleIo $io
* @throws \Exception
*/
private function convert(string $from, string $to, ConsoleIo $io)
{
$toConvert = $this->I18n
->find()
->where([
'locale' => $from,
'content NOT LIKE' => ''
]);
/** @var I18n $entity */
foreach ($toConvert as $entity) {
$this->loadModel($entity->model);
/** @var Table $Table */
$Table = $this->{$entity->model};
$untranslatedEntity = $Table->get($entity->foreign_key);
$originalContent = $untranslatedEntity->{$entity->field};
$untranslatedEntity->{$entity->field} = $entity->content;
$io->info("Updating `$originalContent` from `$entity->model` to `$entity->content`");
$entity->content = $originalContent;
$entity->locale = $to;
$this->db->transactional(function () use ($entity, $Table, $untranslatedEntity) {
$this->I18n->save($entity);
$Table->save($untranslatedEntity);
});
$io->success('Converted!' . $io->nl());
}
}
private function removeEmpty(): int
{
return $this->I18n
->deleteAll([
'content LIKE' => ''
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment