Symfony validator translations - symfony

I just started using symfony validator and i really like it except translation part, currently it uses my own translator lib, but i found validator.LOCALE.xlf files where are translations for almost all languages stored, and i can't figure out how to use them.
My current validator registering code is
$container->register('validator', \Symfony\Component\Validator\Validator\ValidatorInterface::class)
->setFactory(
[
new Reference('validator.builder'),
'getValidator'
]
);
$container->register('validator.builder', \Symfony\Component\Validator\ValidatorBuilderInterface::class)
->setFactory(
[
\Symfony\Component\Validator\Validation::class,
'createValidatorBuilder'
]
)
->addMethodCall(
'setTranslator',
[
new Reference('translator') // Symfony translatorInterface
]
)
->addMethodCall(
'setTranslationDomain',
[
'messages'
]
);
It looks like i checked already whole validator structure, like RecursiveValidator, ContextualValidator, Contexts and etc, but just somewhere missing one single param, on another hand ConstraintViolationBuilder just simply takes passed translator and trying to translate constraint message through it, no attempts to use any xlf files.
Just force search through all validator library files gave no result too.
Symfony guilde didn't helped too, because it offers to use default error sentences as a translation key, and use this "keys" in your own translations files, but why copy already translated sentences to your own file, and also create a mess with keys pattern (for example i use snake case) when there is already structured files exists (i am talking about .xlf)?

Solution is to add xlf file loader to your translator, and pass it .xlf translations as a resource.
Something like that
$container->register('translator.xlf_file_loader', \Symfony\Component\Translation\Loader\XliffFileLoader::class);
$container->register('translator.php_file_loader', \Symfony\Component\Translation\Loader\PhpFileLoader::class);
$container->register('translator', \Project\Framework\Translation\Translator::class)
->addArgument(
new Reference('service_container')
)
->addMethodCall(
'addLoader',
[
'php',
new Reference('translator.php_file_loader')
]
)
->addMethodCall(
'addLoader',
[
'xlf',
new Reference('translator.xlf_file_loader')
]
)
->addMethodCall('addResource', ['php', __DIR__ . '/../translation/lt.php', 'lt'])
->addMethodCall('addResource', ['php', __DIR__ . '/../translation/en.php', 'en'])
->addMethodCall('addResource', ['php', __DIR__ . '/../translation/ru.php', 'ru'])
->addMethodCall('addResource', ['xlf', __DIR__ . '/../../vendor/symfony/validator/Resources/translations/validators.lt.xlf', 'lt'])
->addMethodCall(
'setFallbackLocales',
[
['lt']
]
);

Have you simply tried to either
change the locale in the app configuration:
# config/packages/translation.yaml
framework:
default_locale: 'en'
translator:
fallbacks: ['en']
Documentation
change the locale based on (user) input:
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// some logic to determine the $locale
$request->setLocale($locale);
}
Documentation

Related

Zend framework 3 routers in separate file (not in config array tree)

I am using this tutorial https://docs.zendframework.com/tutorials/getting-started/overview/ for creating album module. It works for me.
Inside project there is /module/Album/config/module.config.php file which contains routes. Routers are located inside an array tree. As my previous experience shows I can have in the future dozens of routes per a project (even per a module).
On this documentation page https://docs.zendframework.com/zend-router/routing/ I found another way to add routers to the module.
// One at a time:
$route = Literal::factory([
'route' => '/foo',
'defaults' => [
'controller' => 'foo-index',
'action' => 'index',
],
]);
$router->addRoute('foo', $route);
Such a way is preferred for me than storing routes in a very deep config array tree.
So, my question is: where I can put php routers code outside a config tree as I have mentioned earlier? Where in the module should be such a routers-file located at?
Next to module.config.php in the modules config/ folder it's common to create a routes.config.php.
I split it further by doing something like user.routes.config.php with roles.routes.config.php. Possibly you'd like front.routes.config.php with admin.routes.config.php.
In the end, it's up to you. For colleagues and future sanity, make sure you do it consistently though.
As an example, the config in a project of mine for the User module:
It's a module that handles anything directly User related, so it's all in there. Should probably split it up more, but for now, that would be unnecessary.
You'd then load all of this config like so in your Module.php:
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface, AutoloaderProviderInterface
{
/**
* #return array
*/
public function getConfig()
{
$config = [];
$path = __DIR__
. DIRECTORY_SEPARATOR . '..'
. DIRECTORY_SEPARATOR . 'config'
. DIRECTORY_SEPARATOR . '*.php';
foreach (glob($path) as $filename) {
$config = array_merge_recursive($config, include $filename);
}
return $config;
}
/**
* #return array
*/
public function getAutoloaderConfig()
{
return [
'Zend\Loader\StandardAutoloader' => [
'namespaces' => [
__NAMESPACE__ => __DIR__ . DIRECTORY_SEPARATOR . 'src',
],
],
];
}
}
Remember, eventual implementation in your project(s) is up to you. However, work out a standard and stick to it. You'll go insane if you have different standards everywhere you go.

Symfony 3.0 load config from php file

I try to set up a symfony project with the microcontroller trait. But instead of use a config.yml I want to use a config.php file.
return [
'framework' => [
'secret' => 'secret_'
]
];
What is the best practice to achieve this?
when using microkernel trait, you can use the configureContainer method in your front controller (app.php) to load configuration directly from an array, like this:
protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
{
// PHP equivalent of config.yml
$c->loadFromExtension('framework', array(
'secret' => 'S0ME_SECRET'
));
}
docs here
You should use the container to set the parameters like
$container->setParameter('framework.secret', 'secret_');
as explained in the Symfony Docs

Custom route configuration with Silex

I know that the basis of Silex approach in which all the application logic in a single file. But my application will be possible to have more than twenty controllers. So I want to have a handy map to manage the router.
My question is to search for solutions in which I would be able to make a router to a separate file. In the best case, the file must be of YAML type:
# config/routing.yml
_home:
pattern: /
defaults: { _controller: MyProject\Controller\MyController::index }
But the native is also a good case (for me):
$routes = new RouteCollection();
$routes->add(
'home',
new Route('/', array('controller' => 'MyProject\Controller\MyController::index')
));
return $routes;
Problem of the second case is that I have to use the match() function for each rule of routing. It is not at all clear.
What are the ways to solve this issue? The condition is that I want to use the existing API Silex or components of Symfony2.
Small note:
I don't use a ControllerProviderInterface for my Controller classes. This is an independent classes.
First of all, the basis of Silex is not that you put everything in one file. The basis of Silex is that you create your own 'framework', your own way of organizing applications.
"Use silex if you are comfortable with making all of your own architecture decisions and full stack Symfony2 if not."
-- Dustin Whittle
Read more about this in this blogpost, created by the creator of Silex.
How to solve your problem
What you basically want is to parse a Yaml file and get the pattern and defaults._controller settings from each route that is parsed.
To parse a Yaml file, you can use the Yaml Component of Symfony2. You get an array back which you can use to add the route to Silex:
// parse the yaml file
$routes = ...;
$app = new Silex\Application();
foreach ($routes as $route) {
$app->match($route['pattern'], $route['defaults']['_controller']);
}
// ...
$app->run();
I thought I'd add my method here as, although others may work, there isn't really a simple solution. Adding FileLocator / YamlFileLoader adds a load of bulk that I don't want in my application just to read / parse a yaml file.
Composer
First, you're going to need to include the relevant files. The symfony YAML component, and a really simple and useful config service provider by someone who actively works on Silex.
"require": {
"symfony/yaml": "~2.3",
"igorw/config-service-provider": "1.2.*"
}
File
Let's say that your routes file looks like this (routes.yml):
config.routes:
dashboard:
pattern: /
defaults: { _controller: 'IndexController::indexAction' }
method: GET
Registration
Individually register each yaml file. The first key in the file is the name it will be available under your $app variable (handled by the pimple service locator).
$this->register(new ConfigServiceProvider(__DIR__."/../config/services.yml"));
$this->register(new ConfigServiceProvider(__DIR__."/../config/routes.yml"));
// any more yaml files you like
Routes
You can get these routes using the following:
$routes = $app['config.routes']; // See the first key in the yaml file for this name
foreach ($routes as $name => $route)
{
$app->match($route['pattern'], $route['defaults']['_controller'])->bind($name)->method(isset($route['method'])?$route['method']:'GET');
}
->bind() allows you to 'name' your urls to be used within twig, for example.
->method() allows you to specify POST | GET. You'll note that I defaulted it to 'GET' with a ternary there if the route doesn't specify a method.
Ok, that's how I solved it.
This method is part of my application and called before run():
# /src/Application.php
...
protected function _initRoutes()
{
$locator = new FileLocator(__DIR__.'/config');
$loader = new YamlFileLoader($locator);
$this['routes'] = $loader->load('routes.yml');
}
Application class is my own and it extends Silex\Application.
Configuration file:
# /src/config/routes.yml
home:
pattern: /
defaults: { _controller: '\MyDemoSite\Controllers\DefaultController::indexAction' }
It works fine for me!
UPD:
I think this is the right option to add collections:
$this['routes']->addCollection($loader->load('routes.yml'));
More flexible.
You could extend the routes service (which is a RouteCollection), and load a YAML file with FileLocator and YamlFileLoader:
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
$app->extend('routes', function($routeCollection) {
$locator = new FileLocator([__DIR__ . '/../config']);
$loader = new YamlFileLoader($locator);
$collection = $loader->load('routes.yml');
$routeCollection->addCollection($collection);
return $routeCollection;
});
You will need symfony/config and symfony/yaml dependencies though.

How to load and cache translations?

I'm using gettext translations for SF2 and I arrange my translation files in different folder structure than the normal bundle (I kind of created my own mini plugin system for some specific needs).
In any case, this is how I'm loading my translation files:
$finder = new Finder();
$finder->files()->filter(function (\SplFileInfo $file)
{
return 2 === substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/', $file->getBasename());
})->in($dirs);
foreach ($finder as $file) {
// filename is domain.locale.format
list($domain, $locale, $format) = explode('.', $file->getBasename(), 3);
// we have to add resource right away or it will be too late
$translator->addResource($format, (string)$file, $locale, $domain);
}
It works well, the only problem is that it is not cached which is not very efficient. I wonder what I should do instead to cache these translation?
My problem was that I forgot the declare translator in the config file and thus the translation pass doesn't work
framework:
translator: { fallback: %locale% }

How do I read configuration settings from Symfony2 config.yml?

I have added a setting to my config.yml file as such:
app.config:
contact_email: somebody#gmail.com
...
For the life of me, I can't figure out how to read it into a variable. I tried something like this in one of my controllers:
$recipient =
$this->container->getParameter('contact_email');
But I get an error saying:
The parameter "contact_email" must be
defined.
I've cleared my cache, I also looked everywhere on the Symfony2 reloaded site documentation, but I can't find out how to do this.
Probably just too tired to figure this out now. Can anyone help with this?
Rather than defining contact_email within app.config, define it in a parameters entry:
parameters:
contact_email: somebody#gmail.com
You should find the call you are making within your controller now works.
While the solution of moving the contact_email to parameters.yml is easy, as proposed in other answers, that can easily clutter your parameters file if you deal with many bundles or if you deal with nested blocks of configuration.
First, I'll answer strictly the question.
Later, I'll give an approach for getting those configs from services without ever passing via a common space as parameters.
FIRST APPROACH: Separated config block, getting it as a parameter
With an extension (more on extensions here) you can keep this easily "separated" into different blocks in the config.yml and then inject that as a parameter gettable from the controller.
Inside your Extension class inside the DependencyInjection directory write this:
class MyNiceProjectExtension extends Extension
{
public function load( array $configs, ContainerBuilder $container )
{
// The next 2 lines are pretty common to all Extension templates.
$configuration = new Configuration();
$processedConfig = $this->processConfiguration( $configuration, $configs );
// This is the KEY TO YOUR ANSWER
$container->setParameter( 'my_nice_project.contact_email', $processedConfig[ 'contact_email' ] );
// Other stuff like loading services.yml
}
Then in your config.yml, config_dev.yml and so you can set
my_nice_project:
contact_email: someone#example.com
To be able to process that config.yml inside your MyNiceBundleExtension you'll also need a Configuration class in the same namespace:
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root( 'my_nice_project' );
$rootNode->children()->scalarNode( 'contact_email' )->end();
return $treeBuilder;
}
}
Then you can get the config from your controller, as you desired in your original question, but keeping the parameters.yml clean, and setting it in the config.yml in separated sections:
$recipient = $this->container->getParameter( 'my_nice_project.contact_email' );
SECOND APPROACH: Separated config block, injecting the config into a service
For readers looking for something similar but for getting the config from a service, there is even a nicer way that never clutters the "paramaters" common space and does even not need the container to be passed to the service (passing the whole container is practice to avoid).
This trick above still "injects" into the parameters space your config.
Nevertheless, after loading your definition of the service, you could add a method-call like for example setConfig() that injects that block only to the service.
For example, in the Extension class:
class MyNiceProjectExtension extends Extension
{
public function load( array $configs, ContainerBuilder $container )
{
$configuration = new Configuration();
$processedConfig = $this->processConfiguration( $configuration, $configs );
// Do not add a paramater now, just continue reading the services.
$loader = new YamlFileLoader( $container, new FileLocator( __DIR__ . '/../Resources/config' ) );
$loader->load( 'services.yml' );
// Once the services definition are read, get your service and add a method call to setConfig()
$sillyServiceDefintion = $container->getDefinition( 'my.niceproject.sillymanager' );
$sillyServiceDefintion->addMethodCall( 'setConfig', array( $processedConfig[ 'contact_email' ] ) );
}
}
Then in your services.yml you define your service as usual, without any absolute change:
services:
my.niceproject.sillymanager:
class: My\NiceProjectBundle\Model\SillyManager
arguments: []
And then in your SillyManager class, just add the method:
class SillyManager
{
private $contact_email;
public function setConfig( $newConfigContactEmail )
{
$this->contact_email = $newConfigContactEmail;
}
}
Note that this also works for arrays instead of scalar values! Imagine that you configure a rabbit queue and need host, user and password:
my_nice_project:
amqp:
host: 192.168.33.55
user: guest
password: guest
Of course you need to change your Tree, but then you can do:
$sillyServiceDefintion->addMethodCall( 'setConfig', array( $processedConfig[ 'amqp' ] ) );
and then in the service do:
class SillyManager
{
private $host;
private $user;
private $password;
public function setConfig( $config )
{
$this->host = $config[ 'host' ];
$this->user = $config[ 'user' ];
$this->password = $config[ 'password' ];
}
}
I have to add to the answer of douglas, you can access the global config, but symfony translates some parameters, for example:
# config.yml
...
framework:
session:
domain: 'localhost'
...
are
$this->container->parameters['session.storage.options']['domain'];
You can use var_dump to search an specified key or value.
In order to be able to expose some configuration parameters for your bundle you should consult the documentation for doing so. It's fairly easy to do :)
Here's the link: How to expose a Semantic Configuration for a Bundle
Like it was saying previously - you can access any parameters by using injection container and use its parameter property.
"Symfony - Working with Container Service Definitions" is a good article about it.
I learnt a easy way from code example of http://tutorial.symblog.co.uk/
1) notice the ZendeskBlueFormBundle and file location
# myproject/app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: #ZendeskBlueFormBundle/Resources/config/config.yml }
framework:
2) notice Zendesk_BlueForm.emails.contact_email and file location
# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml
parameters:
# Zendesk contact email address
Zendesk_BlueForm.emails.contact_email: dunnleaddress#gmail.com
3) notice how i get it in $client and file location of controller
# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php
public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
{
$client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
...
}
Inside a controller:
$this->container->getParameter('configname')
to get the config from config/config.yaml:
parameters:
configname: configvalue

Resources