NelmioApiDocBundle/Parser/DunglasJsonLdApiParser.php

97 lines
2.9 KiB
PHP
Raw Normal View History

2015-03-15 23:48:57 +01:00
<?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;
2015-04-07 22:21:36 +02:00
use Dunglas\JsonLdApiBundle\JsonLd\ResourceCollectionInterface;
use Dunglas\JsonLdApiBundle\JsonLd\ResourceInterface;
2015-03-15 23:48:57 +01:00
use Dunglas\JsonLdApiBundle\Mapping\ClassMetadataFactory;
use Nelmio\ApiDocBundle\DataTypes;
/**
* Use DunglasJsonLdApi to extract input and output information.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class DunglasJsonLdApiParser implements ParserInterface
{
/**
2015-04-07 22:21:36 +02:00
* @var ResourceCollectionInterface
2015-03-15 23:48:57 +01:00
*/
2015-04-07 22:21:36 +02:00
private $resourceCollection;
2015-03-15 23:48:57 +01:00
/**
* @var ClassMetadataFactory
*/
private $classMetadataFactory;
2015-04-07 22:21:36 +02:00
public function __construct(ResourceCollectionInterface $resourceCollection, ClassMetadataFactory $classMetadataFactory)
2015-03-15 23:48:57 +01:00
{
2015-04-07 22:21:36 +02:00
$this->resourceCollection = $resourceCollection;
2015-03-15 23:48:57 +01:00
$this->classMetadataFactory = $classMetadataFactory;
}
/**
* {@inheritdoc}
*/
public function supports(array $item)
{
2015-04-07 22:21:36 +02:00
return null !== $this->resourceCollection->getResourceForEntity($item['class']);
2015-03-15 23:48:57 +01:00
}
/**
* {@inheritdoc}
*/
public function parse(array $item)
{
/**
2015-04-07 22:21:36 +02:00
* @var $resource ResourceInterface
2015-03-15 23:48:57 +01:00
*/
2015-04-07 22:21:36 +02:00
$resource = $this->resourceCollection->getResourceForEntity($item['class']);
2015-03-15 23:48:57 +01:00
$classMetadata = $this->classMetadataFactory->getMetadataFor(
$resource->getEntityClass(),
$resource->getNormalizationGroups(),
$resource->getDenormalizationGroups(),
$resource->getValidationGroups()
);
$data = array();
foreach ($classMetadata->getAttributes() as $attribute) {
$data[$attribute->getName()] = [
'required' => $attribute->isRequired(),
'description' => $attribute->getDescription(),
'readonly' => $attribute->isReadable() && !$attribute->isWritable(),
'class' => $resource->getEntityClass(),
];
if (isset($attribute->getTypes()[0])) {
$type = $attribute->getTypes()[0];
if ($type->isCollection()) {
$dataType = DataTypes::COLLECTION;
} elseif ('object' === $type->getType()) {
if ('DateTime' === $type->getClass()) {
$dataType = DataTypes::DATETIME;
} else {
$dataType = DataTypes::STRING;
}
} else {
$dataType = $type->getType();
}
$data[$attribute->getName()]['dataType'] = $dataType;
2015-04-07 22:21:36 +02:00
} else {
$data[$attribute->getName()]['dataType'] = DataTypes::STRING;
2015-03-15 23:48:57 +01:00
}
}
return $data;
}
}