在Symfony2中将多维数组转换为点表示法

3
Symfony将嵌套的YAML和PHP数组翻译文件转换为点表示法,例如:modules.module.title
我正在编写一些代码,将YAML翻译文件导出到数据库中,并且需要将解析后的文件平铺为点表示法。
有人知道Symfony使用哪个函数将嵌套数组转换为点表示法吗?我在源代码中找不到它。
2个回答

4

这是 Symfony\Component\Translation\Loader\ArrayLoader 中的 flatten() 方法:

<?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;
        }
    }
}

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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接