Skip to content

Instantly share code, notes, and snippets.

@hadl
Last active April 9, 2019 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadl/3cdc979d9d72fbb89c869aabf755be28 to your computer and use it in GitHub Desktop.
Save hadl/3cdc979d9d72fbb89c869aabf755be28 to your computer and use it in GitHub Desktop.
[Pimcore 5 Migration] TranslateUpdateTrait
<?php
/**
* TranslateUpdateTrait
*/
use Doctrine\DBAL\Schema\Schema;
/**
* Class TranslateUpdateTrait
*
* @SuppressWarnings(PHPMD.ShortMethodName)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
trait TranslateUpdateTrait
{
/**
* Does no sql queries
*
* @return bool
*/
public function doesSqlMigrations(): bool
{
return false;
}
/**
* Adds translations for websites
*
* @param array $translations
*/
protected function updateTranslations(array $translations)
{
foreach ($translations as $key => $trans) {
$translation = new \Pimcore\Model\Translation\Website();
$translation->setKey($key);
foreach ($trans as $lang => $text) {
try {
$translation->addTranslation($lang, $text);
$this->writeMessage("Website translation '$text' ($lang) [$key] updated.");
} catch (\Exception $e) {
$this->writeMessage(
"Error creating website translation for key '$key'" . PHP_EOL . $e->getMessage()
);
}
}
$translation->save();
}
}
/**
* Rename translation keys
*
* @param array $keys to rename as ['oldkey' => 'newkey']
*/
protected function renameTranslationKeys(array $keys)
{
foreach ($keys as $oldKey => $newKey) {
try {
$translation = \Pimcore\Model\Translation\Website::getByKey($oldKey);
try {
$translation->setKey($newKey);
$translation->save();
} catch (\Exception $e) {
// save failed - do not delete
$this->writeMessage($e->getMessage());
continue;
}
// can't rename key => delete and save new
$translation->setKey($oldKey);
$translation->delete();
$this->writeMessage('Translation Key "' . $oldKey . '" renamed to "' . $newKey . '"');
} catch (\Exception $e) {
$this->writeMessage($e->getMessage());
}
}
}
/**
* Can not migrate down
*
* @param Schema $schema
*/
public function down(Schema $schema)
{
$this->writeMessage('nothing done');
}
}
<?php
class Version20190213114104 extends AbstractPimcoreMigration
{
use TranslateUpdateTrait;
/**
* Creates translations
*
* @param Schema $schema
*/
public function up(Schema $schema)
{
// adding translations
$this->updateTranslations(
[
'Decor' => [
'de' => 'Dekor',
'en' => 'Decor',
],
'No decor' => [
'de' => 'ohne Dekor',
'en' => 'no decor',
],
]
);
// rename translations
$this->renameTranslationKeys([
'oldkey1' => 'newkey1',
'oldkey2' => 'newkey2',
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment