PHP code example of tobento / app-translation-web

1. Go to this page and download the library: Download tobento/app-translation-web library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tobento / app-translation-web example snippets


use Tobento\App\AppFactory;
use Tobento\App\Translation\Web\Collector\CollectorsInterface;
use Tobento\App\Translation\Web\Onboarding\OnboardingInterface;
use Tobento\App\Translation\Web\Strategy\TranslationsPublishInterface;
use Tobento\App\Translation\Web\TranslationRepositoryInterface;

// Create the app
$app = new AppFactory()->createApp();

// Add directories:
$app->dirs()
    ->dir(realpath(__DIR__.'/../'), 'root')
    ->dir(realpath(__DIR__.'/../app/'), 'app')
    ->dir($app->dir('app').'config', 'config', group: 'config')
    ->dir($app->dir('root').'public', 'public')
    ->dir($app->dir('root').'vendor', 'vendor');

// Adding boots
$app->boot(\Tobento\App\Translation\Web\Boot\TranslationWeb::class);
$app->booting();

// Implemented interfaces:
$collectors = $app->get(CollectorsInterface::class);
$onboarding = $app->get(OnboardingInterface::class);
$strategy = $app->get(TranslationsPublishInterface::class);
$translationRepository = $app->get(TranslationRepositoryInterface::class);

// Run the app
$app->run();

'features' => [
    new Feature\Translations(
        // A menu name to show the translations link, or null for no menu entry.
        menu: 'main',
        menuLabel: 'Translations',
        // A menu parent name (e.g. 'system') or null if none.
        menuParent: null,
        
        // Optional queue name used for all translation background jobs.
        // If null (default), the default queue is used.
        queueName: 'translations',
        
        // You may disable ACL while testing.
        // Otherwise, only users with the 

use Tobento\App\Translation\Web\Controller\TranslationCrudController;
use Tobento\App\Translation\Web\Crud\CollectBulkAction;

class TranslationCrudController extends AbstractCrudController
{
    protected function configureActions(): iterable|ActionsInterface
    {
        //...
        
        if ($this->acl->can('translations.collect')) {
            yield new CollectBulkAction(title: trans('Collect'));
        }
        
        //...
    }
}

use Tobento\App\Translation\Web\Controller\TranslationCrudController;
use Tobento\App\Translation\Web\Crud\CreateForLocaleBulkAction;

class TranslationCrudController extends AbstractCrudController
{
    protected function configureActions(): iterable|ActionsInterface
    {
        //...
        
        if ($this->acl->can('translations.create')) {
            yield new CreateForLocaleBulkAction(title: trans('Create for Locale'));
        }
        
        //...
    }
}

use Tobento\App\Translation\Web\Controller\TranslationCrudController;
use Tobento\App\Translation\Web\Crud\AutoTranslateBulkAction;

class TranslationCrudController extends AbstractCrudController
{
    protected function configureActions(): iterable|ActionsInterface
    {
        //...
        
        if ($this->acl->can('translations.auto-translate')) {
            yield new AutoTranslateBulkAction(title: trans('Auto Translate'));
        }
        
        //...
    }
}

use Tobento\App\Crud\Action;
use Tobento\App\Translation\Web\Controller\TranslationCrudController;

class TranslationCrudController extends AbstractCrudController
{
    protected function configureActions(): iterable|ActionsInterface
    {
        //...
        
        if ($this->acl->can('translations.edit')) {
            yield new Action\BulkEdit(name: 'edit-status', title: trans('Edit Status'))
                ->field('status');
        }
        
        //...
    }
}

use Tobento\App\Crud\Action;
use Tobento\App\Translation\Web\Controller\TranslationCrudController;

class TranslationCrudController extends AbstractCrudController
{
    protected function configureActions(): iterable|ActionsInterface
    {
        //...
        
        if ($this->acl->can('translations.delete')) {
            yield new Action\BulkDelete(title: trans('Delete'));
        }
        
        //...
    }
}

if ($this->acl->can('translations.export')) {
    yield new ExportBulkAction(
        name: 'export',
        title: trans('Export'),
    );
}

if ($this->acl->can('translations.import')) {
    yield new ImportBulkAction(
        name: 'import',
        title: trans('Import'),
        withFields: [
            'id',
            'app_id',
            'resource_name',
            'resource_locale',
            'resource_group',
            'resource_priority',
            'resource_filename',
            'message',
            'translation',
            'translated_by',
        ],
        withFileFields: [],
    );
}

'features' => [
    Feature\TranslationsConsoleCommands::class,
    // 

'features' => [
    Feature\MachineTranslation::class,
],

'translators' => [

    'translations' => static function(Azure\MachineTranslatorFactory $factory): MachineTranslatorInterface {
        return $factory->createTranslator('translations', [
            'apiKey' => 'AZURE_TRANSLATOR_KEY',
            'region' => 'westeurope',
            'nonTranslatableStrategy' => new NonTranslatableStrategy\Placeholder(),
        ]);
    },

'collectors' => [
    new Collector\AllTranslations(
        // A unique identifier for this collector:
        id: 'app-root',

        // A human-readable name shown in the UI:
        name: 'All Translations for the root app',

        // The application ID this collector should operate on:
        appId: 'root',

        // Only collect translations for these resource names (whitelist):
        //collectOnly: [],

        // Do not collect translations for these resource names (blacklist):
        //collectExcept: [],

        // Locales to load; if empty, defaults to translator locale and fallbacks:
        //locales: [],
    ),

    /* Example: another collector for a different app
    new Collector\AllTranslations(
        id: 'app-backend',
        name: 'All Translations for the backend app',
        appId: 'backend',
    ),
    */
],

new Collector\AllTranslations(
    id: 'app-backend',
    name: 'All Translations for the backend app',
    appId: 'backend',
    collectOnly: ['*', 'validator'],
),

'interfaces' => [
    Strategy\TranslationsPublishInterface::class => Strategy\FileResources::class,
],

'interfaces' => [
    Strategy\TranslationsPublishInterface::class =>
    static function(): Strategy\FileResources {
        return new Strategy\FileResources(
            // Queue name for dispatching the file-generation job.
            // Use null to use the default queue:
            queueName: null,

            // Folder name under the app directory where JSON files will be written:
            folderName: 'trans-custom',

            // Directory identifier used by the Dirs service:
            dirName: 'trans-custom',

            // Directory priority (higher overrides defaults):
            dirPriority: 10000,
        );
    },
],

  $translations = $this->repository->findAllPublished(
      appId: $this->appId,
      locale: $locale
  );
  

'interfaces' => [
    Strategy\TranslationsPublishInterface::class => Strategy\InMemoryResources::class,
],

'interfaces' => [
    Strategy\TranslationsPublishInterface::class => Strategy\NullStrategy::class,
],

'interfaces' => [
    MissingTranslationHandlerInterface::class => MissingHandler\Log::class,
    
    // If you don't want any handler, just comment out the line above.
    // MissingTranslationHandlerInterface::class => MissingHandler\Log::class,
],

$app->boot(\Tobento\App\MachineTranslator\Boot\MachineTranslator::class);
$app->boot(\Tobento\App\Queue\Boot\Queue::class);
$app->boot(\Tobento\App\Cache\Boot\Cache::class); // needed for unique queue

use Tobento\App\AppInterface;

'interfaces' => [
    // Use the default AutoTranslate handler
    MissingTranslationHandlerInterface::class => MissingHandler\AutoTranslate::class,

    // Use a custom translator (e.g. the "null" translator)
    MissingTranslationHandlerInterface::class => static function(AppInterface $app) {
        return $app->make(MissingHandler\AutoTranslate::class, [
            // The queue name to dispatch translation jobs to (null = default queue)
            'queueName' => null,

            // Which events should trigger auto-translation:
            // 'missing' = missing translation
            // 'fallback' = fallback translation used
            // 'fallbackToDefault' = default locale used as fallback
            'auto' => ['missing'], // (default)

            // The machine-translator name to use (e.g. "null", "deepl", "google")
            'translatorName' => 'null',
        ]);
    },
],

$app->boot(\Tobento\App\Logging\Boot\Logging::class);

'interfaces' => [
    MissingTranslationHandlerInterface::class => MissingHandler\Log::class,
],

'aliases' => [
    // Log missing translations using the "daily" logger:
    \Tobento\App\Translation\Web\MissingHandler\Log::class => 'daily',
    
    // Or disable logging entirely:
    \Tobento\App\Translation\Web\MissingHandler\Log::class => 'null',
],

use Psr\Log\LoggerInterface;
use Tobento\App\AppInterface;
use Tobento\Service\MachineTranslator\MachineTranslatorInterface;

'interfaces' => [
    MissingTranslationHandlerInterface::class => static function(AppInterface $app) {
        return new \Tobento\Service\Translation\MissingHandler\Chain(
            new MissingHandler\Log(
                logger: $app->get(LoggerInterface::class)
            ),
            new MissingHandler\AutoTranslate(
                translator: $app->get(MachineTranslatorInterface::class)
            ),
        );
    },
],

use Tobento\App\Translation\Onboarding\OnboardingInterface;
use Tobento\Service\Translation\TranslationRepositoryInterface;
use Tobento\Service\Translation\Machine\MachineTranslatorsInterface;

'interfaces' => [
    OnboardingInterface::class => static function(
        TranslationRepositoryInterface $translationRepository,
        null|MachineTranslatorsInterface $machineTranslators = null,
    ): OnboardingInterface {

        $machineTranslator = null;

        if ($machineTranslators && $machineTranslators->has('translations')) {
            $machineTranslator = $machineTranslators->get('translations');
        }

        return new Onboarding\Onboarding(
            translationRepository: $translationRepository,
            machineTranslator: $machineTranslator,
            autoTranslateInChunksOf: 20,
        );
    },
];

use Tobento\App\Translation\Onboarding\OnboardingInterface;

$onboarding = $app->get(OnboardingInterface::class);

$created = $onboarding->createTranslationEntries(
    locale: 'fr',
    appId: 'backend',
);

if ($onboarding->supportsAutoTranslate()) {
    // Auto‑translation is available
}

use Tobento\Service\MachineTranslator\MachineTranslatorInterface;

$translator = $onboarding->machineTranslator();

if ($translator !== null) {
    // A machine translator is available
    var_dump($translator instanceof MachineTranslatorInterface);
    // bool(true)
}

$autoTranslated = $onboarding->autoTranslateEntries(
    locale: 'fr',
    appId: 'backend',
);

$published = $onboarding->publishTranslations(
    locale: 'fr',
    appId: 'backend',
);

$autoTranslated = $onboarding->autoTranslateEntriesBy(
    where: ['id' => ['in' => [1, 2, 3]]],
    orderBy: ['key' => 'ASC'],
    limit: [],
);

'defaults' => [
    'pdo' => 'mysql',
    'storage' => 'file',
    'shared:storage' => 'shared:file',
],

'databases' => [
    'shared:file' => [
        'factory' => \Tobento\Service\Database\Storage\StorageDatabaseFactory::class,
        'config' => [
            'storage' => \Tobento\Service\Storage\JsonFileStorage::class,
            'dir' => directory('app:parent').'storage/database/file/',
        ],
    ],
],

php ap translations:resources
app/config/logging.php

php ap translations:collect

php ap translations:generate-json