NelmioApiDocBundle/Parser/JmsMetadataParser.php
Bez Hermoso 14d1021c8b Unified data types [actualType and subType]
This is the result of https://github.com/nelmio/NelmioApiDocBundle/issues/410.

This PR aims to provide a uniform way of declaring data-types of parameters for
parsers and handlers to follow. In turn, this would allow formatters to
determine data-types in a cleaner and less volatile manner. (See use-case that
can be improved with this PR:
https://github.com/nelmio/NelmioApiDocBundle/blob/master/Formatter/AbstractFormatter.php#L103)

This is possible by the addition two properties to each property item in
`response`, and `parameters` fields in each API endpoint produced by the
`ApiDocExtractor`:

* `actualType` Contains a value from one of the `DataTypes` class constants.

* `subType` Can contain either `null`, or any other `DataTypes` class constant.
This is relevant when the `actualType` is a `DataTypes::COLLECTION`, wherein
`subType` would specify the type of the collection items. It is also relevant
when `actualType` is a `DataTypes::MODEL`, wherein `subType` would contain an
identifier of the model (the FQCN or anything the parser would wish to specify)

Examples:

```php

array(
    'id' => array(
        'dataType' => 'integer',
        'actualType' => DataTypes::INTEGER,
        'subType' => null,
    ),
    'profile' => array(
        'dataType' => 'object (Profile)',
        'actualType' => DataTypes::MODEL,
        'subType' => 'Foo\Entity\Profile',
        'children' => array(
            'name' => array(
                'dataType' => 'string',
                'actualType' => DataTypes::STRING,
                'subType' => null,
             ),
            'birthDate' => array(
                'dataType' => 'date',
                'actualType' => DataTypes::DATE,
                'subType' => null,
            ),
        )
    ),
    'languages' => array(
        'dataType' => 'array of strings',
        'actualType' => DataTypes::COLLECTION,
        'subType' => DataTypes::STRING,
    ),
    'roles' => array(
        'dataType' => 'array of choices',
        'actualType' => DataTypes::COLLECTION,
        'subType' => DataTypes::ENUM,
    ),
    'groups' => array(
        'dataType' => 'array of objects (Group)',
        'actualType' => DataTypes::COLLECTION,
        'subType' => 'Foo\Entity\Group',
    ),
    'profileRevisions' => array(
         'dataType' => 'array of objects (Profile)',
         'actualType' => DataTypes::COLLECTION,
         'subType' => 'Foo\Entity\Profile',
    ),
    'address' => array(
        'dataType' => 'object (a_type_a_custom_JMS_serializer_handler_handles)',
        'actualType' => DataTypes::MODEL,
        'subType' => 'a_type_a_custom_JMS_serializer_handler_handles',
    ),
);
```

When a formatter omits the `dataType` property or leaves it blank, it is
inferred within `ApiDocExtractor` before everything is passed to formatters.
2014-06-25 09:05:48 +02:00

266 lines
8.6 KiB
PHP

<?php
/*
* This file is part of the NelmioApiDocBundle.
*
* (c) Nelmio <hello@nelm.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nelmio\ApiDocBundle\Parser;
use JMS\Serializer\Exclusion\GroupsExclusionStrategy;
use JMS\Serializer\SerializationContext;
use Metadata\MetadataFactoryInterface;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Util\DocCommentExtractor;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Metadata\VirtualPropertyMetadata;
use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
/**
* Uses the JMS metadata factory to extract input/output model information
*/
class JmsMetadataParser implements ParserInterface
{
/**
* @var \Metadata\MetadataFactoryInterface
*/
private $factory;
/**
* @var PropertyNamingStrategyInterface
*/
private $namingStrategy;
/**
* @var \Nelmio\ApiDocBundle\Util\DocCommentExtractor
*/
private $commentExtractor;
private $typeMap = array(
'integer' => DataTypes::INTEGER,
'boolean' => DataTypes::BOOLEAN,
'string' => DataTypes::STRING,
'float' => DataTypes::FLOAT,
'double' => DataTypes::FLOAT,
'array' => DataTypes::COLLECTION,
'DateTime' => DataTypes::DATETIME,
);
/**
* Constructor, requires JMS Metadata factory
*/
public function __construct(
MetadataFactoryInterface $factory,
PropertyNamingStrategyInterface $namingStrategy,
DocCommentExtractor $commentExtractor
) {
$this->factory = $factory;
$this->namingStrategy = $namingStrategy;
$this->commentExtractor = $commentExtractor;
}
/**
* {@inheritdoc}
*/
public function supports(array $input)
{
$className = $input['class'];
try {
if ($meta = $this->factory->getMetadataForClass($className)) {
return true;
}
} catch (\ReflectionException $e) {
}
return false;
}
/**
* {@inheritdoc}
*/
public function parse(array $input)
{
$className = $input['class'];
$groups = $input['groups'];
return $this->doParse($className, array(), $groups);
}
/**
* Recursively parse all metadata for a class
*
* @param string $className Class to get all metadata for
* @param array $visited Classes we've already visited to prevent infinite recursion.
* @param array $groups Serialization groups to include.
* @return array metadata for given class
* @throws \InvalidArgumentException
*/
protected function doParse($className, $visited = array(), array $groups = array())
{
$meta = $this->factory->getMetadataForClass($className);
if (null === $meta) {
throw new \InvalidArgumentException(sprintf("No metadata found for class %s", $className));
}
$exclusionStrategies = array();
if ($groups) {
$exclusionStrategies[] = new GroupsExclusionStrategy($groups);
}
$params = array();
// iterate over property metadata
foreach ($meta->propertyMetadata as $item) {
if (!is_null($item->type)) {
$name = $this->namingStrategy->translateName($item);
$dataType = $this->processDataType($item);
// apply exclusion strategies
foreach ($exclusionStrategies as $strategy) {
if (true === $strategy->shouldSkipProperty($item, SerializationContext::create())) {
continue 2;
}
}
$params[$name] = array(
'dataType' => $dataType['normalized'],
'actualType' => $dataType['actualType'],
'subType' => $dataType['class'],
'required' => false,
//TODO: can't think of a good way to specify this one, JMS doesn't have a setting for this
'description' => $this->getDescription($item),
'readonly' => $item->readOnly,
'sinceVersion' => $item->sinceVersion,
'untilVersion' => $item->untilVersion,
);
if (!is_null($dataType['class']) && false === $dataType['primitive']) {
$params[$name]['class'] = $dataType['class'];
}
// if class already parsed, continue, to avoid infinite recursion
if (in_array($dataType['class'], $visited)) {
continue;
}
// check for nested classes with JMS metadata
if ($dataType['class'] && false === $dataType['primitive'] && null !== $this->factory->getMetadataForClass($dataType['class'])) {
$visited[] = $dataType['class'];
$params[$name]['children'] = $this->doParse($dataType['class'], $visited, $groups);
}
}
}
return $params;
}
/**
* Figure out a normalized data type (for documentation), and get a
* nested class name, if available.
*
* @param PropertyMetadata $type
* @return array
*/
protected function processDataType(PropertyMetadata $item)
{
// check for a type inside something that could be treated as an array
if ($nestedType = $this->getNestedTypeInArray($item)) {
if ($this->isPrimitive($nestedType)) {
return array(
'normalized' => sprintf("array of %ss", $nestedType),
'actualType' => DataTypes::COLLECTION,
'class' => $this->typeMap[$nestedType],
'primitive' => true,
);
}
$exp = explode("\\", $nestedType);
return array(
'normalized' => sprintf("array of objects (%s)", end($exp)),
'actualType' => DataTypes::COLLECTION,
'class' => $nestedType,
'primitive' => false,
);
}
$type = $item->type['name'];
// could be basic type
if ($this->isPrimitive($type)) {
return array(
'normalized' => $type,
'actualType' => $this->typeMap[$type],
'class' => null,
'primitive' => true,
);
}
// we can use type property also for custom handlers, then we don't have here real class name
if (!class_exists($type)) {
return array(
'normalized' => sprintf("custom handler result for (%s)", $type),
'class' => $type,
'actualType' => DataTypes::MODEL,
'primitive' => false,
);
}
// if we got this far, it's a general class name
$exp = explode("\\", $type);
return array(
'normalized' => sprintf("object (%s)", end($exp)),
'class' => $type,
'actualType' => DataTypes::MODEL,
'primitive' => false,
);
}
protected function isPrimitive($type)
{
return in_array($type, array('boolean', 'integer', 'string', 'float', 'double', 'array', 'DateTime'));
}
/**
* Check the various ways JMS describes values in arrays, and
* get the value type in the array
*
* @param PropertyMetadata $item
* @return string|null
*/
protected function getNestedTypeInArray(PropertyMetadata $item)
{
if (isset($item->type['name']) && in_array($item->type['name'], array('array', 'ArrayCollection'))) {
if (isset($item->type['params'][1]['name'])) {
// E.g. array<string, MyNamespaceMyObject>
return $item->type['params'][1]['name'];
}
if (isset($item->type['params'][0]['name'])) {
// E.g. array<MyNamespaceMyObject>
return $item->type['params'][0]['name'];
}
}
return null;
}
protected function getDescription(PropertyMetadata $item)
{
$ref = new \ReflectionClass($item->class);
if ($item instanceof VirtualPropertyMetadata) {
$extracted = $this->commentExtractor->getDocCommentText($ref->getMethod($item->getter));
} else {
$extracted = $this->commentExtractor->getDocCommentText($ref->getProperty($item->name));
}
return $extracted;
}
}