Symfony将嵌套的YAML和PHP数组转换文件转换为点表示法,如下所示:modules.module.title
。
我正在编写一些将YAML翻译文件导出到数据库的代码,我需要将解析后的文件展平为点符号。
是否有人知道Symfony使用哪种函数将嵌套数组展平为点符号?
我无法在源代码中找到它。
答案 0 :(得分:3)
这是flatten()
中的Symfony\Component\Translation\Loader\ArrayLoader
方法:
<?php
/**
* Flattens an nested array of translations.
*
* The scheme used is:
* 'key' => array('key2' => array('key3' => 'value'))
* Becomes:
* 'key.key2.key3' => 'value'
*
* This function takes an array by reference and will modify it
*
* @param array &$messages The array that will be flattened
* @param array $subnode Current subnode being parsed, used internally for recursive calls
* @param string $path Current path being parsed, used internally for recursive calls
*/
private function flatten(array &$messages, array $subnode = null, $path = null)
{
if (null === $subnode) {
$subnode = &$messages;
}
foreach ($subnode as $key => $value) {
if (is_array($value)) {
$nodePath = $path ? $path.'.'.$key : $key;
$this->flatten($messages, $value, $nodePath);
if (null === $path) {
unset($messages[$key]);
}
} elseif (null !== $path) {
$messages[$path.'.'.$key] = $value;
}
}
}
答案 1 :(得分:0)
我不知道以前的Symfony版本是怎么写的,但是从Symfony 4.2开始,翻译已经返回。
返回messages
目录转换的示例控制器。就我而言,我使用此响应来提供i18next js库。
<?php
declare(strict_types=1);
namespace Conferences\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
final class TranslationsController
{
public function __invoke(TranslatorInterface $translator): JsonResponse
{
if (!$translator instanceof TranslatorBagInterface) {
throw new ServiceUnavailableHttpException();
}
return new JsonResponse($translator->getCatalogue()->all()['messages']);
}
}
路线定义:
translations:
path: /{_locale}/translations
controller: App\Controller\TranslationsController
requirements: {_locale: pl|en}