Skip to content

alwaysIdentifier annotation option implementation #1528

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 15, 2018
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
20 changes: 20 additions & 0 deletions features/bootstrap/FeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

declare(strict_types=1);

use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\AlwaysIdentifierDummy;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Answer;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\CompositeItem;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\CompositeLabel;
Expand Down Expand Up @@ -838,4 +839,23 @@ public function thereAreDummyDateObjectsWithDummyDate(int $nb)

$this->manager->flush();
}

/**
* @Given there are AlwaysIdentifierDummies
*/
public function thereAreAlwaysIdentifierDummies()
{
$mainDummy = new AlwaysIdentifierDummy();
$relatedDummy = new AlwaysIdentifierDummy();

$this->manager->persist($relatedDummy);

$mainDummy->setParent($relatedDummy);
$mainDummy->setChildren([$relatedDummy]);
$mainDummy->setRelated([$relatedDummy]);

$this->manager->persist($mainDummy);

$this->manager->flush();
}
}
52 changes: 52 additions & 0 deletions features/hal/always_identifier.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
Feature: allow resources in properties to always be serialized as identifiers
In order to use a hypermedia API
As a client software developer
I need to be able to force to serialize only the identifier of the related resource

@createSchema
@dropSchema
Scenario: Create a set of Dummy with the alwaysIdentifier attributes and check the HAL formatted response
Given there are AlwaysIdentifierDummies
When I add "Accept" header equal to "application/hal+json"
And I add "Content-Type" header equal to "application/hal+json"
And I send a "GET" request to "/always_identifier_dummies/2"
Then the JSON should be equal to:
"""
{
"_links": {
"self": {
"href": "/always_identifier_dummies/2"
},
"children": [
{
"href": "/always_identifier_dummies/1"
}
],
"related": [
{
"href": "/always_identifier_dummies/1"
}
],
"parent": {
"href": "/always_identifier_dummies/1"
}
},
"_embedded": {
"children": [
"/always_identifier_dummies/1"
],
"related": [
{
"_links": {
"self": {
"href": "/always_identifier_dummies/1"
}
}
}
],
"parent": "/always_identifier_dummies/1"
}
}
"""


28 changes: 28 additions & 0 deletions features/json/always_identifier.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Feature: allow resources in properties to always be serialized as identifiers
In order to use a hypermedia API
As a client software developer
I need to be able to force to serialize only the identifier of the related resource

@createSchema
@dropSchema
Scenario: Create a set of Dummy with the alwaysIdentifier attributes and check the JSON formatted response
Given there are AlwaysIdentifierDummies
When I add "Accept" header equal to "application/json"
And I add "Content-Type" header equal to "application/json"
And I send a "GET" request to "/always_identifier_dummies/2"
Then the JSON should be equal to:
"""
{
"children": [
"/always_identifier_dummies/1"
],
"related": [
{
"children": [],
"related": [],
"parent": null
}
],
"parent": "/always_identifier_dummies/1"
}
"""
32 changes: 32 additions & 0 deletions features/jsonld/always_identifier.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
Feature: allow resources in properties to always be serialized as identifiers
In order to use a hypermedia API
As a client software developer
I need to be able to force to serialize only the identifier of the related resource

@createSchema
@dropSchema
Scenario: Create a set of Dummy with the alwaysIdentifier attributes and check the JSON-LD formatted response
Given there are AlwaysIdentifierDummies
When I add "Content-Type" header equal to "application/ld+json"
And I send a "GET" request to "/always_identifier_dummies/2"
Then the JSON should be equal to:
"""
{
"@context": "/contexts/AlwaysIdentifierDummy",
"@id": "/always_identifier_dummies/2",
"@type": "AlwaysIdentifierDummy",
"children": [
"/always_identifier_dummies/1"
],
"related": [
{
"@id": "/always_identifier_dummies/1",
"@type": "AlwaysIdentifierDummy",
"children": [],
"related": [],
"parent": null
}
],
"parent": "/always_identifier_dummies/1"
}
"""
5 changes: 5 additions & 0 deletions src/Annotation/ApiProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,9 @@ final class ApiProperty
* @var array
*/
public $attributes = [];

/**
* @var bool
*/
public $alwaysIdentifier;
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,14 @@ private function createMetadata(ApiProperty $annotation, PropertyMetadata $paren
$annotation->identifier,
$annotation->iri,
null,
$annotation->attributes
$annotation->attributes,
null,
$annotation->alwaysIdentifier
);
}

$propertyMetadata = $parentPropertyMetadata;
foreach ([['get', 'description'], ['is', 'readable'], ['is', 'writable'], ['is', 'readableLink'], ['is', 'writableLink'], ['is', 'required'], ['get', 'iri'], ['is', 'identifier'], ['get', 'attributes']] as $property) {
foreach ([['get', 'description'], ['is', 'readable'], ['is', 'writable'], ['is', 'readableLink'], ['is', 'writableLink'], ['is', 'required'], ['get', 'iri'], ['is', 'identifier'], ['get', 'attributes'], ['is', 'alwaysIdentifier']] as $property) {
if (null !== $value = $annotation->{$property[1]}) {
$propertyMetadata = $this->createWith($propertyMetadata, $property, $value);
}
Expand Down
25 changes: 24 additions & 1 deletion src/Metadata/Property/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ final class PropertyMetadata
private $childInherited;
private $attributes;
private $subresource;
private $alwaysIdentifier;

public function __construct(Type $type = null, string $description = null, bool $readable = null, bool $writable = null, bool $readableLink = null, bool $writableLink = null, bool $required = null, bool $identifier = null, string $iri = null, $childInherited = null, array $attributes = null, SubresourceMetadata $subresource = null)
public function __construct(Type $type = null, string $description = null, bool $readable = null, bool $writable = null, bool $readableLink = null, bool $writableLink = null, bool $required = null, bool $identifier = null, string $iri = null, $childInherited = null, array $attributes = null, SubresourceMetadata $subresource = null, bool $alwaysIdentifier = null)
{
$this->type = $type;
$this->description = $description;
Expand All @@ -49,6 +50,7 @@ public function __construct(Type $type = null, string $description = null, bool
$this->childInherited = $childInherited;
$this->attributes = $attributes;
$this->subresource = $subresource;
$this->alwaysIdentifier = $alwaysIdentifier;
}

/**
Expand Down Expand Up @@ -381,4 +383,25 @@ public function withSubresource(SubresourceMetadata $subresource = null): self

return $metadata;
}

/**
* Returns a new instance with the given alwaysIdentifier flag.
*/
public function withAlwaysIdentifier(bool $alwaysIdentifier): self
{
$metadata = clone $this;
$metadata->alwaysIdentifier = $alwaysIdentifier;

return $metadata;
}

/**
* Is the property should be serialized as identifier ?
*
* @return bool|null
*/
public function isAlwaysIdentifier()
{
return $this->alwaysIdentifier;
}
}
8 changes: 8 additions & 0 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
{
use ContextTrait;

const ALWAYS_IDENTIFIER = 'always_identifier';

protected $propertyNameCollectionFactory;
protected $propertyMetadataFactory;
protected $iriConverter;
Expand Down Expand Up @@ -97,6 +99,10 @@ public function normalize($object, $format = null, array $context = [])
$context['resources'][$resource] = $resource;
}

if ($context[self::ALWAYS_IDENTIFIER] ?? false) {
return $context['iri'] ?? $this->iriConverter->getIriFromItem($object);
}

return parent::normalize($object, $format, $context);
}

Expand Down Expand Up @@ -397,6 +403,8 @@ protected function getAttributeValue($object, $attribute, $format = null, array
{
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));

$context[self::ALWAYS_IDENTIFIER] = $propertyMetadata->isAlwaysIdentifier();

try {
$attributeValue = $this->propertyAccessor->getValue($object, $attribute);
} catch (NoSuchPropertyException $e) {
Expand Down
139 changes: 139 additions & 0 deletions tests/Fixtures/TestBundle/Entity/AlwaysIdentifierDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;

/**
* AlwaysIdentifierDummy.
*
* @author Alexandre Delplace <[email protected]>
*
* @ApiResource(attributes={
* "normalization_context"={"groups"={"alwaysIdentifierGroup"}}
* })
* @ORM\Entity
*/
class AlwaysIdentifierDummy
{
/**
* @var int id
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @var ArrayCollection children dummies
*
* @ORM\ManyToMany(targetEntity="AlwaysIdentifierDummy")
* @ApiProperty(alwaysIdentifier=true)
* @Groups({"alwaysIdentifierGroup"})
*/
private $children;

/**
* @var ArrayCollection related dummies
*
* @ORM\ManyToMany(targetEntity="AlwaysIdentifierDummy")
* @Groups({"alwaysIdentifierGroup"})
* @ORM\JoinTable(name="alwaysidentifierdummies_related")
*/
private $related;

/**
* @var AlwaysIdentifierDummy parent dummy
*
* @ORM\ManyToOne(targetEntity="AlwaysIdentifierDummy")
* @ApiProperty(alwaysIdentifier=true)
* @Groups({"alwaysIdentifierGroup"})
*/
private $parent;

public function __construct()
{
$this->related = new ArrayCollection();
$this->children = new ArrayCollection();
}

/**
* @return int
*/
public function getId()
{
return $this->id;
}

/**
* @param int $id
*/
public function setId($id)
{
$this->id = $id;
}

/**
* @return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}

/**
* @param ArrayCollection $children
*/
public function setChildren($children)
{
$this->children = $children;
}

/**
* @return ArrayCollection
*/
public function getRelated()
{
return $this->related;
}

/**
* @param ArrayCollection $related
*/
public function setRelated($related)
{
$this->related = $related;
}

/**
* @return AlwaysIdentifierDummy
*/
public function getParent()
{
return $this->parent;
}

/**
* @param AlwaysIdentifierDummy $parent
*/
public function setParent($parent)
{
$this->parent = $parent;
}
}
Loading