Skip to content

Commit

Permalink
Initial re-work using decorator pattern
Browse files Browse the repository at this point in the history
Signed-off-by: Kevin Hamilton <[email protected]>
  • Loading branch information
TotalWipeOut committed May 22, 2024
1 parent 7ca402c commit 5c4f32d
Show file tree
Hide file tree
Showing 17 changed files with 200 additions and 224 deletions.
9 changes: 5 additions & 4 deletions src/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ public function getDependencyConfig()
Geography\CountryCodeListInterface::class => Geography\DefaultCountryCodeList::class,
],
'factories' => [
Translator\TranslatorInterface::class => Translator\TranslatorServiceFactory::class,
Translator\LoaderPluginManager::class => Translator\LoaderPluginManagerFactory::class,
Translator\PlaceholderPluginManager::class => Translator\PlaceholderPluginManagerFactory::class,
Geography\DefaultCountryCodeList::class => [Geography\DefaultCountryCodeList::class, 'create'],
Translator\TranslatorInterface::class => Translator\TranslatorServiceFactory::class,
Translator\LoaderPluginManager::class => Translator\LoaderPluginManagerFactory::class,
Translator\FormatterPluginManager::class => Translator\FormatterPluginManagerFactory::class,
Translator\TranslatorFormatterDecorator::class => Translator\TranslatorFormatterDecoratorFactory::class,
Geography\DefaultCountryCodeList::class => [Geography\DefaultCountryCodeList::class, 'create'],
],
];
}
Expand Down
13 changes: 13 additions & 0 deletions src/Translator/Formatter/FormatterInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Laminas\I18n\Translator\Formatter;

interface FormatterInterface
{
/**
* @param iterable<array-key, string> $placeholders
*/
public function format(string $locale, string $message, iterable $placeholders = []): string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

declare(strict_types=1);

namespace Laminas\I18n\Translator\Placeholder;
namespace Laminas\I18n\Translator\Formatter;

use function str_replace;

class HandlebarPlaceholder implements PlaceholderInterface
class HandlebarFormatter implements FormatterInterface
{
public function compile(string $locale, string $message, iterable $placeholders = []): string
public function format(string $locale, string $message, iterable $placeholders = []): string
{
$compiled = $message;
foreach ($placeholders as $key => $value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

declare(strict_types=1);

namespace Laminas\I18n\Translator\Placeholder;
namespace Laminas\I18n\Translator\Formatter;

use MessageFormatter;
use Traversable;

use function iterator_to_array;

class IcuPlaceholder implements PlaceholderInterface
class IcuFormatter implements FormatterInterface
{
public function compile(string $locale, string $message, iterable $placeholders = []): string
public function format(string $locale, string $message, iterable $placeholders = []): string
{
if ($placeholders instanceof Traversable) {
$placeholders = iterator_to_array($placeholders);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

declare(strict_types=1);

namespace Laminas\I18n\Translator\Placeholder;
namespace Laminas\I18n\Translator\Formatter;

use Laminas\I18n\Exception\ParseException;
use Traversable;

use function call_user_func_array;
use function iterator_to_array;

class PrintfPlaceholder implements PlaceholderInterface
class PrintfFormatter implements FormatterInterface
{
public function compile(string $locale, string $message, iterable $placeholders = []): string
public function format(string $locale, string $message, iterable $placeholders = []): string
{
if ($placeholders instanceof Traversable) {
$placeholders = iterator_to_array($placeholders);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace Laminas\I18n\Translator\Placeholder;
namespace Laminas\I18n\Translator\Formatter;

use Laminas\I18n\Exception\InvalidArgumentException;
use Laminas\I18n\Exception\ParseException;
Expand All @@ -17,9 +17,9 @@
use function ucfirst;
use function uksort;

class SegmentPlaceholder implements PlaceholderInterface
class SegmentFormatter implements FormatterInterface
{
public function compile(string $locale, string $message, iterable $placeholders = []): string
public function format(string $locale, string $message, iterable $placeholders = []): string
{
if ($placeholders instanceof Traversable) {
$placeholders = iterator_to_array($placeholders);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,31 @@
* Placeholder\PlaceholderInterface. Additionally, it registers a number
* of default placeholder compilers.
*
* @template InstanceType of Placeholder\PlaceholderInterface
* @template InstanceType of Formatter\FormatterInterface
* @extends AbstractPluginManager<InstanceType>
* @method Placeholder\PlaceholderInterface get(string $name, ?array $options = null)
* @method Formatter\FormatterInterface get(string $name, ?array $options = null)
*/
class PlaceholderPluginManager extends AbstractPluginManager
class FormatterPluginManager extends AbstractPluginManager
{
/** @inheritDoc */
protected $aliases = [
'segment' => Placeholder\SegmentPlaceholder::class,
'colon' => Placeholder\SegmentPlaceholder::class,
'laravel' => Placeholder\SegmentPlaceholder::class,
'handlebar' => Placeholder\HandlebarPlaceholder::class,
'handlebars' => Placeholder\HandlebarPlaceholder::class,
'icu' => Placeholder\IcuPlaceholder::class,
'vsprintf' => Placeholder\PrintfPlaceholder::class,
'sprintf' => Placeholder\PrintfPlaceholder::class,
'printf' => Placeholder\PrintfPlaceholder::class,
'segment' => Formatter\SegmentFormatter::class,
'colon' => Formatter\SegmentFormatter::class,
'laravel' => Formatter\SegmentFormatter::class,
'handlebar' => Formatter\HandlebarFormatter::class,
'handlebars' => Formatter\HandlebarFormatter::class,
'icu' => Formatter\IcuFormatter::class,
'vsprintf' => Formatter\PrintfFormatter::class,
'sprintf' => Formatter\PrintfFormatter::class,
'printf' => Formatter\PrintfFormatter::class,
];

/** @inheritDoc */
protected $factories = [
Placeholder\SegmentPlaceholder::class => InvokableFactory::class,
Placeholder\HandlebarPlaceholder::class => InvokableFactory::class,
Placeholder\IcuPlaceholder::class => InvokableFactory::class,
Placeholder\PrintfPlaceholder::class => InvokableFactory::class,
Formatter\SegmentFormatter::class => InvokableFactory::class,
Formatter\HandlebarFormatter::class => InvokableFactory::class,
Formatter\IcuFormatter::class => InvokableFactory::class,
Formatter\PrintfFormatter::class => InvokableFactory::class,
];

/**
Expand All @@ -57,15 +57,15 @@ class PlaceholderPluginManager extends AbstractPluginManager
*/
public function validate(mixed $instance): void
{
if ($instance instanceof Placeholder\PlaceholderInterface) {
if ($instance instanceof Formatter\FormatterInterface) {
// we're okay
return;
}

throw new InvalidServiceException(sprintf(
'Plugin of type %s is invalid; must implement %s',
is_object($instance) ? $instance::class : gettype($instance),
Placeholder\PlaceholderInterface::class
Formatter\FormatterInterface::class
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,22 @@
use function is_array;

/** @psalm-import-type ServiceManagerConfiguration from ServiceManager */
class PlaceholderPluginManagerFactory implements FactoryInterface
final class FormatterPluginManagerFactory implements FactoryInterface
{
/**
* Create and return a PlaceholderPluginManager.
*
* @param string $requestedName
* @param array<array-key, mixed>|null $options
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @psalm-suppress ArgumentTypeCoercion
* @psalm-suppress DeprecatedClass
*/
public function __invoke(
ContainerInterface $container,
$requestedName,
?array $options = null
): PlaceholderPluginManager {
): FormatterPluginManager {
$options ??= [];
$pluginManager = new PlaceholderPluginManager($container, $options);
$pluginManager = new FormatterPluginManager($container, $options);

Check failure on line 30 in src/Translator/FormatterPluginManagerFactory.php

View workflow job for this annotation

GitHub Actions / ci / QA Checks (Psalm [8.1, locked], ubuntu-latest, laminas/laminas-continuous-integration-action@v1, ...

ArgumentTypeCoercion

src/Translator/FormatterPluginManagerFactory.php:30:65: ArgumentTypeCoercion: Argument 2 of Laminas\I18n\Translator\FormatterPluginManager::__construct expects array{abstract_factories?: array<array-key, Laminas\ServiceManager\Factory\AbstractFactoryInterface|class-string<Laminas\ServiceManager\Factory\AbstractFactoryInterface>>, aliases?: array<string, string>, delegators?: array<string, array<array-key, Laminas\ServiceManager\Factory\DelegatorFactoryInterface|callable(Psr\Container\ContainerInterface, string, callable():object, array<array-key, mixed>|null):object|class-string<Laminas\ServiceManager\Factory\DelegatorFactoryInterface>>>, factories?: array<string, Laminas\ServiceManager\Factory\FactoryInterface|callable(Psr\Container\ContainerInterface, null|string, array<array-key, mixed>|null):object|class-string<Laminas\ServiceManager\Factory\FactoryInterface>>, initializers?: array<array-key, Laminas\ServiceManager\Initializer\InitializerInterface|callable(Psr\Container\ContainerInterface, object):void|class-string<Laminas\ServiceManager\Initializer\InitializerInterface>>, invokables?: array<string, string>, lazy_services?: array{class_map?: array<string, class-string>, proxies_namespace?: non-empty-string, proxies_target_dir?: non-empty-string, write_proxy_files?: bool}, services?: array<string, array<array-key, mixed>|object>, shared?: array<string, bool>, shared_by_default?: bool, ...<array-key, mixed>}, but parent type array<array-key, mixed> provided (see https://psalm.dev/193)

// If this is in a laminas-mvc application, the ServiceListener will inject
// merged configuration during bootstrap.
Expand All @@ -46,12 +43,12 @@ public function __invoke(
$config = $container->get('config');

// If we do not have translator_plugins configuration, nothing more to do
if (! isset($config['translator_placeholders']) || ! is_array($config['translator_placeholders'])) {
if (! isset($config['translator_formatter']) || ! is_array($config['translator_formatter'])) {
return $pluginManager;
}

// Wire service configuration for translator_plugins
(new Config($config['translator_placeholders']))->configureServiceManager($pluginManager);
(new Config($config['translator_formatter']))->configureServiceManager($pluginManager);

Check failure on line 51 in src/Translator/FormatterPluginManagerFactory.php

View workflow job for this annotation

GitHub Actions / ci / QA Checks (Psalm [8.1, locked], ubuntu-latest, laminas/laminas-continuous-integration-action@v1, ...

MixedArgument

src/Translator/FormatterPluginManagerFactory.php:51:21: MixedArgument: Argument 1 of Laminas\ServiceManager\Config::__construct cannot be array<array-key, mixed>|mixed, expecting array{abstract_factories?: array<array-key, Laminas\ServiceManager\Factory\AbstractFactoryInterface|class-string<Laminas\ServiceManager\Factory\AbstractFactoryInterface>>, aliases?: array<string, string>, delegators?: array<string, array<array-key, Laminas\ServiceManager\Factory\DelegatorFactoryInterface|callable(Psr\Container\ContainerInterface, string, callable():object, array<array-key, mixed>|null):object|class-string<Laminas\ServiceManager\Factory\DelegatorFactoryInterface>>>, factories?: array<string, Laminas\ServiceManager\Factory\FactoryInterface|callable(Psr\Container\ContainerInterface, null|string, array<array-key, mixed>|null):object|class-string<Laminas\ServiceManager\Factory\FactoryInterface>>, initializers?: array<array-key, Laminas\ServiceManager\Initializer\InitializerInterface|callable(Psr\Container\ContainerInterface, object):void|class-string<Laminas\ServiceManager\Initializer\InitializerInterface>>, invokables?: array<string, string>, lazy_services?: array{class_map?: array<string, class-string>, proxies_namespace?: string, proxies_target_dir?: string, write_proxy_files?: bool}, services?: array<string, array<array-key, mixed>|object>, shared?: array<string, bool>, ...<array-key, mixed>} (see https://psalm.dev/030)

return $pluginManager;
}
Expand Down
13 changes: 0 additions & 13 deletions src/Translator/Placeholder/PlaceholderInterface.php

This file was deleted.

68 changes: 1 addition & 67 deletions src/Translator/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@
use Laminas\I18n\Exception;
use Laminas\I18n\Translator\Loader\FileLoaderInterface;
use Laminas\I18n\Translator\Loader\RemoteLoaderInterface;
use Laminas\I18n\Translator\Placeholder\PlaceholderInterface;
use Laminas\ServiceManager\ServiceManager;
use Laminas\Stdlib\ArrayUtils;
use Locale;
use Traversable;

use function array_shift;
use function ctype_digit;
use function get_debug_type;
use function is_array;
use function is_file;
Expand All @@ -30,7 +28,7 @@
/**
* Translator.
*/
class Translator implements TranslatorInterface, TranslatorWithParamsInterface
class Translator implements TranslatorInterface
{
/**
* Event fired when the translation for a message is missing.
Expand Down Expand Up @@ -112,8 +110,6 @@ class Translator implements TranslatorInterface, TranslatorWithParamsInterface
*/
protected $eventsEnabled = false;

protected ?PlaceholderInterface $placeholder = null;

/**
* Instantiate a translator
*
Expand Down Expand Up @@ -419,49 +415,6 @@ public function translatePlural(
return $index === 0 ? $singular : $plural;
}

/**
* @param iterable<string|int, string> $params
*/
public function translateWithParams(
string $message,
iterable $params = [],
string $textDomain = 'default',
?string $locale = null
): string {
$locale ??= $this->getLocale();

return $this->compileMessage($this->translate($message, $textDomain, $locale), $params, $locale);
}

/**
* The first number in params is used to determine the plural form.
*
* @param iterable<string|int, string> $params
*/
public function translatePluralWithParams(
string $singular,
string $plural,
iterable $params = [],
string $textDomain = 'default',
?string $locale = null
): string {
$locale ??= $this->getLocale();

$number = 1;
foreach ($params as $param) {
if (ctype_digit($param)) {
$number = (int) $param;
break;
}
}

return $this->compileMessage(
$this->translatePlural($singular, $plural, $number, $textDomain, $locale),
$params,
$locale
);
}

/**
* Get a translated message.
*
Expand Down Expand Up @@ -866,11 +819,6 @@ public function disableEventManager()
return $this;
}

public function setPlaceholder(PlaceholderInterface $placeholder): void
{
$this->placeholder = $placeholder;
}

protected function storeTextDomain(string $textDomain, string $locale, ?TextDomain $loaded): void
{
if (! $loaded instanceof TextDomain) {
Expand All @@ -883,18 +831,4 @@ protected function storeTextDomain(string $textDomain, string $locale, ?TextDoma
$this->messages[$textDomain][$locale] = $loaded;
}
}

/**
* @param iterable<string|int, string> $placeholders
*/
protected function compileMessage(?string $message, iterable $placeholders, string $locale): string
{
return $this->placeholder && $message !== '' && $message !== null ?
$this->placeholder->compile(
$locale,
$message,
$placeholders
) :
($message ?? '');
}
}
Loading

0 comments on commit 5c4f32d

Please sign in to comment.