code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
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
|
isBooleansArray
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/FormModelDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/FormModelDescriber.php
|
MIT
|
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
|
computeGroups
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/JMSModelDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/JMSModelDescriber.php
|
MIT
|
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
|
describeItem
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/JMSModelDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/JMSModelDescriber.php
|
MIT
|
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
|
getNestedTypeInArray
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/JMSModelDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/JMSModelDescriber.php
|
MIT
|
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
|
__construct
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/ObjectModelDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/ObjectModelDescriber.php
|
MIT
|
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.
|
markRequiredProperties
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/ObjectModelDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/ObjectModelDescriber.php
|
MIT
|
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
|
updateProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/AnnotationsReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/AnnotationsReader.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/AnnotationsReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/AnnotationsReader.php
|
MIT
|
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
|
updateProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
|
MIT
|
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
|
getAttribute
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/OpenApiAnnotationsReader.php
|
MIT
|
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
|
updateProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/PropertyPhpDocReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/PropertyPhpDocReader.php
|
MIT
|
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
|
updateProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/ReflectionReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/ReflectionReader.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/ReflectionReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/ReflectionReader.php
|
MIT
|
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
|
updateProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
MIT
|
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.
|
appendPattern
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
MIT
|
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>
|
getAttributes
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
MIT
|
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>
|
locateAttributes
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
MIT
|
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
|
isConstraintInGroup
|
php
|
nelmio/NelmioApiDocBundle
|
src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php
|
MIT
|
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
|
getGroups
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/ModelRegister.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/ModelRegister.php
|
MIT
|
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
|
getPath
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getTag
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getSchema
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getOperation
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getOperationParameter
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getChild
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getCollectionItem
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
getIndexedCollectionItem
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
searchCollectionItem
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
createCollectionItem
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
createChild
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
createContext
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
createWeakContext
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
merge
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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.
|
getSchemaPropertyName
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
mergeChild
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
mergeCollection
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
mergeTyped
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
mergeProperty
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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>>
|
getNestingIndexes
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
modifyAnnotationValue
|
php
|
nelmio/NelmioApiDocBundle
|
src/OpenApiPhp/Util.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/OpenApiPhp/Util.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/ArrayPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/ArrayPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/BooleanPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/BooleanPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/CompoundPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/CompoundPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/DateTimePropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/DateTimePropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/DictionaryPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/DictionaryPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/FloatPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/FloatPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/IntegerPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/IntegerPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/NullablePropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/NullablePropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/ObjectPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/ObjectPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/PropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/PropertyDescriber.php
|
MIT
|
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
|
getPropertyDescriber
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/PropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/PropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/StringPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/StringPropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/TranslatablePropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/TranslatablePropertyDescriber.php
|
MIT
|
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
|
describe
|
php
|
nelmio/NelmioApiDocBundle
|
src/PropertyDescriber/UuidPropertyDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/PropertyDescriber/UuidPropertyDescriber.php
|
MIT
|
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
|
renderFromRequest
|
php
|
nelmio/NelmioApiDocBundle
|
src/Render/RenderOpenApi.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/RenderOpenApi.php
|
MIT
|
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
|
render
|
php
|
nelmio/NelmioApiDocBundle
|
src/Render/RenderOpenApi.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/RenderOpenApi.php
|
MIT
|
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
|
getServersFromOptions
|
php
|
nelmio/NelmioApiDocBundle
|
src/Render/RenderOpenApi.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/RenderOpenApi.php
|
MIT
|
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
|
__construct
|
php
|
nelmio/NelmioApiDocBundle
|
src/Render/Html/HtmlOpenApiRenderer.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Render/Html/HtmlOpenApiRenderer.php
|
MIT
|
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
|
getPattern
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/FosRestDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
|
MIT
|
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
|
getFormat
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/FosRestDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
|
MIT
|
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
|
getEnum
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/FosRestDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
|
MIT
|
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[]
|
getAttributes
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/FosRestDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/FosRestDescriber.php
|
MIT
|
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
|
getRefParams
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/RouteMetadataDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/RouteMetadataDescriber.php
|
MIT
|
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>
|
getPossibleEnumValues
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/RouteMetadataDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/RouteMetadataDescriber.php
|
MIT
|
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
|
describeValidateFilter
|
php
|
nelmio/NelmioApiDocBundle
|
src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
src/Routing/FilteredRouteCollectionBuilder.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Routing/FilteredRouteCollectionBuilder.php
|
MIT
|
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
|
getReflectionMethod
|
php
|
nelmio/NelmioApiDocBundle
|
src/Util/ControllerReflector.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/src/Util/ControllerReflector.php
|
MIT
|
#[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
|
testHtml
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Command/DumpCommandTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Command/DumpCommandTest.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/DependencyInjection/NelmioApiDocExtensionTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/DependencyInjection/NelmioApiDocExtensionTest.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/DependencyInjection/NelmioApiDocExtensionTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/DependencyInjection/NelmioApiDocExtensionTest.php
|
MIT
|
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
|
create
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/ConfigurableContainerFactory.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/ConfigurableContainerFactory.php
|
MIT
|
#[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
|
testControllers
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/ControllerTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/ControllerTest.php
|
MIT
|
#[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.
|
testSwaggerAction
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/FunctionalTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/FunctionalTest.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/FunctionalTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/FunctionalTest.php
|
MIT
|
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
|
__construct
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/NelmioKernel.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/NelmioKernel.php
|
MIT
|
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
|
getParameter
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/WebTestCase.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
|
MIT
|
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
|
assertHasParameter
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/WebTestCase.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
|
MIT
|
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
|
assertNotHasParameter
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/WebTestCase.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
|
MIT
|
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
|
assertHasProperty
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/WebTestCase.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
|
MIT
|
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
|
assertNotHasProperty
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/WebTestCase.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/WebTestCase.php
|
MIT
|
#[Route('/deprecated', methods: ['GET'])]
public function deprecatedAction()
{
}
|
This action is deprecated.
Please do not use this action.
@deprecated
|
deprecatedAction
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/Controller/ApiController.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/ApiController.php
|
MIT
|
#[Route('/admin', methods: ['GET'])]
public function adminAction()
{
}
|
This action is not documented. It is excluded by the config.
|
adminAction
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/Controller/ApiController.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/ApiController.php
|
MIT
|
#[Route('/undocumented', methods: ['GET'])]
public function undocumentedAction()
{
}
|
This path is excluded by the config (only /api allowed).
|
undocumentedAction
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Functional/Controller/UndocumentedController.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Functional/Controller/UndocumentedController.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/Model/ModelRegistryTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/Model/ModelRegistryTest.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
|
MIT
|
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
|
createObj
|
php
|
nelmio/NelmioApiDocBundle
|
tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
#[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
|
testGetChild
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
#[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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
#[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
|
testMerge
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
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
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
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
|
createObj
|
php
|
nelmio/NelmioApiDocBundle
|
tests/SwaggerPhp/UtilTest.php
|
https://github.com/nelmio/NelmioApiDocBundle/blob/master/tests/SwaggerPhp/UtilTest.php
|
MIT
|
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
|
__construct
|
php
|
dannyvankooten/AltoRouter
|
AltoRouter.php
|
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
|
MIT
|
public function getRoutes(): array
{
return $this->routes;
}
|
Retrieves all routes.
Useful if you want to process or display routes.
@return array All routes.
|
getRoutes
|
php
|
dannyvankooten/AltoRouter
|
AltoRouter.php
|
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
|
MIT
|
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
|
addRoutes
|
php
|
dannyvankooten/AltoRouter
|
AltoRouter.php
|
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
|
MIT
|
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
|
setBasePath
|
php
|
dannyvankooten/AltoRouter
|
AltoRouter.php
|
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.