Есть ли способ использовать несколько файлов yml с nelmio_api_doc в symfony 3 с NelmioApiDocBundle?

NelmioApiDocBundle позволяет использовать только один файл конфигурации в формате .yml.

nelmio_api_doc:
  routes:
    path_patterns: # an array of regexps
      - ^/api
  documentation:
    paths:
      /api/login_check:
      ...
      /api/refresh_token:
      ...

Но у меня есть более 200 URL-адресов для разных пакетов. это будет работать правильно, но трудно обрабатывать все в одном файле.

Так что, если у кого-то есть решение разделить «пути» на разные отдельные файлы.


person dom    schedule 23.11.2017    source источник


Ответы (4)


Я не вижу параметры конфигурации «маршруты» и «документация» в ссылка на конфигурацию NelmioApiDocBundle

Вместо этого вам следует использовать аннотации, как описано в документации.

person Chris    schedule 23.11.2017
comment
Эта документация только для приложения Symfony 2.x, но я использовал Symfony 3.3, а документация для последней версии NelmioApiDocBundle находится здесь: github .com/nelmio/NelmioApiDocBundle - person dom; 23.11.2017
comment
Нет, это документация v2 из комплекта ApiDoc. Недавно я перешел на Symfony 3.3, и он работает хорошо. - person Chris; 23.11.2017
comment
Нет, это работает, но есть варианты маршрутов и документации, доступные в doc. и API работает правильно с одним файлом, и нет необходимости изменять что-либо из них. - person dom; 24.11.2017

Задача решена! :-)

У одного из моих друзей есть отличная идея решить эту проблему. на самом деле это не правильное решение, но это единственный способ решить эту проблему.

Создаем "api_index.yaml"

export_path: '/config/packages/api_doc.yaml'

import_paths:
  - "@DomCoreBundle/Resources/config/api_doc/api_base_doc.yaml"
  - "@DomCmsBundle/Resources/config/api_doc/static_page_path_doc.yaml"
  - "@DomEntityBundle/Resources/config/api_doc/category_path_doc.yaml"
  - "@DomCmsBundle/Resources/config/api_doc/carousel_path_doc.yaml"
  - "@DomQuickLinkBundle/Resources/config/api_doc/quick_link_path_doc.yaml"
  - "@DomUserBundle/Resources/config/api_doc/user_path_doc.yaml"
  - "@DomUserBundle/Resources/config/api_doc/dealer_path_doc.yaml"
  ...

Затем мы создаем команду (скрипт) Symfony, которая читает каждый файл «import_paths» и добавляет содержимое в файл «export_path».

$this->io = new SymfonyStyle($input, $output);
$path = $this->kernel->locateResource('@FaCoreBundle/Resources/config/api_index.yaml');
$paths = Yaml::parse(file_get_contents($path));

if (array_key_exists('import_paths', $paths)) {
    $contentLength = $this->loadFilesByPath($input, $output, $paths);
    if ($input->getOption('watch')) {
        $contentLengthNew = [];
        while (true) {
            foreach ($paths['import_paths'] as $path) {
                $ymlPath = $this->kernel->locateResource($path);
                $contentLengthNew[$ymlPath] = md5((file_get_contents($ymlPath)));
            }

            if (!empty(array_diff($contentLength, $contentLengthNew)) || count($contentLength) != count($contentLengthNew)) {
                $diff = array_diff($contentLengthNew, $contentLength);
                if (!empty($diff)) {
                    $this->io->writeln(sprintf('<comment>%s</comment> <info>[file+]</info> %s', date('H:i:s'), current(array_keys($diff))));
                }

                $contentLength = $this->loadFilesByPath($input, $output, $paths);
            }

            sleep($input->getOption('period'));
        }
    }
}
person dom    schedule 04.06.2018

Простой способ - прочитать файлы yaml из области, не предназначенной для автозагрузки, объединить содержимое и записать один файл, который будет загружен.

SF 4.x

/config
    /NELMIOApiDocDefinitions // out of autowire
        /one.yaml
        /two.yaml
    /packages
        /_NELMIOApiDocDefinitions.yaml // file_put_content()

один.yaml

nelmio_api_doc:
    areas:
        path_patterns:
            - /one
    documentation:
        tags:
            - { name: One, description: '...' }
        paths:
            /onepath/:
                ...

Ядро.php

protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
{
    $this->mergeNELMIOApiDocYamlDefinitions();
    ...
}

private function mergeNELMIOApiDocYamlDefinitions()
{
    // dev, prod, ...
    $kernelEnvironnement = $this->getEnvironment();

    // No need to rebuild definitions in production
    if ($kernelEnvironnement == 'prod')
        return;

    // Path to the configuration directory
    $confDir = $this->getProjectDir() . '/config';

    // Path to the documentations files to merge
    $yamlDefinitionsDirectory = $confDir . '/NELMIOApiDocDefinitions';

    // Get the files to merge (without dots directories)
    $yamlDefinitionsFiles = array_diff(scandir($yamlDefinitionsDirectory), ['.', '..']);

    // Read definitions files and merge key with theirs values
    $mergedDefinitions = [];
    foreach ($yamlDefinitionsFiles as $yamlDefinitionFile) {
        $yamlFileContent = Yaml::parseFile($yamlDefinitionsDirectory . '/' . $yamlDefinitionFile);
        $mergedDefinitions = array_merge_recursive($mergedDefinitions, $yamlFileContent);
    }

    // Build the YAML
    $yaml = Yaml::dump($mergedDefinitions);

    // Write the YAML into a single file to be loaded by Symfony
    file_put_contents($confDir . '/packages/_NELMIOApiDocDefinitions.yaml', $yaml);
}
person user11233247    schedule 23.04.2019

Проблема решена с

config/packages/nelmio.yaml

imports:
 - {resource: '../nelmio/default.yaml'}
 - {resource: '../nelmio/v1.yaml'}

config/nelmio/default.yaml

nelmio_api_doc:
    areas:
        default:
            path_patterns: [ ^/default/ ]
            documentation:
                info:
                    title: Default

config/nelmio/v1.yaml

nelmio_api_doc:
    areas:
        default:
            path_patterns: [ ^/v1/ ]
            documentation:
                info:
                    title: V1
person gturquais    schedule 25.06.2019