Shuu12121/php-treesitter-filtered-datasetsV2 · Datasets at Fast360
{
// 获取包含Hugging Face文本的span元素
const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap');
spans.forEach(span => {
if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) {
span.textContent = 'AI快站';
}
});
});
// 替换logo图片的alt属性
document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => {
if (img.alt.match(/Hugging\s*Face/i)) {
img.alt = 'AI快站 logo';
}
});
}
// 替换导航栏中的链接
function replaceNavigationLinks() {
// 已替换标记,防止重复运行
if (window._navLinksReplaced) {
return;
}
// 已经替换过的链接集合,防止重复替换
const replacedLinks = new Set();
// 只在导航栏区域查找和替换链接
const headerArea = document.querySelector('header') || document.querySelector('nav');
if (!headerArea) {
return;
}
// 在导航区域内查找链接
const navLinks = headerArea.querySelectorAll('a');
navLinks.forEach(link => {
// 如果已经替换过,跳过
if (replacedLinks.has(link)) return;
const linkText = link.textContent.trim();
const linkHref = link.getAttribute('href') || '';
// 替换Spaces链接 - 仅替换一次
if (
(linkHref.includes('/spaces') || linkHref === '/spaces' ||
linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) &&
linkText !== 'OCR模型免费转Markdown' &&
linkText !== 'OCR模型免费转Markdown'
) {
link.textContent = 'OCR模型免费转Markdown';
link.href = 'https://fast360.xyz';
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
replacedLinks.add(link);
}
// 删除Posts链接
else if (
(linkHref.includes('/posts') || linkHref === '/posts' ||
linkText === 'Posts' || linkText.match(/^s*Postss*$/i))
) {
if (link.parentNode) {
link.parentNode.removeChild(link);
}
replacedLinks.add(link);
}
// 替换Docs链接 - 仅替换一次
else if (
(linkHref.includes('/docs') || linkHref === '/docs' ||
linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) &&
linkText !== '模型下载攻略'
) {
link.textContent = '模型下载攻略';
link.href = '/';
replacedLinks.add(link);
}
// 删除Enterprise链接
else if (
(linkHref.includes('/enterprise') || linkHref === '/enterprise' ||
linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i))
) {
if (link.parentNode) {
link.parentNode.removeChild(link);
}
replacedLinks.add(link);
}
});
// 查找可能嵌套的Spaces和Posts文本
const textNodes = [];
function findTextNodes(element) {
if (element.nodeType === Node.TEXT_NODE) {
const text = element.textContent.trim();
if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') {
textNodes.push(element);
}
} else {
for (const child of element.childNodes) {
findTextNodes(child);
}
}
}
// 只在导航区域内查找文本节点
findTextNodes(headerArea);
// 替换找到的文本节点
textNodes.forEach(node => {
const text = node.textContent.trim();
if (text === 'Spaces') {
node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown');
} else if (text === 'Posts') {
// 删除Posts文本节点
if (node.parentNode) {
node.parentNode.removeChild(node);
}
} else if (text === 'Enterprise') {
// 删除Enterprise文本节点
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
});
// 标记已替换完成
window._navLinksReplaced = true;
}
// 替换代码区域中的域名
function replaceCodeDomains() {
// 特别处理span.hljs-string和span.njs-string元素
document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => {
if (span.textContent && span.textContent.includes('huggingface.co')) {
span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
});
// 替换hljs-string类的span中的域名(移除多余的转义符号)
document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => {
if (span.textContent && span.textContent.includes('huggingface.co')) {
span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
});
// 替换pre和code标签中包含git clone命令的域名
document.querySelectorAll('pre, code').forEach(element => {
if (element.textContent && element.textContent.includes('git clone')) {
const text = element.innerHTML;
if (text.includes('huggingface.co')) {
element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
// 处理特定的命令行示例
document.querySelectorAll('pre, code').forEach(element => {
const text = element.innerHTML;
if (text.includes('huggingface.co')) {
// 针对git clone命令的专门处理
if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) {
element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
// 特别处理模型下载页面上的代码片段
document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => {
const content = container.innerHTML;
if (content && content.includes('huggingface.co')) {
container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com');
}
});
// 特别处理模型仓库克隆对话框中的代码片段
try {
// 查找包含"Clone this model repository"标题的对话框
const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]');
if (cloneDialog) {
// 查找对话框中所有的代码片段和命令示例
const codeElements = cloneDialog.querySelectorAll('pre, code, span');
codeElements.forEach(element => {
if (element.textContent && element.textContent.includes('huggingface.co')) {
if (element.innerHTML.includes('huggingface.co')) {
element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com');
} else {
element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
}
// 更精确地定位克隆命令中的域名
document.querySelectorAll('[data-target]').forEach(container => {
const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string');
codeBlocks.forEach(block => {
if (block.textContent && block.textContent.includes('huggingface.co')) {
if (block.innerHTML.includes('huggingface.co')) {
block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com');
} else {
block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com');
}
}
});
});
} catch (e) {
// 错误处理但不打印日志
}
}
// 当DOM加载完成后执行替换
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
replaceHeaderBranding();
replaceNavigationLinks();
replaceCodeDomains();
// 只在必要时执行替换 - 3秒后再次检查
setTimeout(() => {
if (!window._navLinksReplaced) {
console.log('[Client] 3秒后重新检查导航链接');
replaceNavigationLinks();
}
}, 3000);
});
} else {
replaceHeaderBranding();
replaceNavigationLinks();
replaceCodeDomains();
// 只在必要时执行替换 - 3秒后再次检查
setTimeout(() => {
if (!window._navLinksReplaced) {
console.log('[Client] 3秒后重新检查导航链接');
replaceNavigationLinks();
}
}, 3000);
}
// 增加一个MutationObserver来处理可能的动态元素加载
const observer = new MutationObserver(mutations => {
// 检查是否导航区域有变化
const hasNavChanges = mutations.some(mutation => {
// 检查是否存在header或nav元素变化
return Array.from(mutation.addedNodes).some(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
// 检查是否是导航元素或其子元素
if (node.tagName === 'HEADER' || node.tagName === 'NAV' ||
node.querySelector('header, nav')) {
return true;
}
// 检查是否在导航元素内部
let parent = node.parentElement;
while (parent) {
if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') {
return true;
}
parent = parent.parentElement;
}
}
return false;
});
});
// 只在导航区域有变化时执行替换
if (hasNavChanges) {
// 重置替换状态,允许再次替换
window._navLinksReplaced = false;
replaceHeaderBranding();
replaceNavigationLinks();
}
});
// 开始观察document.body的变化,包括子节点
if (document.body) {
observer.observe(document.body, { childList: true, subtree: true });
} else {
document.addEventListener('DOMContentLoaded', () => {
observer.observe(document.body, { childList: true, subtree: true });
});
}
})();
', $output);\n self::assertStringContainsString($expectedHtml, $output);\n }"},"docstring":{"kind":"string","value":"@param mixed $htmlConfig the value of the --html-config option"},"func_name":{"kind":"string","value":"testHtml"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Command/DumpCommandTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Command/DumpCommandTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2271,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideCacheConfig')]\n public function testApiDocGeneratorWithCachePool(array $config, array $expectedValues): void\n {\n $container = new ContainerBuilder();\n $container->setParameter('kernel.bundles', []);\n\n $extension = new NelmioApiDocExtension();\n $extension->load([$config], $container);\n\n $reference = $container->getDefinition('nelmio_api_doc.generator.default')->getArgument(2);\n if (null === $expectedValues['defaultCachePool']) {\n self::assertNull($reference);\n } else {\n self::assertInstanceOf(Reference::class, $reference);\n self::assertSame($expectedValues['defaultCachePool'], (string) $reference);\n }\n\n $reference = $container->getDefinition('nelmio_api_doc.generator.area1')->getArgument(2);\n if (null === $expectedValues['area1CachePool']) {\n self::assertNull($reference);\n } else {\n self::assertInstanceOf(Reference::class, $reference);\n self::assertSame($expectedValues['area1CachePool'], (string) $reference);\n }\n\n $cacheItemId = $container->getDefinition('nelmio_api_doc.generator.default')->getArgument(3);\n self::assertSame($expectedValues['defaultCacheItemId'], $cacheItemId);\n\n $cacheItemId = $container->getDefinition('nelmio_api_doc.generator.area1')->getArgument(3);\n self::assertSame($expectedValues['area1CacheItemId'], $cacheItemId);\n }"},"docstring":{"kind":"string","value":"@param array $config\n@param array $expectedValues"},"func_name":{"kind":"string","value":"testApiDocGeneratorWithCachePool"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/DependencyInjection/NelmioApiDocExtensionTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/DependencyInjection/NelmioApiDocExtensionTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2272,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideOpenApiRendererWithHtmlConfig')]\n public function testHtmlOpenApiRendererWithHtmlConfig(array $htmlConfig, array $expectedHtmlConfig): void\n {\n $container = new ContainerBuilder();\n $container->setParameter('kernel.bundles', [\n 'TwigBundle' => TwigBundle::class,\n ]);\n\n $extension = new NelmioApiDocExtension();\n $extension->load([['html_config' => $htmlConfig]], $container);\n\n $argument = $container->getDefinition('nelmio_api_doc.render_docs.html')->getArgument(1);\n self::assertSame($expectedHtmlConfig, $argument);\n }"},"docstring":{"kind":"string","value":"@param array $htmlConfig\n@param array $expectedHtmlConfig"},"func_name":{"kind":"string","value":"testHtmlOpenApiRendererWithHtmlConfig"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/DependencyInjection/NelmioApiDocExtensionTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/DependencyInjection/NelmioApiDocExtensionTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2273,"cells":{"code":{"kind":"string","value":"public function create(array $extraBundles, ?callable $routeConfiguration, array $extraConfigs, array $extraDefinitions): void\n {\n // clear cache directory for a fresh container\n $filesystem = new Filesystem();\n $filesystem->remove('var/cache/test');\n\n $appKernel = new NelmioKernel($extraBundles, $routeConfiguration, $extraConfigs, $extraDefinitions);\n $appKernel->boot();\n\n $this->container = $appKernel->getContainer();\n }"},"docstring":{"kind":"string","value":"@param Bundle[] $extraBundles\n@param array> $extraConfigs Key is the extension name, value is the config\n@param array $extraDefinitions"},"func_name":{"kind":"string","value":"create"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/ConfigurableContainerFactory.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/ConfigurableContainerFactory.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2274,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideTestCases')]\n public function testControllers(?string $controller, ?string $fixtureSuffix = null, array $extraBundles = [], array $extraConfigs = [], array $extraDefinitions = [], ?\\Closure $extraRoutes = null): void\n {\n $fixtureName = null !== $fixtureSuffix ? $controller.'.'.$fixtureSuffix : $controller;\n\n $routingConfiguration = function (RoutingConfigurator &$routes) use ($controller, $extraRoutes) {\n if (null !== $extraRoutes) {\n ($extraRoutes)($routes);\n }\n\n if (null === $controller) {\n return;\n }\n\n $routes->withPath('/')->import(__DIR__.\"/Controller/$controller.php\", 'attribute');\n };\n\n $this->configurableContainerFactory->create($extraBundles, $routingConfiguration, $extraConfigs, $extraDefinitions);\n\n $apiDefinition = $this->getOpenApiDefinition();\n\n // Create the fixture if it does not exist\n if (!file_exists($fixtureDir = __DIR__.'/Fixtures/'.$fixtureName.'.json')) {\n file_put_contents($fixtureDir, $apiDefinition->toJson());\n }\n\n self::assertSame(\n self::getFixture($fixtureDir),\n $this->getOpenApiDefinition()->toJson(),\n );\n }"},"docstring":{"kind":"string","value":"@param Bundle[] $extraBundles\n@param array> $extraConfigs Key is the extension name, value is the config\n@param array $extraDefinitions"},"func_name":{"kind":"string","value":"testControllers"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/ControllerTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/ControllerTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2275,"cells":{"code":{"kind":"string","value":"#[DataProvider('swaggerActionPathsProvider')]\n public function testSwaggerAction(string $path): void\n {\n $operation = $this->getOperation($path, 'get');\n\n $this->assertHasResponse('201', $operation);\n $response = $this->getOperationResponse($operation, '201');\n self::assertEquals('An example resource', $response->description);\n }"},"docstring":{"kind":"string","value":"Tests that the paths are automatically resolved in Swagger annotations."},"func_name":{"kind":"string","value":"testSwaggerAction"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/FunctionalTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/FunctionalTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2276,"cells":{"code":{"kind":"string","value":"public function testPrivateProtectedExposure(): void\n {\n // Ensure that groups are supported\n $model = $this->getModel('PrivateProtectedExposure');\n self::assertCount(1, $model->properties);\n $this->assertHasProperty('publicField', $model);\n $this->assertNotHasProperty('privateField', $model);\n $this->assertNotHasProperty('protectedField', $model);\n $this->assertNotHasProperty('protected', $model);\n }"},"docstring":{"kind":"string","value":"Related to https://github.com/nelmio/NelmioApiDocBundle/issues/1756\nEnsures private/protected properties are not exposed, just like the symfony serializer does."},"func_name":{"kind":"string","value":"testPrivateProtectedExposure"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/FunctionalTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/FunctionalTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2277,"cells":{"code":{"kind":"string","value":"public function __construct(\n private array $extraBundles,\n private ?\\Closure $routeConfiguration,\n private array $extraConfigs,\n private array $extraDefinitions,\n ) {\n parent::__construct('test', true);\n }"},"docstring":{"kind":"string","value":"@param Bundle[] $extraBundles\n@param array> $extraConfigs Key is the extension name, value is the config\n@param array $extraDefinitions"},"func_name":{"kind":"string","value":"__construct"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/NelmioKernel.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/NelmioKernel.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2278,"cells":{"code":{"kind":"string","value":"protected function getParameter(OA\\AbstractAnnotation $annotation, string $name, string $in): OA\\Parameter\n {\n $this->assertHasParameter($name, $in, $annotation);\n $parameters = array_filter($annotation->parameters ?? [], function (OA\\Parameter $parameter) use ($name, $in) {\n return $parameter->name === $name && $parameter->in === $in;\n });\n\n return array_values($parameters)[0];\n }"},"docstring":{"kind":"string","value":"@param OA\\Operation|OA\\OpenApi $annotation"},"func_name":{"kind":"string","value":"getParameter"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/WebTestCase.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2279,"cells":{"code":{"kind":"string","value":"public function assertHasParameter(string $name, string $in, OA\\AbstractAnnotation $annotation): void\n {\n $parameters = array_filter(Generator::UNDEFINED !== $annotation->parameters ? $annotation->parameters : [], function (OA\\Parameter $parameter) use ($name, $in) {\n return $parameter->name === $name && $parameter->in === $in;\n });\n\n static::assertNotEmpty(\n $parameters,\n \\sprintf('Failed asserting that parameter \"%s\" in \"%s\" does exist.', $name, $in)\n );\n }"},"docstring":{"kind":"string","value":"@param OA\\Operation|OA\\OpenApi $annotation"},"func_name":{"kind":"string","value":"assertHasParameter"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/WebTestCase.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2280,"cells":{"code":{"kind":"string","value":"public function assertNotHasParameter(string $name, string $in, OA\\AbstractAnnotation $annotation): void\n {\n $parameters = array_column(Generator::UNDEFINED !== $annotation->parameters ? $annotation->parameters : [], 'name', 'in');\n static::assertNotContains(\n $name,\n $parameters[$in] ?? [],\n \\sprintf('Failed asserting that parameter \"%s\" in \"%s\" does not exist.', $name, $in)\n );\n }"},"docstring":{"kind":"string","value":"@param OA\\Operation|OA\\OpenApi $annotation"},"func_name":{"kind":"string","value":"assertNotHasParameter"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/WebTestCase.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2281,"cells":{"code":{"kind":"string","value":"public function assertHasProperty(string $property, OA\\AbstractAnnotation $annotation): void\n {\n $properties = array_column(Generator::UNDEFINED !== $annotation->properties ? $annotation->properties : [], 'property');\n static::assertContains(\n $property,\n $properties,\n \\sprintf('Failed asserting that property \"%s\" does exist.', $property)\n );\n }"},"docstring":{"kind":"string","value":"@param OA\\Schema|OA\\Property|OA\\Items $annotation"},"func_name":{"kind":"string","value":"assertHasProperty"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/WebTestCase.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2282,"cells":{"code":{"kind":"string","value":"public function assertNotHasProperty(string $property, OA\\AbstractAnnotation $annotation): void\n {\n $properties = array_column(Generator::UNDEFINED !== $annotation->properties ? $annotation->properties : [], 'property');\n static::assertNotContains(\n $property,\n $properties,\n \\sprintf('Failed asserting that property \"%s\" does not exist.', $property)\n );\n }"},"docstring":{"kind":"string","value":"@param OA\\Schema|OA\\Property|OA\\Items $annotation"},"func_name":{"kind":"string","value":"assertNotHasProperty"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/WebTestCase.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2283,"cells":{"code":{"kind":"string","value":"#[Route('/deprecated', methods: ['GET'])]\n public function deprecatedAction()\n {\n }"},"docstring":{"kind":"string","value":"This action is deprecated.\n\nPlease do not use this action.\n\n@deprecated"},"func_name":{"kind":"string","value":"deprecatedAction"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/Controller/ApiController.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/ApiController.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2284,"cells":{"code":{"kind":"string","value":"#[Route('/admin', methods: ['GET'])]\n public function adminAction()\n {\n }"},"docstring":{"kind":"string","value":"This action is not documented. It is excluded by the config."},"func_name":{"kind":"string","value":"adminAction"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/Controller/ApiController.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/ApiController.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2285,"cells":{"code":{"kind":"string","value":"#[Route('/undocumented', methods: ['GET'])]\n public function undocumentedAction()\n {\n }"},"docstring":{"kind":"string","value":"This path is excluded by the config (only /api allowed)."},"func_name":{"kind":"string","value":"undocumentedAction"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Functional/Controller/UndocumentedController.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/UndocumentedController.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2286,"cells":{"code":{"kind":"string","value":"#[DataProvider('getNameAlternatives')]\n public function testNameAliasingForObjects(string $expected, ?array $groups, array $alternativeNames): void\n {\n $registry = new ModelRegistry([], $this->createOpenApi(), $alternativeNames);\n $type = new Type(Type::BUILTIN_TYPE_OBJECT, false, self::class);\n\n self::assertEquals($expected, $registry->register(new Model($type, $groups)));\n }"},"docstring":{"kind":"string","value":"@param string[]|null $groups\n@param array $alternativeNames"},"func_name":{"kind":"string","value":"testNameAliasingForObjects"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/Model/ModelRegistryTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Model/ModelRegistryTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2287,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideRangeConstraintDoesNotSetMinimumIfMinIsNotSet')]\n public function testReaderWithValidationGroupsEnabledChecksForDefaultGroupWhenNoSerializationGroupsArePassed(object $entity): void\n {\n $schema = $this->createObj(OA\\Schema::class, []);\n $schema->merge([$this->createObj(OA\\Property::class, ['property' => 'property1'])]);\n $reader = new SymfonyConstraintAnnotationReader(true);\n $reader->setSchema($schema);\n\n // no serialization groups passed here\n $reader->updateProperty(\n new \\ReflectionProperty($entity, 'property1'),\n $schema->properties[0]\n );\n\n self::assertSame(10, $schema->properties[0]->maximum, 'should have read constraints in the default group');\n }"},"docstring":{"kind":"string","value":"re-using another provider here, since all constraints land in the default\ngroup when `group={\"someGroup\"}` is not set."},"func_name":{"kind":"string","value":"testReaderWithValidationGroupsEnabledChecksForDefaultGroupWhenNoSerializationGroupsArePassed"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2288,"cells":{"code":{"kind":"string","value":"private function createObj(string $className, array $props = []): object\n {\n return new $className($props + ['_context' => new Context()]);\n }"},"docstring":{"kind":"string","value":"@template T of OA\\AbstractAnnotation\n\n@param class-string $className\n@param array $props\n\n@return T"},"func_name":{"kind":"string","value":"createObj"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2289,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideIndexedCollectionData')]\n public function testSearchIndexedCollectionItem(array $setup, array $asserts): void\n {\n foreach ($asserts as $collection => $items) {\n foreach ($items as $assert) {\n $setupCollection = !isset($assert['components']) ?\n ($setup[$collection] ?? []) :\n (Generator::UNDEFINED !== $setup['components']->{$collection} ? $setup['components']->{$collection} : []);\n\n // get the indexing correct within haystack preparation\n $properties = array_fill(0, \\count($setupCollection), null);\n\n // prepare the haystack array\n foreach ($items as $assertItem) {\n // e.g. $properties[1] = self::createObj(OA\\PathItem::class, ['path' => 'path 1'])\n $properties[$assertItem['index']] = self::createObj($assertItem['class'], [\n $assertItem['key'] => $assertItem['value'],\n ]);\n }\n\n self::assertSame(\n $assert['index'],\n Util::searchIndexedCollectionItem($properties, $assert['key'], $assert['value']),\n \\sprintf('Failed to get the correct index for %s', print_r($assert, true))\n );\n }\n }\n }"},"docstring":{"kind":"string","value":"@param array $setup\n@param array $asserts"},"func_name":{"kind":"string","value":"testSearchIndexedCollectionItem"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2290,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideIndexedCollectionData')]\n public function testGetIndexedCollectionItem(array $setup, array $asserts): void\n {\n $parent = new $setup['class'](array_merge(\n $this->getSetupPropertiesWithoutClass($setup),\n ['_context' => $this->rootContext]\n ));\n\n foreach ($asserts as $collection => $items) {\n foreach ($items as $assert) {\n $itemParent = !isset($assert['components']) ? $parent : $parent->components;\n\n self::assertTrue(is_a($assert['class'], OA\\AbstractAnnotation::class, true), \\sprintf('Invalid class %s', $assert['class']));\n $child = Util::getIndexedCollectionItem(\n $itemParent,\n $assert['class'],\n $assert['value']\n );\n\n self::assertInstanceOf($assert['class'], $child);\n self::assertSame($child->{$assert['key']}, $assert['value']);\n self::assertSame(\n $itemParent->{$collection}[$assert['index']],\n $child\n );\n\n $setupHaystack = !isset($assert['components']) ?\n $setup[$collection] ?? [] :\n $setup['components']->{$collection} ?? [];\n\n // the children created within provider are not connected\n if (!\\in_array($child, $setupHaystack, true)) {\n $this->assertIsNested($itemParent, $child);\n $this->assertIsConnectedToRootContext($child);\n }\n }\n }\n }"},"docstring":{"kind":"string","value":"@param array $setup\n@param array $asserts"},"func_name":{"kind":"string","value":"testGetIndexedCollectionItem"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2291,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideChildData')]\n public function testGetChild(string $parent, array $parentProperties, array $children): void\n {\n $parent = new $parent([\n ...$parentProperties,\n ...['_context' => $this->rootContext],\n ]);\n\n foreach ($children as $childClass => $childProperties) {\n self::assertTrue(is_a($childClass, OA\\AbstractAnnotation::class, true), \\sprintf('Invalid class %s', $childClass));\n\n $child = Util::createChild($parent, $childClass, $childProperties);\n self::assertInstanceOf($childClass, $child);\n\n self::assertEquals($childProperties, $this->getNonDefaultProperties($child));\n }\n }"},"docstring":{"kind":"string","value":"@param array> $parentProperties\n@param array, array> $children"},"func_name":{"kind":"string","value":"testGetChild"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2292,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideInvalidChildData')]\n public function testGetChildThrowsOnInvalidNestedProperty(string $parent, array $children): void\n {\n $parent = new $parent(['_context' => $this->rootContext]);\n\n foreach ($children as $childClass => $childProperties) {\n self::assertTrue(is_a($childClass, OA\\AbstractAnnotation::class, true), \\sprintf('Invalid class %s', $childClass));\n\n self::expectException(\\InvalidArgumentException::class);\n self::expectExceptionMessage('Nesting attribute properties is not supported, only nest classes.');\n\n Util::createChild($parent, $childClass, $childProperties);\n }\n }"},"docstring":{"kind":"string","value":"@param array, array> $children"},"func_name":{"kind":"string","value":"testGetChildThrowsOnInvalidNestedProperty"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2293,"cells":{"code":{"kind":"string","value":"#[DataProvider('provideMergeData')]\n public function testMerge(array $setup, $merge, array $assert): void\n {\n $api = self::createObj(OA\\OpenApi::class, $setup + ['_context' => new Context()]);\n\n Util::merge($api, $merge, false);\n self::assertTrue($api->validate());\n $actual = json_decode(json_encode($api), true);\n\n self::assertEquals($assert, $actual);\n }"},"docstring":{"kind":"string","value":"@param array $setup\n@param array|\\ArrayObject $merge\n@param array $assert"},"func_name":{"kind":"string","value":"testMerge"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2294,"cells":{"code":{"kind":"string","value":"private function getSetupPropertiesWithoutClass(array $setup): array\n {\n return array_filter($setup, function ($k) {return 'class' !== $k; }, \\ARRAY_FILTER_USE_KEY);\n }"},"docstring":{"kind":"string","value":"@param array $setup\n\n@return array"},"func_name":{"kind":"string","value":"getSetupPropertiesWithoutClass"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2295,"cells":{"code":{"kind":"string","value":"private static function createObj(string $className, array $props = []): object\n {\n return new $className($props + ['_context' => new Context()]);\n }"},"docstring":{"kind":"string","value":"@param class-string $className\n@param array $props"},"func_name":{"kind":"string","value":"createObj"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"nelmio/NelmioApiDocBundle"},"path":{"kind":"string","value":"tests/SwaggerPhp/UtilTest.php"},"url":{"kind":"string","value":"https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2296,"cells":{"code":{"kind":"string","value":"public function __construct(array $routes = [], string $basePath = '', array $matchTypes = [])\n {\n $this->addRoutes($routes);\n $this->setBasePath($basePath);\n $this->addMatchTypes($matchTypes);\n }"},"docstring":{"kind":"string","value":"Create router in one call from config.\n\n@param array $routes\n@param string $basePath\n@param array $matchTypes\n@throws Exception"},"func_name":{"kind":"string","value":"__construct"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"dannyvankooten/AltoRouter"},"path":{"kind":"string","value":"AltoRouter.php"},"url":{"kind":"string","value":"https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2297,"cells":{"code":{"kind":"string","value":"public function getRoutes(): array\n {\n return $this->routes;\n }"},"docstring":{"kind":"string","value":"Retrieves all routes.\nUseful if you want to process or display routes.\n@return array All routes."},"func_name":{"kind":"string","value":"getRoutes"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"dannyvankooten/AltoRouter"},"path":{"kind":"string","value":"AltoRouter.php"},"url":{"kind":"string","value":"https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2298,"cells":{"code":{"kind":"string","value":"public function addRoutes($routes)\n {\n if (!is_array($routes) && !$routes instanceof Traversable) {\n throw new RuntimeException('Routes should be an array or an instance of Traversable');\n }\n foreach ($routes as $route) {\n call_user_func_array([$this, 'map'], $route);\n }\n }"},"docstring":{"kind":"string","value":"Add multiple routes at once from array in the following format:\n\n $routes = [\n [$method, $route, $target, $name]\n ];\n\n@param array $routes\n@return void\n@author Koen Punt\n@throws Exception"},"func_name":{"kind":"string","value":"addRoutes"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"dannyvankooten/AltoRouter"},"path":{"kind":"string","value":"AltoRouter.php"},"url":{"kind":"string","value":"https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php"},"license":{"kind":"string","value":"MIT"}}},{"rowIdx":2299,"cells":{"code":{"kind":"string","value":"public function setBasePath(string $basePath)\n {\n $this->basePath = $basePath;\n }"},"docstring":{"kind":"string","value":"Set the base path.\nUseful if you are running your application from a subdirectory.\n@param string $basePath"},"func_name":{"kind":"string","value":"setBasePath"},"language":{"kind":"string","value":"php"},"repo":{"kind":"string","value":"dannyvankooten/AltoRouter"},"path":{"kind":"string","value":"AltoRouter.php"},"url":{"kind":"string","value":"https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php"},"license":{"kind":"string","value":"MIT"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":22,"numItemsPerPage":100,"numTotalItems":905197,"offset":2200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjMzMDc2Miwic3ViIjoiL2RhdGFzZXRzL1NodXUxMjEyMS9waHAtdHJlZXNpdHRlci1maWx0ZXJlZC1kYXRhc2V0c1YyIiwiZXhwIjoxNzU2MzM0MzYyLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.tqr7ZmA7LCyW5QnBie5DOds9_IrZcWNkvB5HkadhNwJzWDjI-GPKhHz0T6U9aM7AuZSiz7ts0D561_r9TgwvBg","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
Subset (1)
default (1.01M rows)
Split (3)
train (905k rows) validation (99.8k rows) test (7.62k rows)
private function isBooleansArray(array $array): bool
{
foreach ($array as $item) {
if (!\is_bool($item)) {
return false;
}
}
return true;
}
@param mixed[] $array
@return bool true if $array contains only booleans, false otherwise
nelmio/NelmioApiDocBundle
src/ModelDescriber/FormModelDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/FormModelDescriber.php
private function computeGroups(Context $context, ?array $type = null): ?array
{
if (null === $type || true !== $this->propertyTypeUsesGroups($type)) {
return null;
}
$groupsExclusion = $context->getExclusionStrategy();
if (!($groupsExclusion instanceof GroupsExclusionStrategy)) {
return null;
}
$groups = $groupsExclusion->getGroupsFor($context);
if ([GroupsExclusionStrategy::DEFAULT_GROUP] === $groups) {
return null;
}
return $groups;
}
@param mixed[]|null $type
@return string[]|null
nelmio/NelmioApiDocBundle
src/ModelDescriber/JMSModelDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/JMSModelDescriber.php
public function describeItem(array $type, OA\Schema $property, Context $context, array $serializationContext): void
{
$nestedTypeInfo = $this->getNestedTypeInArray($type);
if (null !== $nestedTypeInfo) {
[$nestedType, $isHash] = $nestedTypeInfo;
if ($isHash) {
$property->type = 'object';
$property->additionalProperties = Util::createChild($property, OA\AdditionalProperties::class);
// this is a free form object (as nested array)
if ('array' === $nestedType['name'] && !isset($nestedType['params'][0])) {
// in the case of a virtual property, set it as free object type
$property->additionalProperties = true;
return;
}
$this->describeItem($nestedType, $property->additionalProperties, $context, $serializationContext);
return;
}
$property->type = 'array';
$property->items = Util::createChild($property, OA\Items::class);
$this->describeItem($nestedType, $property->items, $context, $serializationContext);
} elseif ('array' === $type['name']) {
$property->type = 'object';
$property->additionalProperties = true;
} elseif ('string' === $type['name']) {
$property->type = 'string';
} elseif (\in_array($type['name'], ['bool', 'boolean'], true)) {
$property->type = 'boolean';
} elseif (\in_array($type['name'], ['int', 'integer'], true)) {
$property->type = 'integer';
} elseif (\in_array($type['name'], ['double', 'float'], true)) {
$property->type = 'number';
$property->format = $type['name'];
} elseif (is_a($type['name'], \DateTimeInterface::class, true)) {
$property->type = 'string';
$property->format = 'date-time';
} else {
// See https://github.com/schmittjoh/serializer/blob/5a5a03a/src/Metadata/Driver/EnumPropertiesDriver.php#L51
if ('enum' === $type['name']
&& isset($type['params'][0])
) {
$typeParam = $type['params'][0];
if (isset($typeParam['name'])) {
$typeParam = $typeParam['name'];
}
if (\is_string($typeParam) && enum_exists($typeParam)) {
$type['name'] = $typeParam;
}
if (isset($type['params'][1])) {
if ('value' !== $type['params'][1] && is_a($type['name'], \BackedEnum::class, true)) {
// In case of a backed enum, it is possible to serialize it using its names instead of values
// Set a specific serialization context property to enforce a new model, as options cannot be used to force a new model
// See https://github.com/schmittjoh/serializer/blob/5a5a03a71a28a480189c5a0ca95893c19f1d120c/src/Handler/EnumHandler.php#L47
$serializationContext[EnumModelDescriber::FORCE_NAMES] = true;
}
}
}
$groups = $this->computeGroups($context, $type);
unset($serializationContext['groups']);
$model = new Model(new Type(Type::BUILTIN_TYPE_OBJECT, false, $type['name']), $groups, [], $serializationContext);
$modelRef = $this->modelRegistry->register($model);
$customFields = (array) $property->jsonSerialize();
unset($customFields['property']);
if ([] === $customFields) { // no custom fields
$property->ref = $modelRef;
} else {
$weakContext = Util::createWeakContext($property->_context);
$property->oneOf = [new OA\Schema(['ref' => $modelRef, '_context' => $weakContext])];
}
$this->contexts[$model->getHash()] = $context;
$this->metadataStacks[$model->getHash()] = clone $context->getMetadataStack();
}
}
@internal
@param mixed[] $type
@param mixed[] $serializationContext
nelmio/NelmioApiDocBundle
src/ModelDescriber/JMSModelDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/JMSModelDescriber.php
private function getNestedTypeInArray(array $type): ?array
{
if ('array' !== $type['name'] && 'ArrayCollection' !== $type['name']) {
return null;
}
// array<string, MyNamespaceMyObject>
if (isset($type['params'][1]['name'])) {
return [$type['params'][1], true];
}
// array<MyNamespaceMyObject>
if (isset($type['params'][0]['name'])) {
return [$type['params'][0], false];
}
return null;
}
@param mixed[] $type
@return array{0: mixed, 1: bool}|null
nelmio/NelmioApiDocBundle
src/ModelDescriber/JMSModelDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/JMSModelDescriber.php
public function __construct(
PropertyInfoExtractorInterface $propertyInfo,
PropertyDescriberInterface|TypeDescriberInterface $propertyDescribers,
array $mediaTypes,
?NameConverterInterface $nameConverter = null,
bool $useValidationGroups = false,
?ClassMetadataFactoryInterface $classMetadataFactory = null,
) {
$this->propertyInfo = $propertyInfo;
$this->propertyDescriber = $propertyDescribers;
$this->mediaTypes = $mediaTypes;
$this->nameConverter = $nameConverter;
$this->useValidationGroups = $useValidationGroups;
$this->classMetadataFactory = $classMetadataFactory;
}
@param (NameConverterInterface&AdvancedNameConverterInterface)|null $nameConverter
@param string[] $mediaTypes
nelmio/NelmioApiDocBundle
src/ModelDescriber/ObjectModelDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/ObjectModelDescriber.php
private function markRequiredProperties(OA\Schema $schema): void
{
if (Generator::isDefault($properties = $schema->properties)) {
return;
}
$newRequired = [];
foreach ($properties as $property) {
if (\is_array($schema->required) && \in_array($property->property, $schema->required, true)) {
$newRequired[] = $property->property;
continue;
}
if (true === $property->nullable || !Generator::isDefault($property->default)) {
continue;
}
$newRequired[] = $property->property;
}
if ([] !== $newRequired) {
$originalRequired = Generator::isDefault($schema->required) ? [] : $schema->required;
$schema->required = array_values(array_unique(array_merge($newRequired, $originalRequired)));
}
}
Mark properties as required while ordering them in the same order as the properties of the schema.
Then append the original required properties.
nelmio/NelmioApiDocBundle
src/ModelDescriber/ObjectModelDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/ObjectModelDescriber.php
public function updateProperty($reflection, OA\Property $property, ?array $serializationGroups = null): void
{
$this->openApiAnnotationsReader->updateProperty($reflection, $property, $serializationGroups);
$this->phpDocReader->updateProperty($reflection, $property);
$this->reflectionReader->updateProperty($reflection, $property);
$this->symfonyConstraintAnnotationReader->updateProperty($reflection, $property, $serializationGroups);
}
@param \ReflectionProperty|\ReflectionMethod $reflection
@param string[]|null $serializationGroups
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/AnnotationsReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/AnnotationsReader.php
private function shouldDescribeModelProperties(OA\Schema $schema): bool
{
return (Generator::UNDEFINED === $schema->type || 'object' === $schema->type)
&& Generator::UNDEFINED === $schema->ref;
}
Whether the model describer should continue reading class properties
after updating the open api schema from an `OA\Schema` definition.
Users may manually define a `type` or `ref` on a schema, and if that's the case
model describers should _probably_ not describe any additional properties or try
to merge in properties.
shouldDescribeModelProperties
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/AnnotationsReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/AnnotationsReader.php
public function updateProperty($reflection, OA\Property $property, ?array $serializationGroups = null): void
{
if (null === $oaProperty = $this->getAttribute($property->_context, $reflection, OA\Property::class)) {
return;
}
// Read #[Model] attributes
$this->modelRegister->__invoke(new Analysis([$oaProperty], Util::createContext()), $serializationGroups);
if (!$oaProperty->validate()) {
return;
}
$property->mergeProperties($oaProperty);
}
@param \ReflectionProperty|\ReflectionMethod $reflection
@param string[]|null $serializationGroups
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
private function getAttribute(Context $parentContext, $reflection, string $className)
{
$this->setContextFromReflection($parentContext, $reflection);
try {
if (null !== $attribute = $reflection->getAttributes($className, \ReflectionAttribute::IS_INSTANCEOF)[0] ?? null) {
return $attribute->newInstance();
}
} finally {
$this->setContext(null);
}
return null;
}
@template T of object
@param \ReflectionClass|\ReflectionProperty|\ReflectionMethod $reflection
@param class-string<T> $className
@return T|null
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
public function updateProperty($reflection, OA\Property $property): void
{
try {
$docBlock = $this->docBlockFactory->create($reflection);
} catch (\Exception $e) {
// ignore
return;
}
$title = $docBlock->getSummary();
/** @var Var_ $var */
foreach ($docBlock->getTagsByName('var') as $var) {
if ('' === $title && method_exists($var, 'getDescription') && null !== $description = $var->getDescription()) {
$title = $description->render();
}
if (
!isset($min)
&& !isset($max)
&& method_exists($var, 'getType') && null !== $varType = $var->getType()
) {
$types = $varType instanceof Compound
? $varType->getIterator()
: [$varType];
foreach ($types as $type) {
if ($type instanceof IntegerRange) {
$min = is_numeric($type->getMinValue()) ? (int) $type->getMinValue() : null;
$max = is_numeric($type->getMaxValue()) ? (int) $type->getMaxValue() : null;
break;
} elseif ($type instanceof PositiveInteger) {
$min = 1;
$max = null;
break;
} elseif ($type instanceof NegativeInteger) {
$min = null;
$max = -1;
break;
}
}
}
}
if (Generator::UNDEFINED === $property->title && '' !== $title) {
$property->title = $title;
}
if (Generator::UNDEFINED === $property->description && '' !== $docBlock->getDescription()->render()) {
$property->description = $docBlock->getDescription()->render();
}
if (Generator::UNDEFINED === $property->minimum && isset($min)) {
$property->minimum = $min;
}
if (Generator::UNDEFINED === $property->maximum && isset($max)) {
$property->maximum = $max;
}
}
Update the Swagger information with information from the DocBlock comment.
@param \ReflectionProperty|\ReflectionMethod $reflection
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/PropertyPhpDocReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/PropertyPhpDocReader.php
public function updateProperty(
$reflection,
OA\Property $property,
): void {
// The default has been set by an Annotation or Attribute
// We leave that as it is!
if (Generator::UNDEFINED !== $property->default) {
return;
}
$serializedName = $reflection->getName();
foreach (['get', 'is', 'has', 'can', 'add', 'remove', 'set'] as $prefix) {
if (str_starts_with($serializedName, $prefix)) {
$serializedName = substr($serializedName, \strlen($prefix));
}
}
if ($reflection instanceof \ReflectionMethod) {
$methodDefault = $this->getDefaultFromMethodReflection($reflection);
if (Generator::UNDEFINED !== $methodDefault) {
if (null === $methodDefault) {
$property->nullable = true;
return;
}
$property->default = $methodDefault;
return;
}
}
if ($reflection instanceof \ReflectionProperty) {
$propertyDefault = $this->getDefaultFromPropertyReflection($reflection);
if (Generator::UNDEFINED !== $propertyDefault) {
if (Generator::UNDEFINED === $property->nullable && null === $propertyDefault) {
$property->nullable = true;
return;
}
$property->default = $propertyDefault;
return;
}
}
// Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/2222
// Promoted properties with a value initialized by the constructor are not considered to have a default value
// and are therefore not returned by ReflectionClass::getDefaultProperties(); see https://bugs.php.net/bug.php?id=81386
$reflClassConstructor = $reflection->getDeclaringClass()->getConstructor();
$reflClassConstructorParameters = null !== $reflClassConstructor ? $reflClassConstructor->getParameters() : [];
foreach ($reflClassConstructorParameters as $parameter) {
if ($parameter->name !== $serializedName) {
continue;
}
if (!$parameter->isDefaultValueAvailable()) {
continue;
}
if (null === $this->schema) {
continue;
}
if (!Generator::isDefault($property->default)) {
continue;
}
$default = $parameter->getDefaultValue();
if (Generator::UNDEFINED === $property->nullable && null === $default) {
$property->nullable = true;
}
$property->default = $default;
}
}
Update the given property and schema with defined Symfony constraints.
@param \ReflectionProperty|\ReflectionMethod $reflection
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/ReflectionReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/ReflectionReader.php
private function hasImplicitNullDefaultValue(\ReflectionProperty $reflection): bool
{
if (null !== $reflection->getDefaultValue()) {
return false;
}
if (false === $reflection->getDocComment()) {
return true;
}
$docComment = $reflection->getDocComment();
if (!preg_match('/@var\s+([^\s]+)/', $docComment, $matches)) {
return true;
}
return !str_contains(strtolower($matches[1]), 'null');
}
Check whether the default value is an implicit null.
An implicit null would be any null value that is not explicitly set and
contradicts a set DocBlock @ var annotation
So a property without an explicit value but an `@var int` docblock
would be considered as not having an implicit null default value as
that contradicts the annotation.
A property without a default value and no docblock would be considered
to have an explicit NULL default value to be set though.
hasImplicitNullDefaultValue
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/ReflectionReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/ReflectionReader.php
public function updateProperty($reflection, OA\Property $property, ?array $validationGroups = null): void
{
foreach ($this->getAttributes($property->_context, $reflection, $validationGroups) as $outerAttribute) {
$innerAttributes = $outerAttribute instanceof Assert\Compound || $outerAttribute instanceof Assert\Sequentially
? $outerAttribute->constraints
: [$outerAttribute];
$this->processPropertyAttributes($reflection, $property, $innerAttributes);
}
}
Update the given property and schema with defined Symfony constraints.
@param \ReflectionProperty|\ReflectionMethod $reflection
@param string[]|null $validationGroups
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
private function processPropertyAttributes($reflection, OA\Property $property, array $attributes): void
{
foreach ($attributes as $attribute) {
if ($attribute instanceof Assert\NotBlank || $attribute instanceof Assert\NotNull) {
if ($attribute instanceof Assert\NotBlank && $attribute->allowNull) {
// The field is optional
return;
}
// The field is required
if (null === $this->schema) {
return;
}
$propertyName = Util::getSchemaPropertyName($this->schema, $property);
if (null === $propertyName) {
return;
}
if (!Generator::isDefault($property->default)) {
return;
}
$existingRequiredFields = Generator::UNDEFINED !== $this->schema->required ? $this->schema->required : [];
$existingRequiredFields[] = $propertyName;
$this->schema->required = array_values(array_unique($existingRequiredFields));
$property->nullable = false;
} elseif ($attribute instanceof Assert\Length) {
if (isset($attribute->min)) {
$property->minLength = $attribute->min;
}
if (isset($attribute->max)) {
$property->maxLength = $attribute->max;
}
} elseif ($attribute instanceof Assert\Regex) {
$this->appendPattern($property, $attribute->getHtmlPattern());
} elseif ($attribute instanceof Assert\Count) {
if (isset($attribute->min)) {
$property->minItems = $attribute->min;
}
if (isset($attribute->max)) {
$property->maxItems = $attribute->max;
}
} elseif ($attribute instanceof Assert\Choice) {
$this->applyEnumFromChoiceConstraint($property, $attribute, $reflection);
} elseif ($attribute instanceof Assert\Range) {
if (\is_int($attribute->min)) {
$property->minimum = $attribute->min;
}
if (\is_int($attribute->max)) {
$property->maximum = $attribute->max;
}
} elseif ($attribute instanceof Assert\LessThan) {
if (\is_int($attribute->value)) {
$property->exclusiveMaximum = true;
$property->maximum = $attribute->value;
}
} elseif ($attribute instanceof Assert\LessThanOrEqual) {
if (\is_int($attribute->value)) {
$property->maximum = $attribute->value;
}
} elseif ($attribute instanceof Assert\GreaterThan) {
if (\is_int($attribute->value)) {
$property->exclusiveMinimum = true;
$property->minimum = $attribute->value;
}
} elseif ($attribute instanceof Assert\GreaterThanOrEqual) {
if (\is_int($attribute->value)) {
$property->minimum = $attribute->value;
}
}
}
}
@param \ReflectionProperty|\ReflectionMethod $reflection
@param Constraint[] $attributes
processPropertyAttributes
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
private function appendPattern(OA\Schema $property, ?string $newPattern): void
{
if (null === $newPattern) {
return;
}
if (Generator::UNDEFINED !== $property->pattern) {
$property->pattern = \sprintf('%s, %s', $property->pattern, $newPattern);
} else {
$property->pattern = $newPattern;
}
}
Append the pattern from the constraint to the existing pattern.
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
private function getAttributes(Context $parentContext, $reflection, ?array $validationGroups): iterable
{
// To correctly load OA attributes
$this->setContextFromReflection($parentContext, $reflection);
foreach ($this->locateAttributes($reflection) as $attribute) {
if (!$this->useValidationGroups || $this->isConstraintInGroup($attribute, $validationGroups)) {
yield $attribute;
}
}
$this->setContext(null);
}
@param \ReflectionProperty|\ReflectionMethod $reflection
@param string[]|null $validationGroups
@return iterable<Constraint>
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
private function locateAttributes($reflection): \Traversable
{
if (class_exists(Constraint::class)) {
foreach ($reflection->getAttributes(Constraint::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
yield $attribute->newInstance();
}
}
}
@param \ReflectionProperty|\ReflectionMethod $reflection
@return \Traversable<Constraint>
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
private function isConstraintInGroup(Constraint $attribute, ?array $validationGroups): bool
{
if (null === $validationGroups) {
$validationGroups = [Constraint::DEFAULT_GROUP];
}
return [] !== array_intersect(
$validationGroups,
(array) $attribute->groups
);
}
Check to see if the given constraint is in the provided serialization groups.
If no groups are provided the validator would run in the Constraint::DEFAULT_GROUP,
and constraints without any `groups` passed to them would be in that same
default group. So even with a null $validationGroups passed here there still
has to be a check on the default group.
@param string[]|null $validationGroups
nelmio/NelmioApiDocBundle
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
private function getGroups(ModelAnnotation $model, ?array $parentGroups = null): ?array
{
if (null === $model->groups) {
return $parentGroups;
}
return array_merge($parentGroups ?? [], $model->groups);
}
@param string[]|null $parentGroups
@return string[]|null
nelmio/NelmioApiDocBundle
src/OpenApiPhp/ModelRegister.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/ModelRegister.php
public static function getPath(OA\OpenApi $api, string $path): OA\PathItem
{
return self::getIndexedCollectionItem($api, OA\PathItem::class, $path);
}
Return an existing PathItem object from $api->paths[] having its member path set to $path.
Create, add to $api->paths[] and return this new PathItem object and set the property if none found.
@see OA\OpenApi::$paths
@see OA\PathItem::path
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getTag(OA\OpenApi $api, string $name): OA\Tag
{
// Tags ar not considered indexed, so we cannot use getIndexedCollectionItem directly
// because we need to specify that the search should use the "name" property.
$key = self::searchIndexedCollectionItem(
\is_array($api->tags) ? $api->tags : [],
'name',
$name
);
if (false === $key) {
$key = self::createCollectionItem($api, 'tags', OA\Tag::class, ['name' => $name]);
}
return $api->tags[$key];
}
Return an existing Tag object from $api->tags[] having its member name set to $name.
Create, add to $api->tags[] and return this new Tag object and set the property if none found.
@see OA\OpenApi::$tags
@see OA\Tag::$name
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getSchema(OA\OpenApi $api, string $schema): OA\Schema
{
if (!$api->components instanceof OA\Components) {
$api->components = new OA\Components(['_context' => self::createWeakContext($api->_context)]);
}
return self::getIndexedCollectionItem($api->components, OA\Schema::class, $schema);
}
Return an existing Schema object from $api->components->schemas[] having its member schema set to $schema.
Create, add to $api->components->schemas[] and return this new Schema object and set the property if none found.
@see OA\Schema::$schema
@see OA\Components::$schemas
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getProperty(OA\Schema $schema, string $property): OA\Property
{
return self::getIndexedCollectionItem($schema, OA\Property::class, $property);
}
Return an existing Property object from $schema->properties[]
having its member property set to $property.
Create, add to $schema->properties[] and return this new Property object
and set the property if none found.
@see OA\Schema::$properties
@see OA\Property::$property
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getOperation(OA\PathItem $path, string $method): OA\Operation
{
$class = array_keys($path::$_nested, strtolower($method), true)[0];
if (!is_a($class, OA\Operation::class, true)) {
throw new \InvalidArgumentException('Invalid operation class provided.');
}
return self::getChild($path, $class, ['path' => $path->path]);
}
Return an existing Operation from $path->{$method}
or create, set $path->{$method} and return this new Operation object.
@see OA\PathItem::$post
@see OA\PathItem::$put
@see OA\PathItem::$patch
@see OA\PathItem::$delete
@see OA\PathItem::$options
@see OA\PathItem::$head
@see OA\PathItem::$get
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getOperationParameter(OA\Operation $operation, $name, $in): OA\Parameter
{
return self::getCollectionItem($operation, OA\Parameter::class, ['name' => $name, 'in' => $in]);
}
Return an existing Parameter object from $operation->parameters[]
having its members name set to $name and in set to $in.
Create, add to $operation->parameters[] and return
this new Parameter object and set its members if none found.
@see OA\Operation::$parameters
@see OA\Parameter::$name
@see OA\Parameter::$in
@param string $name
@param string $in
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getChild(OA\AbstractAnnotation $parent, string $class, array $properties = []): OA\AbstractAnnotation
{
$nested = $parent::$_nested;
$property = $nested[$class];
if (null === $parent->{$property} || Generator::UNDEFINED === $parent->{$property}) {
$parent->{$property} = self::createChild($parent, $class, $properties);
}
return $parent->{$property};
}
Return an existing nested Annotation from $parent->{$property} if exists.
Create, add to $parent->{$property} and set its members to $properties otherwise.
$property is determined from $parent::$_nested[$class]
it is expected to be a string nested property.
@template T of OA\AbstractAnnotation
@param class-string<T> $class
@param array<string, mixed> $properties
@return T
@see OA\AbstractAnnotation::$_nested
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getCollectionItem(OA\AbstractAnnotation $parent, string $class, array $properties = []): OA\AbstractAnnotation
{
$key = null;
$nested = $parent::$_nested;
$collection = $nested[$class][0];
if ([] !== $properties) {
$key = self::searchCollectionItem(
$parent->{$collection} && Generator::UNDEFINED !== $parent->{$collection} ? $parent->{$collection} : [],
$properties
);
}
if (null === $key) {
$key = self::createCollectionItem($parent, $collection, $class, $properties);
}
return $parent->{$collection}[$key];
}
Return an existing nested Annotation from $parent->{$collection}[]
having all $properties set to the respective values.
Create, add to $parent->{$collection}[] and set its members
to $properties otherwise.
$collection is determined from $parent::$_nested[$class]
it is expected to be a single value array nested Annotation.
@template T of OA\AbstractAnnotation
@param class-string<T> $class
@param array<string, mixed> $properties
@return T
@see OA\AbstractAnnotation::$_nested
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getIndexedCollectionItem(OA\AbstractAnnotation $parent, string $class, mixed $value): OA\AbstractAnnotation
{
$nested = $parent::$_nested;
[$collection, $property] = $nested[$class];
$key = self::searchIndexedCollectionItem(
$parent->{$collection} && Generator::UNDEFINED !== $parent->{$collection} ? $parent->{$collection} : [],
$property,
$value
);
if (false === $key) {
$key = self::createCollectionItem($parent, $collection, $class, [$property => $value]);
}
return $parent->{$collection}[$key];
}
Return an existing nested Annotation from $parent->{$collection}[]
having its mapped $property set to $value.
Create, add to $parent->{$collection}[] and set its member $property to $value otherwise.
$collection is determined from $parent::$_nested[$class]
it is expected to be a double value array nested Annotation
with the second value being the mapping index $property.
@template T of OA\AbstractAnnotation
@param class-string<T> $class
@param mixed $value The value to set
@return T
@see OA\AbstractAnnotation::$_nested
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function searchCollectionItem(array $collection, array $properties)
{
foreach ($collection as $i => $child) {
foreach ($properties as $k => $prop) {
if ($child->{$k} !== $prop) {
continue 2;
}
}
return $i;
}
return null;
}
Search for an Annotation within $collection that has all members set
to the respective values in the associative array $properties.
@param mixed[] $properties
@param mixed[] $collection
@return int|string|null
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function searchIndexedCollectionItem(array $collection, string $member, mixed $value)
{
foreach ($collection as $i => $child) {
if ($child->{$member} === $value) {
return $i;
}
}
return false;
}
Search for an Annotation within the $collection that has its member $index set to $value.
@param OA\AbstractAnnotation[] $collection
@param mixed $value The value to search for
@return false|int|string
searchIndexedCollectionItem
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function createCollectionItem(OA\AbstractAnnotation $parent, string $collection, string $class, array $properties = []): int
{
if (Generator::UNDEFINED === $parent->{$collection}) {
$parent->{$collection} = [];
}
$key = \count($parent->{$collection} ?? []);
$parent->{$collection}[$key] = self::createChild($parent, $class, $properties);
return $key;
}
Create a new Object of $class with members $properties within $parent->{$collection}[]
and return the created index.
@template T of OA\AbstractAnnotation
@param class-string<T> $class
@param array<string, mixed> $properties
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function createChild(OA\AbstractAnnotation $parent, string $class, array $properties = []): OA\AbstractAnnotation
{
$nesting = self::getNestingIndexes($class);
foreach ($nesting as $childClass => $property) {
// Check if a nested property is defined
if (!\in_array($property, array_keys($properties), true)) {
continue;
}
$propertyMapping = $class::$_nested[$childClass];
// Single class value
if (\is_string($propertyMapping)) {
if (!is_a($properties[$propertyMapping], $childClass, true)) {
throw new \InvalidArgumentException('Nesting attribute properties is not supported, only nest classes.');
}
continue;
}
foreach ($properties[$propertyMapping[0]] as $childProperty) {
if (!is_a($childProperty, $childClass, true)) {
throw new \InvalidArgumentException('Nesting attribute properties is not supported, only nest classes.');
}
}
}
return new $class(
array_merge($properties, ['_context' => self::createContext(['nested' => $parent], $parent->_context)])
);
}
Create a new Object of $class with members $properties and set the context parent to be $parent.
@template T of OA\AbstractAnnotation
@param class-string<T> $class
@param array<string, mixed> $properties
@return T
@throws \InvalidArgumentException at an attempt to pass in properties that are found in $parent::$_nested
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function createContext(array $properties = [], ?Context $parent = null): Context
{
return new Context($properties, $parent);
}
Create a new Context with members $properties and parent context $parent.
@param array<string, mixed> $properties
@see Context
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function createWeakContext(?Context $parent = null, array $additionalProperties = []): Context
{
$propsToCopy = [
'version',
'line',
'character',
'namespace',
'class',
'interface',
'trait',
'method',
'property',
'logger',
];
$filteredProps = [];
foreach ($propsToCopy as $prop) {
$value = $parent->{$prop} ?? null;
if (null === $value) {
continue;
}
$filteredProps[$prop] = $value;
}
return new Context(array_merge($filteredProps, $additionalProperties));
}
Create a new Context by copying the properties of the parent, but without a reference to the parent.
@param array<string, mixed> $additionalProperties
@see Context
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function merge(OA\AbstractAnnotation $annotation, $from, bool $overwrite = false): void
{
if (\is_array($from)) {
self::mergeFromArray($annotation, $from, $overwrite);
} elseif (is_a($from, OA\AbstractAnnotation::class)) {
/* @var OA\AbstractAnnotation $from */
self::mergeFromArray($annotation, json_decode(json_encode($from), true), $overwrite);
} elseif (is_a($from, \ArrayObject::class)) {
/* @var \ArrayObject $from */
self::mergeFromArray($annotation, $from->getArrayCopy(), $overwrite);
}
}
Merge $from into $annotation. $overwrite is only used for leaf scalar values.
The main purpose is to create a Swagger Object from array config values
in the structure of a json serialized Swagger object.
@param array<mixed>|\ArrayObject|OA\AbstractAnnotation $from
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function getSchemaPropertyName(OA\Schema $schema, OA\Schema $property): ?string
{
if (Generator::UNDEFINED === $schema->properties) {
return null;
}
foreach ($schema->properties as $schemaProperty) {
if ($schemaProperty === $property) {
return Generator::UNDEFINED !== $schemaProperty->property ? $schemaProperty->property : null;
}
}
return null;
}
Get assigned property name for property schema.
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
private static function mergeChild(OA\AbstractAnnotation $annotation, string $className, mixed $value, bool $overwrite): void
{
self::merge(self::getChild($annotation, $className), $value, $overwrite);
}
@template T of OA\AbstractAnnotation
@param class-string<T> $className
@param mixed $value The value of the property
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
private static function mergeCollection(OA\AbstractAnnotation $annotation, string $className, ?string $property, $items, bool $overwrite): void
{
if (null !== $property) {
foreach ($items as $prop => $value) {
$child = self::getIndexedCollectionItem($annotation, $className, (string) $prop);
self::merge($child, $value);
}
} else {
$nesting = self::getNestingIndexes($className);
foreach ($items as $props) {
$create = [];
$merge = [];
foreach ($props as $k => $v) {
if (\in_array($k, $nesting, true)) {
$merge[$k] = $v;
} else {
$create[$k] = $v;
}
}
self::merge(self::getCollectionItem($annotation, $className, $create), $merge, $overwrite);
}
}
}
@template T of OA\AbstractAnnotation
@param class-string<T> $className
@param array<mixed>|\ArrayObject $items
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
private static function mergeTyped(OA\AbstractAnnotation $annotation, string $propertyName, $type, array $properties, array $defaults, bool $overwrite): void
{
if (\is_string($type) && str_starts_with($type, '[')) {
$innerType = substr($type, 1, -1);
if (!$annotation->{$propertyName} || Generator::UNDEFINED === $annotation->{$propertyName}) {
$annotation->{$propertyName} = [];
}
if (!class_exists($innerType)) {
/* type is declared as array in @see OA\AbstractAnnotation::$_types */
$annotation->{$propertyName} = array_unique(array_merge(
$annotation->{$propertyName},
$properties[$propertyName]
));
return;
}
// $type == [Schema] for instance
foreach ($properties[$propertyName] as $child) {
$annotation->{$propertyName}[] = $annot = self::createChild($annotation, $innerType, []);
self::merge($annot, $child, $overwrite);
}
} else {
self::mergeProperty($annotation, $propertyName, $properties[$propertyName], $defaults[$propertyName], $overwrite);
}
}
@param array<string, mixed> $properties
@param array<string, mixed> $defaults
@param string|array<string> $type
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
private static function mergeProperty(OA\AbstractAnnotation $annotation, string $propertyName, $value, $default, bool $overwrite): void
{
if (true === $overwrite || $default === $annotation->{$propertyName}) {
$annotation->{$propertyName} = $value;
}
}
@param mixed $value The new value of the property
@param mixed $default The default value of the property
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
private static function getNestingIndexes(string $class): array
{
return array_map(function ($property) {
return \is_array($property) ? $property[0] : $property;
}, $class::$_nested);
}
@template T of OA\AbstractAnnotation
@param class-string<T> $class
@return array<class-string<OA\AbstractAnnotation>, string|array<string>>
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public static function modifyAnnotationValue(OA\AbstractAnnotation $parameter, string $property, $value): void
{
if (!Generator::isDefault($parameter->{$property})) {
return;
}
$parameter->{$property} = $value;
}
Helper method to modify an annotation value only if its value has not yet been set.
@param mixed $value The new value to set
nelmio/NelmioApiDocBundle
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'array';
/** @var OA\Items $property */
$property = Util::getChild($property, OA\Items::class);
foreach ($types[0]->getCollectionValueTypes() as $type) {
// Handle list pseudo type
// https://symfony.com/doc/current/components/property_info.html#type-getcollectionkeytypes-type-getcollectionvaluetypes
if ($this->supports([$type], $context) && [] === $type->getCollectionValueTypes()) {
continue;
}
$this->propertyDescriber->describe([$type], $property, $context);
}
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/ArrayPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/ArrayPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'boolean';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/BooleanPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/BooleanPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->oneOf = Generator::UNDEFINED !== $property->oneOf ? $property->oneOf : [];
foreach ($types as $type) {
$property->oneOf[] = $schema = Util::createChild($property, OA\Schema::class, []);
$this->propertyDescriber->describe([$type], $schema, $context);
}
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/CompoundPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/CompoundPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'string';
$property->format = 'date-time';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/DateTimePropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/DateTimePropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'object';
/** @var OA\AdditionalProperties $additionalProperties */
$additionalProperties = Util::getChild($property, OA\AdditionalProperties::class);
$this->propertyDescriber->describe($types[0]->getCollectionValueTypes(), $additionalProperties, $context);
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/DictionaryPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/DictionaryPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'number';
$property->format = 'float';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/FloatPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/FloatPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'integer';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/IntegerPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/IntegerPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
if (Generator::UNDEFINED === $property->nullable) {
$property->nullable = true;
}
$this->propertyDescriber->describe($types, $property, $context);
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/NullablePropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/NullablePropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$type = new Type(
$types[0]->getBuiltinType(),
false,
$types[0]->getClassName(),
$types[0]->isCollection(),
$types[0]->getCollectionKeyTypes(),
$types[0]->getCollectionValueTypes()[0] ?? null,
); // ignore nullable field
if (null === $types[0]->getClassName()) {
$property->type = 'object';
$property->additionalProperties = true;
return;
}
if ($types[0]->isNullable()) {
$weakContext = Util::createWeakContext($property->_context);
$schemas = [new OA\Schema(['ref' => $this->modelRegistry->register(new Model($type, serializationContext: $context)), '_context' => $weakContext])];
$property->oneOf = $schemas;
return;
}
$property->ref = $this->modelRegistry->register(new Model($type, serializationContext: $context));
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/ObjectPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/ObjectPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
if (null === $propertyDescriber = $this->getPropertyDescriber($types, $context)) {
return;
}
$this->called[$this->getHash($types)][] = $propertyDescriber;
$propertyDescriber->describe($types, $property, $context);
$this->called = []; // Reset recursion helper
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/PropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/PropertyDescriber.php
private function getPropertyDescriber(array $types, array $context): ?PropertyDescriberInterface
{
foreach ($this->propertyDescribers as $propertyDescriber) {
// Prevent infinite recursion
if (\array_key_exists($this->getHash($types), $this->called)) {
if (\in_array($propertyDescriber, $this->called[$this->getHash($types)], true)) {
continue;
}
}
if ($propertyDescriber instanceof ModelRegistryAwareInterface) {
$propertyDescriber->setModelRegistry($this->modelRegistry);
}
if ($propertyDescriber instanceof PropertyDescriberAwareInterface) {
$propertyDescriber->setPropertyDescriber($this);
}
if ($propertyDescriber->supports($types, $context)) {
return $propertyDescriber;
}
}
return null;
}
@param Type[] $types
@param array<string, mixed> $context
nelmio/NelmioApiDocBundle
src/PropertyDescriber/PropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/PropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'string';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/StringPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/StringPropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'string';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/TranslatablePropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/TranslatablePropertyDescriber.php
public function describe(array $types, OA\Schema $property, array $context = []): void
{
$property->type = 'string';
$property->format = 'uuid';
}
@param array<string, mixed> $context Context options for describing the property
nelmio/NelmioApiDocBundle
src/PropertyDescriber/UuidPropertyDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/UuidPropertyDescriber.php
public function renderFromRequest(Request $request, string $format, string $area, array $extraOptions = [])
{
$options = [];
if ('' !== $request->getBaseUrl()) {
$options += [
'fallback_url' => $request->getSchemeAndHttpHost().$request->getBaseUrl(),
];
}
$options += $extraOptions;
return $this->render($format, $area, $options);
}
@param array<string, mixed> $extraOptions
@return string
nelmio/NelmioApiDocBundle
src/Render/RenderOpenApi.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/RenderOpenApi.php
public function render(string $format, string $area, array $options = []): string
{
if (!$this->generatorLocator->has($area)) {
throw new RenderInvalidArgumentException(\sprintf('Area "%s" is not supported.', $area));
} elseif (!\array_key_exists($format, $this->openApiRenderers)) {
throw new RenderInvalidArgumentException(\sprintf('Format "%s" is not supported.', $format));
}
/** @var OpenApi $spec */
$spec = $this->generatorLocator->get($area)->generate();
$tmpServers = $spec->servers;
try {
$spec->servers = $this->getServersFromOptions($spec, $options);
return $this->openApiRenderers[$format]->render($spec, $options);
} finally {
$spec->servers = $tmpServers; // Restore original value as we should not modify OpenApi object from the generator
}
}
@param array<string, mixed> $options
@throws \InvalidArgumentException If the area to dump is not valid
nelmio/NelmioApiDocBundle
src/Render/RenderOpenApi.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/RenderOpenApi.php
private function getServersFromOptions(OpenApi $spec, array $options)
{
if (\array_key_exists('server_url', $options)) {
return [new Server(['url' => $options['server_url'], '_context' => new Context()])];
}
if (Generator::UNDEFINED !== $spec->servers) {
return $spec->servers;
}
if (\array_key_exists('fallback_url', $options)) {
return [new Server(['url' => $options['fallback_url'], '_context' => new Context()])];
}
return Generator::UNDEFINED;
}
@param array<string, mixed> $options
@return Server[]|Generator::UNDEFINED
nelmio/NelmioApiDocBundle
src/Render/RenderOpenApi.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/RenderOpenApi.php
public function __construct($twig, array $htmlConfig)
{
if (!$twig instanceof \Twig_Environment && !$twig instanceof Environment) {
throw new \InvalidArgumentException(\sprintf('Providing an instance of "%s" as twig is not supported.', $twig::class));
}
$this->twig = $twig;
$this->htmlConfig = $htmlConfig;
}
@param Environment|\Twig_Environment $twig
@param array<string, mixed> $htmlConfig
nelmio/NelmioApiDocBundle
src/Render/Html/HtmlOpenApiRenderer.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/Html/HtmlOpenApiRenderer.php
private function getPattern(mixed $requirements): ?string
{
if (\is_array($requirements) && isset($requirements['rule'])) {
return (string) $requirements['rule'];
}
if (\is_string($requirements)) {
return $requirements;
}
if ($requirements instanceof Regex) {
return $requirements->getHtmlPattern();
}
return null;
}
@param mixed $requirements Value to retrieve a pattern from
nelmio/NelmioApiDocBundle
src/RouteDescriber/FosRestDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
private function getFormat(mixed $requirements): ?string
{
if ($requirements instanceof Constraint && !$requirements instanceof Regex) {
if ($requirements instanceof DateTime) {
// As defined per RFC3339
if (\DateTime::RFC3339 === $requirements->format || 'c' === $requirements->format) {
return 'date-time';
}
if ('Y-m-d' === $requirements->format) {
return 'date';
}
return null;
}
$reflectionClass = new \ReflectionClass($requirements);
return $reflectionClass->getShortName();
}
return null;
}
@param mixed $requirements Value to retrieve a format from
nelmio/NelmioApiDocBundle
src/RouteDescriber/FosRestDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
private function getEnum(mixed $requirements, \ReflectionMethod $reflectionMethod): ?array
{
if (!($requirements instanceof Choice)) {
return null;
}
if (null === $requirements->callback) {
return $requirements->choices;
}
if (\is_callable($choices = $requirements->callback)
|| \is_callable($choices = [$reflectionMethod->class, $requirements->callback])
) {
return $choices();
}
return null;
}
@param mixed $requirements Value to retrieve an enum from
@return mixed[]|null
nelmio/NelmioApiDocBundle
src/RouteDescriber/FosRestDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
private function getAttributes(\ReflectionMethod $reflection, string $className): array
{
$attributes = [];
foreach ($reflection->getAttributes($className, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
$attributes[] = $attribute->newInstance();
}
return $attributes;
}
@template T of object
@param class-string<T> $className
@return T[]
nelmio/NelmioApiDocBundle
src/RouteDescriber/FosRestDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
private function getRefParams(OA\OpenApi $api, OA\Operation $operation): array
{
/** @var OA\Parameter[] $globalParams */
$globalParams = Generator::UNDEFINED !== $api->components && Generator::UNDEFINED !== $api->components->parameters ? $api->components->parameters : [];
$globalParams = array_column($globalParams, null, 'parameter'); // update the indexes of the array with the reference names actually used
$existingParams = [];
$operationParameters = Generator::UNDEFINED !== $operation->parameters ? $operation->parameters : [];
/** @var OA\Parameter $parameter */
foreach ($operationParameters as $id => $parameter) {
$ref = $parameter->ref;
if (Generator::UNDEFINED === $ref) {
// we only concern ourselves with '$ref' parameters, so continue the loop
continue;
}
$ref = mb_substr($ref, 24); // trim the '#/components/parameters/' part of ref
if (!isset($globalParams[$ref])) {
// this shouldn't happen during proper configs, but in case of bad config, just ignore it here
continue;
}
$refParameter = $globalParams[$ref];
// param ids are in form {name}/{in}
$existingParams[\sprintf('%s/%s', $refParameter->name, $refParameter->in)] = $refParameter;
}
return $existingParams;
}
The '$ref' parameters need special handling, since their objects are missing 'name' and 'in'.
@return OA\Parameter[] existing $ref parameters
nelmio/NelmioApiDocBundle
src/RouteDescriber/RouteMetadataDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/RouteMetadataDescriber.php
private function getPossibleEnumValues(string $reqPattern): array
{
$requirements = [];
if (str_contains($reqPattern, '|')) {
$parts = explode('|', $reqPattern);
foreach ($parts as $part) {
if ('' === $part || 0 === preg_match(self::ALPHANUM_EXPANDED_REGEX, $part)) {
// we check a complex regex expression containing | - abort in that case
return [];
} else {
$requirements[] = $part;
}
}
}
return $requirements;
}
returns array of separated alphanumeric (including '-', '_') strings from a simple OR regex requirement pattern.
(routing parameters containing enums have already been resolved to that format at this time).
@param string $reqPattern a requirement pattern to match, e.g. 'a.html|b.html'
@return array<string>
nelmio/NelmioApiDocBundle
src/RouteDescriber/RouteMetadataDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/RouteMetadataDescriber.php
private function describeValidateFilter(?int $filter, int $flags, array $options): array
{
if (null === $filter) {
return [];
}
if (\FILTER_VALIDATE_BOOLEAN === $filter) {
return ['type' => 'boolean'];
}
if (\FILTER_VALIDATE_DOMAIN === $filter) {
return ['type' => 'string', 'format' => 'hostname'];
}
if (\FILTER_VALIDATE_EMAIL === $filter) {
return ['type' => 'string', 'format' => 'email'];
}
if (\FILTER_VALIDATE_FLOAT === $filter) {
return ['type' => 'number', 'format' => 'float'];
}
if (\FILTER_VALIDATE_INT === $filter) {
$props = [];
if (\array_key_exists('min_range', $options)) {
$props['minimum'] = $options['min_range'];
}
if (\array_key_exists('max_range', $options)) {
$props['maximum'] = $options['max_range'];
}
return ['type' => 'integer', ...$props];
}
if (\FILTER_VALIDATE_IP === $filter) {
$format = match ($flags) {
\FILTER_FLAG_IPV4 => 'ipv4',
\FILTER_FLAG_IPV6 => 'ipv6',
default => 'ip',
};
return ['type' => 'string', 'format' => $format];
}
if (\FILTER_VALIDATE_MAC === $filter) {
return ['type' => 'string', 'format' => 'mac'];
}
if (\FILTER_VALIDATE_REGEXP === $filter) {
return ['type' => 'string', 'pattern' => $this->getEcmaRegexpFromPCRE($options['regexp'])];
}
if (\FILTER_VALIDATE_URL === $filter) {
return ['type' => 'string', 'format' => 'uri'];
}
if (\FILTER_DEFAULT === $filter) {
return ['type' => 'string'];
}
return [];
}
@param mixed[] $options
@return array<string, mixed>
@see https://www.php.net/manual/en/filter.filters.validate.php
nelmio/NelmioApiDocBundle
src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php
private function getAttributesAsAnnotation($reflection, string $className): array
{
$annotations = [];
foreach ($reflection->getAttributes($className, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
$annotations[] = $attribute->newInstance();
}
return $annotations;
}
@param \ReflectionClass|\ReflectionMethod $reflection
@return Areas[]
getAttributesAsAnnotation
nelmio/NelmioApiDocBundle
src/Routing/FilteredRouteCollectionBuilder.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Routing/FilteredRouteCollectionBuilder.php
public function getReflectionMethod($controller): ?\ReflectionMethod
{
if (\is_string($controller)) {
$controller = $this->getClassAndMethod($controller);
}
if (null === $controller) {
return null;
}
return $this->getReflectionMethodByClassNameAndMethodName(...$controller);
}
Returns the ReflectionMethod for the given controller string.
@param string|array{string, string}|null $controller
nelmio/NelmioApiDocBundle
src/Util/ControllerReflector.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Util/ControllerReflector.php
#[DataProvider('provideAssetsMode')]
public function testHtml($htmlConfig, string $expectedHtml): void
{
$output = $this->executeDumpCommand([
'--area' => 'test',
'--format' => 'html',
'--html-config' => json_encode($htmlConfig),
]);
self::assertStringContainsString('<html>', $output);
self::assertStringContainsString('<body', $output);
self::assertStringContainsString('</body>', $output);
self::assertStringContainsString($expectedHtml, $output);
}
@param mixed $htmlConfig the value of the --html-config option
nelmio/NelmioApiDocBundle
tests/Command/DumpCommandTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Command/DumpCommandTest.php
#[DataProvider('provideCacheConfig')]
public function testApiDocGeneratorWithCachePool(array $config, array $expectedValues): void
{
$container = new ContainerBuilder();
$container->setParameter('kernel.bundles', []);
$extension = new NelmioApiDocExtension();
$extension->load([$config], $container);
$reference = $container->getDefinition('nelmio_api_doc.generator.default')->getArgument(2);
if (null === $expectedValues['defaultCachePool']) {
self::assertNull($reference);
} else {
self::assertInstanceOf(Reference::class, $reference);
self::assertSame($expectedValues['defaultCachePool'], (string) $reference);
}
$reference = $container->getDefinition('nelmio_api_doc.generator.area1')->getArgument(2);
if (null === $expectedValues['area1CachePool']) {
self::assertNull($reference);
} else {
self::assertInstanceOf(Reference::class, $reference);
self::assertSame($expectedValues['area1CachePool'], (string) $reference);
}
$cacheItemId = $container->getDefinition('nelmio_api_doc.generator.default')->getArgument(3);
self::assertSame($expectedValues['defaultCacheItemId'], $cacheItemId);
$cacheItemId = $container->getDefinition('nelmio_api_doc.generator.area1')->getArgument(3);
self::assertSame($expectedValues['area1CacheItemId'], $cacheItemId);
}
@param array<string, mixed> $config
@param array<string, mixed> $expectedValues
testApiDocGeneratorWithCachePool
nelmio/NelmioApiDocBundle
tests/DependencyInjection/NelmioApiDocExtensionTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/DependencyInjection/NelmioApiDocExtensionTest.php
#[DataProvider('provideOpenApiRendererWithHtmlConfig')]
public function testHtmlOpenApiRendererWithHtmlConfig(array $htmlConfig, array $expectedHtmlConfig): void
{
$container = new ContainerBuilder();
$container->setParameter('kernel.bundles', [
'TwigBundle' => TwigBundle::class,
]);
$extension = new NelmioApiDocExtension();
$extension->load([['html_config' => $htmlConfig]], $container);
$argument = $container->getDefinition('nelmio_api_doc.render_docs.html')->getArgument(1);
self::assertSame($expectedHtmlConfig, $argument);
}
@param array<string, mixed> $htmlConfig
@param array<string, mixed> $expectedHtmlConfig
testHtmlOpenApiRendererWithHtmlConfig
nelmio/NelmioApiDocBundle
tests/DependencyInjection/NelmioApiDocExtensionTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/DependencyInjection/NelmioApiDocExtensionTest.php
public function create(array $extraBundles, ?callable $routeConfiguration, array $extraConfigs, array $extraDefinitions): void
{
// clear cache directory for a fresh container
$filesystem = new Filesystem();
$filesystem->remove('var/cache/test');
$appKernel = new NelmioKernel($extraBundles, $routeConfiguration, $extraConfigs, $extraDefinitions);
$appKernel->boot();
$this->container = $appKernel->getContainer();
}
@param Bundle[] $extraBundles
@param array<string, array<mixed>> $extraConfigs Key is the extension name, value is the config
@param array<string, Definition> $extraDefinitions
nelmio/NelmioApiDocBundle
tests/Functional/ConfigurableContainerFactory.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/ConfigurableContainerFactory.php
#[DataProvider('provideTestCases')]
public function testControllers(?string $controller, ?string $fixtureSuffix = null, array $extraBundles = [], array $extraConfigs = [], array $extraDefinitions = [], ?\Closure $extraRoutes = null): void
{
$fixtureName = null !== $fixtureSuffix ? $controller.'.'.$fixtureSuffix : $controller;
$routingConfiguration = function (RoutingConfigurator &$routes) use ($controller, $extraRoutes) {
if (null !== $extraRoutes) {
($extraRoutes)($routes);
}
if (null === $controller) {
return;
}
$routes->withPath('/')->import(__DIR__."/Controller/$controller.php", 'attribute');
};
$this->configurableContainerFactory->create($extraBundles, $routingConfiguration, $extraConfigs, $extraDefinitions);
$apiDefinition = $this->getOpenApiDefinition();
// Create the fixture if it does not exist
if (!file_exists($fixtureDir = __DIR__.'/Fixtures/'.$fixtureName.'.json')) {
file_put_contents($fixtureDir, $apiDefinition->toJson());
}
self::assertSame(
self::getFixture($fixtureDir),
$this->getOpenApiDefinition()->toJson(),
);
}
@param Bundle[] $extraBundles
@param array<string, array<mixed>> $extraConfigs Key is the extension name, value is the config
@param array<string, Definition> $extraDefinitions
nelmio/NelmioApiDocBundle
tests/Functional/ControllerTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/ControllerTest.php
#[DataProvider('swaggerActionPathsProvider')]
public function testSwaggerAction(string $path): void
{
$operation = $this->getOperation($path, 'get');
$this->assertHasResponse('201', $operation);
$response = $this->getOperationResponse($operation, '201');
self::assertEquals('An example resource', $response->description);
}
Tests that the paths are automatically resolved in Swagger annotations.
nelmio/NelmioApiDocBundle
tests/Functional/FunctionalTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/FunctionalTest.php
public function testPrivateProtectedExposure(): void
{
// Ensure that groups are supported
$model = $this->getModel('PrivateProtectedExposure');
self::assertCount(1, $model->properties);
$this->assertHasProperty('publicField', $model);
$this->assertNotHasProperty('privateField', $model);
$this->assertNotHasProperty('protectedField', $model);
$this->assertNotHasProperty('protected', $model);
}
Related to https://github.com/nelmio/NelmioApiDocBundle/issues/1756
Ensures private/protected properties are not exposed, just like the symfony serializer does.
testPrivateProtectedExposure
nelmio/NelmioApiDocBundle
tests/Functional/FunctionalTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/FunctionalTest.php
public function __construct(
private array $extraBundles,
private ?\Closure $routeConfiguration,
private array $extraConfigs,
private array $extraDefinitions,
) {
parent::__construct('test', true);
}
@param Bundle[] $extraBundles
@param array<string, array<mixed>> $extraConfigs Key is the extension name, value is the config
@param array<string, Definition> $extraDefinitions
nelmio/NelmioApiDocBundle
tests/Functional/NelmioKernel.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/NelmioKernel.php
protected function getParameter(OA\AbstractAnnotation $annotation, string $name, string $in): OA\Parameter
{
$this->assertHasParameter($name, $in, $annotation);
$parameters = array_filter($annotation->parameters ?? [], function (OA\Parameter $parameter) use ($name, $in) {
return $parameter->name === $name && $parameter->in === $in;
});
return array_values($parameters)[0];
}
@param OA\Operation|OA\OpenApi $annotation
nelmio/NelmioApiDocBundle
tests/Functional/WebTestCase.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
public function assertHasParameter(string $name, string $in, OA\AbstractAnnotation $annotation): void
{
$parameters = array_filter(Generator::UNDEFINED !== $annotation->parameters ? $annotation->parameters : [], function (OA\Parameter $parameter) use ($name, $in) {
return $parameter->name === $name && $parameter->in === $in;
});
static::assertNotEmpty(
$parameters,
\sprintf('Failed asserting that parameter "%s" in "%s" does exist.', $name, $in)
);
}
@param OA\Operation|OA\OpenApi $annotation
nelmio/NelmioApiDocBundle
tests/Functional/WebTestCase.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
public function assertNotHasParameter(string $name, string $in, OA\AbstractAnnotation $annotation): void
{
$parameters = array_column(Generator::UNDEFINED !== $annotation->parameters ? $annotation->parameters : [], 'name', 'in');
static::assertNotContains(
$name,
$parameters[$in] ?? [],
\sprintf('Failed asserting that parameter "%s" in "%s" does not exist.', $name, $in)
);
}
@param OA\Operation|OA\OpenApi $annotation
nelmio/NelmioApiDocBundle
tests/Functional/WebTestCase.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
public function assertHasProperty(string $property, OA\AbstractAnnotation $annotation): void
{
$properties = array_column(Generator::UNDEFINED !== $annotation->properties ? $annotation->properties : [], 'property');
static::assertContains(
$property,
$properties,
\sprintf('Failed asserting that property "%s" does exist.', $property)
);
}
@param OA\Schema|OA\Property|OA\Items $annotation
nelmio/NelmioApiDocBundle
tests/Functional/WebTestCase.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
public function assertNotHasProperty(string $property, OA\AbstractAnnotation $annotation): void
{
$properties = array_column(Generator::UNDEFINED !== $annotation->properties ? $annotation->properties : [], 'property');
static::assertNotContains(
$property,
$properties,
\sprintf('Failed asserting that property "%s" does not exist.', $property)
);
}
@param OA\Schema|OA\Property|OA\Items $annotation
nelmio/NelmioApiDocBundle
tests/Functional/WebTestCase.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
#[Route('/deprecated', methods: ['GET'])]
public function deprecatedAction()
{
}
This action is deprecated.
Please do not use this action.
@deprecated
nelmio/NelmioApiDocBundle
tests/Functional/Controller/ApiController.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/ApiController.php
#[Route('/admin', methods: ['GET'])]
public function adminAction()
{
}
This action is not documented. It is excluded by the config.
nelmio/NelmioApiDocBundle
tests/Functional/Controller/ApiController.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/ApiController.php
#[Route('/undocumented', methods: ['GET'])]
public function undocumentedAction()
{
}
This path is excluded by the config (only /api allowed).
nelmio/NelmioApiDocBundle
tests/Functional/Controller/UndocumentedController.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/UndocumentedController.php
#[DataProvider('getNameAlternatives')]
public function testNameAliasingForObjects(string $expected, ?array $groups, array $alternativeNames): void
{
$registry = new ModelRegistry([], $this->createOpenApi(), $alternativeNames);
$type = new Type(Type::BUILTIN_TYPE_OBJECT, false, self::class);
self::assertEquals($expected, $registry->register(new Model($type, $groups)));
}
@param string[]|null $groups
@param array<string, mixed> $alternativeNames
testNameAliasingForObjects
nelmio/NelmioApiDocBundle
tests/Model/ModelRegistryTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Model/ModelRegistryTest.php
#[DataProvider('provideRangeConstraintDoesNotSetMinimumIfMinIsNotSet')]
public function testReaderWithValidationGroupsEnabledChecksForDefaultGroupWhenNoSerializationGroupsArePassed(object $entity): void
{
$schema = $this->createObj(OA\Schema::class, []);
$schema->merge([$this->createObj(OA\Property::class, ['property' => 'property1'])]);
$reader = new SymfonyConstraintAnnotationReader(true);
$reader->setSchema($schema);
// no serialization groups passed here
$reader->updateProperty(
new \ReflectionProperty($entity, 'property1'),
$schema->properties[0]
);
self::assertSame(10, $schema->properties[0]->maximum, 'should have read constraints in the default group');
}
re-using another provider here, since all constraints land in the default
group when `group={"someGroup"}` is not set.
testReaderWithValidationGroupsEnabledChecksForDefaultGroupWhenNoSerializationGroupsArePassed
nelmio/NelmioApiDocBundle
tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
private function createObj(string $className, array $props = []): object
{
return new $className($props + ['_context' => new Context()]);
}
@template T of OA\AbstractAnnotation
@param class-string<T> $className
@param array<string, mixed> $props
@return T
nelmio/NelmioApiDocBundle
tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
#[DataProvider('provideIndexedCollectionData')]
public function testSearchIndexedCollectionItem(array $setup, array $asserts): void
{
foreach ($asserts as $collection => $items) {
foreach ($items as $assert) {
$setupCollection = !isset($assert['components']) ?
($setup[$collection] ?? []) :
(Generator::UNDEFINED !== $setup['components']->{$collection} ? $setup['components']->{$collection} : []);
// get the indexing correct within haystack preparation
$properties = array_fill(0, \count($setupCollection), null);
// prepare the haystack array
foreach ($items as $assertItem) {
// e.g. $properties[1] = self::createObj(OA\PathItem::class, ['path' => 'path 1'])
$properties[$assertItem['index']] = self::createObj($assertItem['class'], [
$assertItem['key'] => $assertItem['value'],
]);
}
self::assertSame(
$assert['index'],
Util::searchIndexedCollectionItem($properties, $assert['key'], $assert['value']),
\sprintf('Failed to get the correct index for %s', print_r($assert, true))
);
}
}
}
@param array<mixed> $setup
@param array<mixed> $asserts
testSearchIndexedCollectionItem
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
#[DataProvider('provideIndexedCollectionData')]
public function testGetIndexedCollectionItem(array $setup, array $asserts): void
{
$parent = new $setup['class'](array_merge(
$this->getSetupPropertiesWithoutClass($setup),
['_context' => $this->rootContext]
));
foreach ($asserts as $collection => $items) {
foreach ($items as $assert) {
$itemParent = !isset($assert['components']) ? $parent : $parent->components;
self::assertTrue(is_a($assert['class'], OA\AbstractAnnotation::class, true), \sprintf('Invalid class %s', $assert['class']));
$child = Util::getIndexedCollectionItem(
$itemParent,
$assert['class'],
$assert['value']
);
self::assertInstanceOf($assert['class'], $child);
self::assertSame($child->{$assert['key']}, $assert['value']);
self::assertSame(
$itemParent->{$collection}[$assert['index']],
$child
);
$setupHaystack = !isset($assert['components']) ?
$setup[$collection] ?? [] :
$setup['components']->{$collection} ?? [];
// the children created within provider are not connected
if (!\in_array($child, $setupHaystack, true)) {
$this->assertIsNested($itemParent, $child);
$this->assertIsConnectedToRootContext($child);
}
}
}
}
@param array<mixed> $setup
@param array<mixed> $asserts
testGetIndexedCollectionItem
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
#[DataProvider('provideChildData')]
public function testGetChild(string $parent, array $parentProperties, array $children): void
{
$parent = new $parent([
...$parentProperties,
...['_context' => $this->rootContext],
]);
foreach ($children as $childClass => $childProperties) {
self::assertTrue(is_a($childClass, OA\AbstractAnnotation::class, true), \sprintf('Invalid class %s', $childClass));
$child = Util::createChild($parent, $childClass, $childProperties);
self::assertInstanceOf($childClass, $child);
self::assertEquals($childProperties, $this->getNonDefaultProperties($child));
}
}
@param array<string, array<mixed>> $parentProperties
@param array<class-string<OA\AbstractAnnotation>, array<mixed>> $children
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
#[DataProvider('provideInvalidChildData')]
public function testGetChildThrowsOnInvalidNestedProperty(string $parent, array $children): void
{
$parent = new $parent(['_context' => $this->rootContext]);
foreach ($children as $childClass => $childProperties) {
self::assertTrue(is_a($childClass, OA\AbstractAnnotation::class, true), \sprintf('Invalid class %s', $childClass));
self::expectException(\InvalidArgumentException::class);
self::expectExceptionMessage('Nesting attribute properties is not supported, only nest classes.');
Util::createChild($parent, $childClass, $childProperties);
}
}
@param array<class-string<OA\AbstractAnnotation>, array<mixed>> $children
testGetChildThrowsOnInvalidNestedProperty
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
#[DataProvider('provideMergeData')]
public function testMerge(array $setup, $merge, array $assert): void
{
$api = self::createObj(OA\OpenApi::class, $setup + ['_context' => new Context()]);
Util::merge($api, $merge, false);
self::assertTrue($api->validate());
$actual = json_decode(json_encode($api), true);
self::assertEquals($assert, $actual);
}
@param array<mixed> $setup
@param array<mixed>|\ArrayObject $merge
@param array<mixed> $assert
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
private function getSetupPropertiesWithoutClass(array $setup): array
{
return array_filter($setup, function ($k) {return 'class' !== $k; }, \ARRAY_FILTER_USE_KEY);
}
@param array<mixed> $setup
@return array<mixed>
getSetupPropertiesWithoutClass
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
private static function createObj(string $className, array $props = []): object
{
return new $className($props + ['_context' => new Context()]);
}
@param class-string<OA\AbstractAnnotation> $className
@param array<string, mixed> $props
nelmio/NelmioApiDocBundle
tests/SwaggerPhp/UtilTest.php
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
public function __construct(array $routes = [], string $basePath = '', array $matchTypes = [])
{
$this->addRoutes($routes);
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
}
Create router in one call from config.
@param array $routes
@param string $basePath
@param array $matchTypes
@throws Exception
dannyvankooten/AltoRouter
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
public function getRoutes(): array
{
return $this->routes;
}
Retrieves all routes.
Useful if you want to process or display routes.
@return array All routes.
dannyvankooten/AltoRouter
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
public function addRoutes($routes)
{
if (!is_array($routes) && !$routes instanceof Traversable) {
throw new RuntimeException('Routes should be an array or an instance of Traversable');
}
foreach ($routes as $route) {
call_user_func_array([$this, 'map'], $route);
}
}
Add multiple routes at once from array in the following format:
$routes = [
[$method, $route, $target, $name]
];
@param array $routes
@return void
@author Koen Punt
@throws Exception
dannyvankooten/AltoRouter
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
public function setBasePath(string $basePath)
{
$this->basePath = $basePath;
}
Set the base path.
Useful if you are running your application from a subdirectory.
@param string $basePath
dannyvankooten/AltoRouter
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
Saved Queries
Top Community Queries
No community queries yet
The top public SQL queries from the community will appear here once available.