75 lines
1.8 KiB
PHP
75 lines
1.8 KiB
PHP
<?php declare(strict_types=1);
|
|
|
|
namespace korElf\TranslateLaravel\Translate;
|
|
|
|
use Illuminate\Contracts\Foundation\Application;
|
|
use korElf\TranslateLaravel\Contracts\Translate;
|
|
use InvalidArgumentException;
|
|
|
|
final class TranslateManager
|
|
{
|
|
/**
|
|
* The array of resolved translation services.
|
|
*/
|
|
private array $translates = [];
|
|
|
|
public function __construct(
|
|
private Application $app,
|
|
) { }
|
|
|
|
public function service(?string $name = null): Translate
|
|
{
|
|
$name = $name ?: $this->getDefaultDriver();
|
|
|
|
return $this->translates[$name] ??= $this->resolve($name);
|
|
}
|
|
|
|
public function getDefaultDriver(): string
|
|
{
|
|
return $this->app['config']['translate.default'];
|
|
}
|
|
|
|
public function setDefaultDriver(string $name): void
|
|
{
|
|
$this->app['config']['translate.default'] = $name;
|
|
}
|
|
|
|
/**
|
|
* Resolve the given translate service.
|
|
*
|
|
* @throws InvalidArgumentException
|
|
*/
|
|
public function resolve(string $name): Translate
|
|
{
|
|
$config = $this->getConfig($name);
|
|
|
|
if (\is_null($config)) {
|
|
throw new InvalidArgumentException("Translate service [{$name}] is not defined.");
|
|
}
|
|
|
|
return $config['driver']::init($this->app, $config['config']);
|
|
}
|
|
|
|
/**
|
|
* Disconnect the given driver and remove from local cache.
|
|
*/
|
|
public function purge(?string $name = null): void
|
|
{
|
|
$name ??= $this->getDefaultDriver();
|
|
|
|
unset($this->translates[$name]);
|
|
}
|
|
|
|
/**
|
|
* Dynamically call the default driver instance.
|
|
*/
|
|
public function __call(string $method, mixed $parameters): mixed
|
|
{
|
|
return $this->service()->$method(...$parameters);
|
|
}
|
|
|
|
private function getConfig(string $name): ?array
|
|
{
|
|
return $this->app['config']["translate.services.{$name}"] ?? null;
|
|
}
|
|
} |