Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions src/AnnotationGenerator/DoctrineMongoDBAnnotationGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

/*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace ApiPlatform\SchemaGenerator\AnnotationGenerator;

use ApiPlatform\SchemaGenerator\CardinalitiesExtractor;
use ApiPlatform\SchemaGenerator\TypesGenerator;

/**
* Doctrine MongoDB annotation generator.
*
* @author Andrew Meshchanchuk <andrew.meshchanchuk@gmail.com>>
*/
class DoctrineMongoDBAnnotationGenerator extends AbstractAnnotationGenerator
{
/**
* {@inheritdoc}
*/
public function generateClassAnnotations($className)
{
$class = $this->classes[$className];

if ($class['isEnum']) {
return [];
}

if (isset($this->config['types'][$class['resource']->localName()]['doctrine']['inheritanceMapping'])) {
$inheritanceMapping = $this->config['types'][$class['resource']->localName()]['doctrine']['inheritanceMapping'];
} else {
$inheritanceMapping = $class['abstract'] ? '@MongoDB\MappedSuperclass' : '@MongoDB\Document';
}

return [
'',
$inheritanceMapping,
];
}

/**
* {@inheritdoc}
*/
public function generateFieldAnnotations($className, $fieldName)
{
$this->classes[$className];
$field = $this->classes[$className]['fields'][$fieldName];

$annotations = [];

if ($field['isEnum']) {
if ($field['isArray']) {
$type = 'simple_array';
} else {
$type = 'string';
}
} else {
switch ($field['range']) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can probably extract some parts of these method to other ones to make the code a bit more readable

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have idea, how do it. Can you help me?

case 'Boolean':
$type = 'boolean';
break;
case 'Date':
// No break
case 'DateTime':
$type = 'date';
break;
case 'Time':
$type = 'time';
break;
case 'Number':
// No break
case 'Float':
$type = 'float';
break;
case 'Integer':
$type = 'integer';
break;
case 'Text':
// No break
case 'URL':
$type = 'string';
break;
}
}

if (isset($type)) {
if (!$field['isId']) {
$annotation = '@MongoDB\Field';

if ($field['isArray']) {
$type = 'collection';
}

$annotation .= sprintf('(type="%s")', $type);

$annotations[] = $annotation;
}
} else {
if ($field['cardinality'] === CardinalitiesExtractor::CARDINALITY_0_1
|| $field['cardinality'] === CardinalitiesExtractor::CARDINALITY_1_1
|| $field['cardinality'] === CardinalitiesExtractor::CARDINALITY_N_0
|| $field['cardinality'] === CardinalitiesExtractor::CARDINALITY_N_1) {
$annotations[] = sprintf('@MongoDB\ReferenceOne(targetDocument="%s", simple=true))', $this->getRelationName($field['range']));
} elseif ($field['cardinality'] === CardinalitiesExtractor::CARDINALITY_0_N
|| $field['cardinality'] === CardinalitiesExtractor::CARDINALITY_1_N
|| $field['cardinality'] === CardinalitiesExtractor::CARDINALITY_N_N) {
$annotations[] = sprintf('@MongoDB\ReferenceMany(targetDocument="%s", simple=true)', $this->getRelationName($field['range']));
}
}

if ($field['isId']) {
$annotations[] = '@MongoDB\Id';
}

return $annotations;
}

/**
* {@inheritdoc}
*/
public function generateUses($className)
{
$resource = $this->classes[$className]['resource'];

$subClassOf = $resource->get('rdfs:subClassOf');
$typeIsEnum = $subClassOf && $subClassOf->getUri() === TypesGenerator::SCHEMA_ORG_ENUMERATION;

return $typeIsEnum ? [] : ['Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB'];
}

/**
* Gets class or interface name to use in relations.
*
* @param string $range
*
* @return string
*/
private function getRelationName($range)
{
$class = $this->classes[$range];

if (isset($class['interfaceName'])) {
return $class['interfaceName'];
}

return $class['name'];
}
}
47 changes: 47 additions & 0 deletions tests/config/mongodb/address-book.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# The PHP namespace of generated entities
namespaces:
entity: 'AddressBook\Document'
# Enable DunglasApiAnnotationGenerator
annotationGenerators:
- ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGenerator
- ApiPlatform\SchemaGenerator\AnnotationGenerator\DoctrineMongoDBAnnotationGenerator
- ApiPlatform\SchemaGenerator\AnnotationGenerator\ConstraintAnnotationGenerator
- ApiPlatform\SchemaGenerator\AnnotationGenerator\DunglasApiAnnotationGenerator
# The list of types and properties we want to use
types:
Person:
parent: false
properties:
name: ~
familyName: ~
givenName: ~
additionalName: ~
gender: ~
address: { range: PostalAddress }
birthDate: ~
telephone: ~
email: ~
jobTitle: ~
# Default relation table name would be "person_organization" for all following fields, but we customize them
affiliation: ~
brand: { relationTableName: "person_brand"}
memberOf: { range: "Organization", cardinality: (1..*), relationTableName: "person_memberof"}
worksFor: { range: "Organization", cardinality: (0..*), relationTableName: "person_worksfor"}
# url field is a custom one without definition, it should render error
url: ~
friends: { range: "Person", cardinality: (0..*) }
PostalAddress:
# Disable the generation of the class hierarchy for this type
parent: false
properties:
# Force the type of the addressCountry property to text
addressCountry: { range: "Text" }
addressLocality: ~
addressRegion: ~
postOfficeBoxNumber: ~
postalCode: ~
streetAddress: ~
Organization:
parent: false
properties:
name: ~
94 changes: 94 additions & 0 deletions tests/config/mongodb/ecommerce.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
header: |
/*
* This file is part of the Ecommerce package.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
rdfa:
-
uri: tests/data/schema.rdfa
format: rdfa
relations:
- tests/data/v1.owl
namespaces:
entity: 'Dunglas\EcommerceBundle\Document'
enum: 'Dunglas\EcommerceBundle\Enum'
interface: 'Dunglas\EcommerceBundle\Model'
annotationGenerators:
- ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGenerator
- ApiPlatform\SchemaGenerator\AnnotationGenerator\ConstraintAnnotationGenerator
- ApiPlatform\SchemaGenerator\AnnotationGenerator\DoctrineMongoDBAnnotationGenerator
author: "Kévin Dunglas <dunglas@gmail.com>"
debug: true
useInterface: true
checkIsGoodRelations: true
types:
Thing:
properties:
name: ~
description: ~
image: { range: ImageObject }
additionalType: ~
Product:
properties:
sku:
cardinality: "(0..1)"
url: ~
brand: ~
productID: ~
releaseDate: ~
offers: ~
itemCondition: ~
gtin13: ~
gtin14: ~
gtin8: ~
mpn: ~
color: ~
depth: { range: "Text" }
height: { range: "Text" }
weight: { range: "Text" }
width: { range: "Text" }
seller: { range: "Seller" }
Brand:
parent: "Thing"
properties:
logo: { range: "ImageObject" }
Seller:
parent: false
guessFrom: Person
properties:
name: ~
birthDate: ~
ImageObject:
parent: Thing
properties:
caption: ~
ProductModel:
properties:
isVariantOf: ~
Offer:
parent: Thing
properties:
acceptedPaymentMethod: ~
availability: ~
availabilityStarts: ~
availabilityEnds: ~
availableDeliveryMethod: ~
category: { range: "Text" }
deliveryLeadTime: ~
inventoryLevel: ~
itemCondition: ~
price: { range: Number }
priceCurrency: ~
validFrom: ~
validThrough: ~
DeliveryChargeSpecification: { parent: false }
PaymentChargeSpecification: { parent: false }
OfferItemCondition: ~
PaymentMethod: ~
ItemAvailability: ~
DeliveryMethod: ~
QuantitativeValue: { parent: false }
4 changes: 4 additions & 0 deletions tests/run-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ bin/schema generate-types build/address-book/ tests/config/address-book.yml
bin/schema generate-types build/ecommerce/ tests/config/ecommerce.yml
bin/schema generate-types build/vgo/ tests/config/vgo.yml

mkdir -p build/mongodb/ecommerce/ build/mongodb/address-book/
bin/schema generate-types build/mongodb/address-book/ tests/config/mongodb/address-book.yml
bin/schema generate-types build/mongodb/ecommerce/ tests/config/mongodb/ecommerce.yml

# Check code CS
vendor/bin/php-cs-fixer --dry-run --diff -vvv fix src/

Expand Down