Skip to content

Instantly share code, notes, and snippets.

@lexisother
Created November 26, 2024 14:20
Show Gist options
  • Select an option

  • Save lexisother/155bdfe4c5e4c786ba571651b2b2100d to your computer and use it in GitHub Desktop.

Select an option

Save lexisother/155bdfe4c5e4c786ba571651b2b2100d to your computer and use it in GitHub Desktop.
Craft CMS table translation
<?php
namespace modules\sitemodule\console\controllers;
use Craft;
use craft\console\Controller;
use craft\elements\Entry;
use Google\Cloud\Translate\V2\TranslateClient;
use yii\console\ExitCode;
class TranslateController
{
public function actionUsps()
{
$siteNL = Craft::$app->getSites()->getSiteByHandle('default');
$siteDE = Craft::$app->getSites()->getSiteByHandle('proPartDE');
$products = Entry::find()
->section('products')
->siteId($siteNL->id)
->status(null)
->all();
$translate = new TranslateClient([
'key' => ''
]);
foreach ($products as $product) {
$deProduct = Entry::find()
->section('products')
->siteId($siteDE->id)
->status(null)
->id($product->id)
->one();
if ($deProduct) {
$changed = false;
if ($product->usps) {
$this->stdout("Processing $product->id...\n");
$deProduct->usps = array_map(function ($usp) use ($translate) {
$uspText = $usp['usp'];
$res = $translate->translate($uspText, [
'source' => 'nl',
'target' => 'de'
]);
$uspText = $res['text'];
return [
'col1' => $uspText,
'usp' => $uspText
];
}, $product->usps);
$this->stdout(" Translated USPs for $product->id\n");
$changed = true;
}
if ($changed) {
if (Craft::$app->elements->saveElement($deProduct)) {
$this->stdout(" Saved!\n");
}
}
}
}
$this->stdout("Done!\n");
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment