Coder Social home page Coder Social logo

yin's Introduction

Woohoo Labs. Yin

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads Gitter

Woohoo Labs. Yin is a PHP framework which helps you to build beautifully crafted JSON:APIs.

Table of Contents

Introduction

JSON:API specification reached 1.0 on 29th May 2015 and we also believe it is a big day for RESTful APIs as this specification can help you make APIs more robust and future-proof. Woohoo Labs. Yin (named after Yin-Yang) was born to bring efficiency and elegance to your JSON:API servers, while Woohoo Labs. Yang is its client-side counterpart.

Features

  • 100% PSR-7 compatibility
  • 99% JSON:API 1.1 compatibility (approximately)
  • Developed for efficiency and ease of use
  • Extensive documentation and examples
  • Provides Documents and Transformers to fetch resources
  • Provides Hydrators to create and update resources
  • Additional middleware for the easier kickstart and debugging

Why Yin?

Complete JSON:API framework

Woohoo Labs. Yin is a framework-agnostic library which supports the vast majority of the JSON:API 1.1 specification: it provides various capabilities including content negotiation, error handling and pagination, as well as fetching, creation, updating and deleting resources. Although Yin consists of many loosely coupled packages and classes which can be used separately, the framework is most powerful when used in its entirety.

Efficiency

We designed Yin to be as efficient as possible. That's why attributes and relationships are transformed only and if only they are requested. This feature is extremely advantageous when there are a lot of resources to transform or a rarely required transformation is very expensive. Furthermore, as transformers are stateless, the overhead of having a separate model object for each resource is avoided. Additionally, due to statelessness, the overall library works really well with dependency injection.

Supplementary middleware

There is some additional middleware for Woohoo Labs. Yin you might find useful. It can facilitate various tasks like error handling (via transformation of exceptions into JSON:API error responses), dispatching JSON:API-aware controllers or debugging (via syntax checking and validation of requests and responses).

Install

The only thing you need before getting started is Composer.

Install a PSR-7 implementation:

Because Yin requires a PSR-7 implementation (a package which provides the psr/http-message-implementation virtual package), you must install one first. You may use Laminas Diactoros or any other library of your preference:

$ composer require laminas/laminas-diactoros

Install Yin:

To install the latest version of this library, run the command below:

$ composer require woohoolabs/yin

Note: The tests and examples won't be downloaded by default. You have to use composer require woohoolabs/yin --prefer-source or clone the repository if you need them.

The latest version of Yin requires PHP 7.1 at least but you can use Yin 2.0.6 for PHP 7.0.

Install the optional dependencies:

If you want to take advantage of request/response validation then you have to also ask for the following dependencies:

$ composer require justinrainbow/json-schema
$ composer require seld/jsonlint

Basic Usage

When using Woohoo Labs. Yin, you will create:

  • Documents and resources in order to map domain objects to JSON:API responses
  • Hydrators in order to transform resources in a POST or PATCH request to domain objects

Furthermore, a JsonApi class will be responsible for the instrumentation, while a PSR-7 compatible JsonApiRequest class provides functionalities you commonly need.

Documents

The following sections will guide you through creating documents for successful responses and creating or building error documents.

Documents for successful responses

For successful requests, you must return information about one or more resources. Woohoo Labs. Yin provides multiple abstract classes that help you to create your own documents for different use cases:

  • AbstractSuccessfulDocument: A generic base document for successful responses
  • AbstractSimpleResourceDocument: A base class for documents about a single, very simple top-level resource
  • AbstractSingleResourceDocument: A base class for documents about a single, more complex top-level resource
  • AbstractCollectionDocument: A base class for documents about a collection of top-level resources

As the AbstractSuccessfulDocument is only useful for special use-cases (e.g. when a document can contain resources of multiple types), we will not cover it here.

The difference between the AbstractSimpleResourceDocument and the AbstractSingleResourceDocument classes is that the first one doesn't need a resource object. For this reason, it is preferable to use the former for only really simple domain objects (like messages), while the latter works better for more complex domain objects (like users or addresses).

Let's first have a quick look at the AbstractSimpleResourceDocument: it has a getResource() abstract method which needs to be implemented when you extend this class. The getResource() method returns the whole transformed resource as an array including the type, id, attributes, and relationships like below:

protected function getResource(): array
{
    return [
        "type"       => "<type>",
        "id"         => "<ID>",
        "attributes" => [
            "key" => "value",
        ],
    ];
}

Please note that AbstractSimpleResourceDocument doesn't support some features out-of-the-box like sparse fieldsets, automatic inclusion of related resources etc. That's why this document type should only be considered as a quick-and-dirty solution, and generally you should choose another, more advanced document type introduced below in the majority of the use cases.

AbstractSingleResourceDocument and AbstractCollectionDocument both need a resource object in order to work, which is a concept introduced in the following sections. For now, it is enough to know that one must be passed for the documents during instantiation. This means that a minimal constructor of your documents should look like this:

public function __construct(MyResource $resource)
{
    parent::__construct($resource);
}

You can of course provide other dependencies for your constructor or completely omit it if you don't need it.

When you extend either AbstractSingleResourceDocument or AbstractCollectionDocument, they both require you to implement the following methods:

/**
 * Provides information about the "jsonapi" member of the current document.
 *
 * The method returns a new JsonApiObject object if this member should be present or null
 * if it should be omitted from the response.
 */
public function getJsonApi(): ?JsonApiObject
{
    return new JsonApiObject("1.1");
}

The description says it very clear: if you want a jsonapi member in your response, then create a new JsonApiObject. Its constructor expects the JSON:API version number and an optional meta object (as an array).

/**
 * Provides information about the "meta" member of the current document.
 *
 * The method returns an array of non-standard meta information about the document. If
 * this array is empty, the member won't appear in the response.
 */
public function getMeta(): array
{
    return [
        "page" => [
            "offset" => $this->object->getOffset(),
            "limit" => $this->object->getLimit(),
            "total" => $this->object->getCount(),
        ]
    ];
}

Documents may also have a "meta" member which can contain any non-standard information. The example above adds information about pagination to the document.

Note that the object property is a variable of any type (in this case it is a hypothetical collection), and this is the main "subject" of the document.

/**
 * Provides information about the "links" member of the current document.
 *
 * The method returns a new DocumentLinks object if you want to provide linkage data
 * for the document or null if the member should be omitted from the response.
 */
public function getLinks(): ?DocumentLinks
{
    return new DocumentLinks(
        "https://example.com/api",
        [
            "self" => new Link("/books/" . $this->getResourceId())
        ]
    );

    /* This is equivalent to the following:
    return DocumentLinks::createWithBaseUri(
        "https://example.com/api",
        [
            "self" => new Link("/books/" . $this->getResourceId())
        ]
    );
}

This time, we want a self link to appear in the document. For this purpose, we utilize the getResourceId() method, which is a shortcut of calling the resource (which is introduced below) to obtain the ID of the primary resource ($this->resource->getId($this->object)).

The only difference between the AbstractSingleResourceDocument and AbstractCollectionDocument is the way they regard the object. The first one regards it as a single domain object while the latter regards it as an iterable collection.

Usage

Documents can be transformed to HTTP responses. The easiest way to achieve this is to use the JsonApi class and choose the appropriate response type. Successful documents support three kinds of responses:

  • normal: All the top-level members can be present in the response (except for the "errors")
  • meta: Only the "jsonapi", "links" and meta top-level member can be present in the response
  • relationship: The specified relationship object will be the primary data of the response

Documents for error responses

An AbstractErrorDocument can be used to create reusable documents for error responses. It also requires the same abstract methods to be implemented as the successful ones, but additionally an addError() method can be used to include error items.

/** @var AbstractErrorDocument $errorDocument */
$errorDocument = new MyErrorDocument();
$errorDocument->addError(new MyError());

There is an ErrorDocument too, which makes it possible to build error responses on-the-fly:

/** @var ErrorDocument $errorDocument */
$errorDocument = new ErrorDocument();
$errorDocument->setJsonApi(new JsonApiObject("1.0"));
$errorDocument->setLinks(ErrorLinks::createWithoutBaseUri()->setAbout("https://example.com/api/errors/404")));
$errorDocument->addError(new MyError());

Resources

Documents for successful responses can contain one or more top-level resources and included resources. That's why resources are responsible for converting domain objects into JSON:API resources and resource identifiers.

Although you are encouraged to create one transformer for each resource type, you also have the ability to define "composite" resources following the Composite design pattern.

Resources must implement the ResourceInterface. In order to facilitate this job, you can also extend the AbstractResource class.

Children of the AbstractResource class need several abstract methods to be implemented - most of them are similar to the ones seen in the Document objects. The following example illustrates a resource dealing with a book domain object and its "authors" and "publisher" relationships.

class BookResource extends AbstractResource
{
    /**
     * @var AuthorResource
     */
    private $authorResource;

    /**
     * @var PublisherResource
     */
    private $publisherResource;

    /**
     * You can type-hint the object property this way.
     * @var array
     */
    protected $object;

    public function __construct(
        AuthorResource $authorResource,
        PublisherResource $publisherResource
    ) {
        $this->authorResource = $authorResource;
        $this->publisherResource = $publisherResource;
    }

    /**
     * Provides information about the "type" member of the current resource.
     *
     * The method returns the type of the current resource.
     *
     * @param array $book
     */
    public function getType($book): string
    {
        return "book";
    }

    /**
     * Provides information about the "id" member of the current resource.
     *
     * The method returns the ID of the current resource which should be a UUID.
     *
     * @param array $book
     */
    public function getId($book): string
    {
        return $this->object["id"];

        // This is equivalent to the following (the $book parameter is used this time instead of $this->object):
        return $book["id"];
    }

    /**
     * Provides information about the "meta" member of the current resource.
     *
     * The method returns an array of non-standard meta information about the resource. If
     * this array is empty, the member won't appear in the response.
     *
     * @param array $book
     */
    public function getMeta($book): array
    {
        return [];
    }

    /**
     * Provides information about the "links" member of the current resource.
     *
     * The method returns a new ResourceLinks object if you want to provide linkage
     * data about the resource or null if it should be omitted from the response.
     *
     * @param array $book
     */
    public function getLinks($book): ?ResourceLinks
    {
        return new ResourceLinks::createWithoutBaseUri()->setSelf(new Link("/books/" . $this->getId($book)));

        // This is equivalent to the following:
        // return new ResourceLinks("", new Link("/books/" . $this->getResourceId()));
    }

    /**
     * Provides information about the "attributes" member of the current resource.
     *
     * The method returns an array where the keys signify the attribute names,
     * while the values are callables receiving the domain object as an argument,
     * and they should return the value of the corresponding attribute.
     *
     * @param array $book
     * @return callable[]
     */
    public function getAttributes($book): array
    {
        return [
            "title" => function () {
                return $this->object["title"];
            },
            "pages" => function () {
                return (int) $this->object["pages"];
            },
        ];

        // This is equivalent to the following (the $book parameter is used this time instead of $this->object):
        return [
            "title" => function (array $book) {
                return $book["title"];
            },
            "pages" => function (array $book) {
                return (int) $book["pages"];
            },
        ];
    }

    /**
     * Returns an array of relationship names which are included in the response by default.
     *
     * @param array $book
     */
    public function getDefaultIncludedRelationships($book): array
    {
        return ["authors"];
    }

    /**
     * Provides information about the "relationships" member of the current resource.
     *
     * The method returns an array where the keys signify the relationship names,
     * while the values are callables receiving the domain object as an argument,
     * and they should return a new relationship instance (to-one or to-many).
     *
     * @param array $book
     * @return callable[]
     */
    public function getRelationships($book): array
    {
        return [
            "authors" => function () {
                return ToManyRelationship::create()
                    ->setLinks(
                        RelationshipLinks::createWithoutBaseUri()->setSelf(new Link("/books/relationships/authors"))
                    )
                    ->setData($this->object["authors"], $this->authorTransformer);
            },
            "publisher" => function () {
                return ToOneRelationship::create()
                    ->setLinks(
                        RelationshipLinks::createWithoutBaseUri()->setSelf(new Link("/books/relationships/publisher"))
                    )
                    ->setData($this->object["publisher"], $this->publisherTransformer);
            },
        ];

        // This is equivalent to the following (the $book parameter is used this time instead of $this->object):

        return [
            "authors" => function (array $book) {
                return ToManyRelationship::create()
                    ->setLinks(
                        RelationshipLinks::createWithoutBaseUri()->setSelf(new Link("/books/relationships/authors"))
                    )
                    ->setData($book["authors"], $this->authorTransformer);
            },
            "publisher" => function ($book) {
                return ToOneRelationship::create()
                    ->setLinks(
                        RelationshipLinks::createWithoutBaseUri()->setSelf(new Link("/books/relationships/publisher"))
                    )
                    ->setData($book["publisher"], $this->publisherTransformer);
            },
        ];
    }
}

Generally, you don't use resources directly. Only documents need them to be able to fill the "data", the "included", and the "relationship" members in the responses.

Hydrators

Hydrators allow us to initialize the properties of a domain object as required by the current HTTP request. This means, when a client wants to create or update a resource, hydrators can help instantiate a domain object, which can then be validated, saved etc.

There are three abstract hydrator classes in Woohoo Labs. Yin:

  • AbstractCreateHydrator: It can be used for requests which create a new resource
  • AbstractUpdateHydrator: It can be used for requests which update an existing resource
  • AbstractHydrator: It can be used for both type of requests

For the sake of brevity, we only introduce the usage of the latter class as it is simply the union of AbstractCreateHydrator and AbstractUpdateHydrator. Let's have a look at an example hydrator:

class BookHydrator extends AbstractHydrator
{
    /**
     * Determines which resource types can be accepted by the hydrator.
     *
     * The method should return an array of acceptable resource types. When such a resource is received for hydration
     * which can't be accepted (its type doesn't match the acceptable types of the hydrator), a ResourceTypeUnacceptable
     * exception will be raised.
     *
     * @return string[]
     */
    protected function getAcceptedTypes(): array
    {
        return ["book"];
    }

    /**
     * Validates a client-generated ID.
     *
     * If the $clientGeneratedId is not a valid ID for the domain object, then
     * the appropriate exception should be thrown: if it is not well-formed then
     * a ClientGeneratedIdNotSupported exception can be raised, if the ID already
     * exists then a ClientGeneratedIdAlreadyExists exception can be thrown.
     *
     * @throws ClientGeneratedIdNotSupported
     * @throws ClientGeneratedIdAlreadyExists
     * @throws Exception
     */
    protected function validateClientGeneratedId(
        string $clientGeneratedId,
        JsonApiRequestInterface $request,
        ExceptionFactoryInterface $exceptionFactory
    ) {
        if ($clientGeneratedId !== null) {
            throw $exceptionFactory->createClientGeneratedIdNotSupportedException($request, $clientGeneratedId);
        }
    }

    /**
     * Produces a new ID for the domain objects.
     *
     * UUID-s are preferred according to the JSON:API specification.
     */
    protected function generateId(): string
    {
        return Uuid::generate();
    }

    /**
     * Sets the given ID for the domain object.
     *
     * The method mutates the domain object and sets the given ID for it.
     * If it is an immutable object or an array the whole, updated domain
     * object can be returned.
     *
     * @param array $book
     * @return mixed|void
     */
    protected function setId($book, string $id)
    {
        $book["id"] = $id;

        return $book;
    }

    /**
     * You can validate the request.
     *
     * @throws JsonApiExceptionInterface
     */
    protected function validateRequest(JsonApiRequestInterface $request): void
    {
        // WARNING! THIS CONDITION CONTRADICTS TO THE SPEC
        if ($request->getAttribute("title") === null) {
            throw new LogicException("The 'title' attribute is required!");
        }
    }

    /**
     * Provides the attribute hydrators.
     *
     * The method returns an array of attribute hydrators, where a hydrator is a key-value pair:
     * the key is the specific attribute name which comes from the request and the value is a
     * callable which hydrates the given attribute.
     * These callables receive the domain object (which will be hydrated), the value of the
     * currently processed attribute, the "data" part of the request and the name of the attribute
     * to be hydrated as their arguments, and they should mutate the state of the domain object.
     * If it is an immutable object or an array (and passing by reference isn't used),
     * the callable should return the domain object.
     *
     * @param array $book
     * @return callable[]
     */
    protected function getAttributeHydrator($book): array
    {
        return [
            "title" => function (array $book, $attribute, $data, $attributeName) {
                $book["title"] = $attribute;

                return $book;
            },
            "pages" => function (array &$book, $attribute, $data, $attributeName) {
                $book["pages"] = $attribute;
            },
        ];
    }

    /**
     * Provides the relationship hydrators.
     *
     * The method returns an array of relationship hydrators, where a hydrator is a key-value pair:
     * the key is the specific relationship name which comes from the request and the value is a
     * callable which hydrate the previous relationship.
     * These callables receive the domain object (which will be hydrated), an object representing the
     * currently processed relationship (it can be a ToOneRelationship or a ToManyRelationship
     * object), the "data" part of the request and the relationship name as their arguments, and
     * they should mutate the state of the domain object.
     * If it is an immutable object or an array (and passing by reference isn't used),
     * the callable should return the domain object.
     *
     * @param mixed $book
     * @return callable[]
     */
    protected function getRelationshipHydrator($book): array
    {
        return [
            "authors" => function (array $book, ToManyRelationship $authors, $data, string $relationshipName) {
                $book["authors"] = BookRepository::getAuthors($authors->getResourceIdentifierIds());

                return $book;
            },
            "publisher" => function (array &$book, ToOneRelationship $publisher, $data, string $relationshipName) {
                $book["publisher"] = BookRepository::getPublisher($publisher->getResourceIdentifier()->getId());
            },
        ];
    }

    /**
     * You can validate the domain object after it has been hydrated from the request.
     * @param mixed $book
     */
    protected function validateDomainObject($book): void
    {
        if (empty($book["authors"])) {
            throw new LogicException("The 'authors' relationship cannot be empty!");
        }
    }
}

According to the book example, the following request:

POST /books HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": {
    "type": "book",
    "attributes": {
      "title": "Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation",
      "pages": 512
    },
    "relationships": {
      "authors": {
        "data": [
            { "type": "author", "id": "100" },
            { "type": "author", "id": "101" }
        ]
      }
    }
  }
}

will result in the following Book domain object:

Array
(
    [id] => 1
    [title] => Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation
    [pages] => 512
    [authors] => Array
        (
            [0] => Array
                (
                    [id] => 100
                    [name] => Jez Humble
                )
            [1] => Array
                (
                    [id] => 101
                    [name] => David Farley
                )
        )
    [publisher] => Array
        (
            [id] => 12346
            [name] => Addison-Wesley Professional
        )
)

Exceptions

Woohoo Labs. Yin was designed to make error handling as easy and customizable as possible. That's why all the default exceptions extend the JsonApiException class and contain an error document with the appropriate error object(s). That's why if you want to respond with an error document in case of an exception you need to do the following:

try {
    // Do something which results in an exception
} catch (JsonApiExceptionInterface $e) {
    // Get the error document from the exception
    $errorDocument = $e->getErrorDocument();

    // Instantiate the responder - make sure to pass the correct dependencies to it
    $responder = Responder::create($request, $response, $exceptionFactory, $serializer);

    // Create a response from the error document
    $responder->genericError($errorDocument);

    // Emit the HTTP response
    sendResponse($response);
}

To guarantee total customizability, we introduced the concept of Exception Factories. These are classes which create all the exceptions thrown by Woohoo Labs. Yin. As an Exception Factory of your own choice is passed to every transformer and hydrator, you can completely customize what kind of exceptions are thrown.

The default Exception Factory creates children of JsonApiExceptions but you are free to create any JsonApiExceptionInterface exceptions. If you only want to customize the error document or the error objects of your exceptions, just extend the basic Exception class and create your createErrorDocument() or getErrors() methods.

JsonApi class

The JsonApi class is the orchestrator of the whole framework. It is highly recommended to utilize this class if you want to use the entire functionality of Woohoo Labs. Yin. You can find various examples about the usage of it in the examples section or example directory.

JsonApiRequest class

The JsonApiRequest class implements the WoohooLabs\Yin\JsonApi\Request\JsonApiRequestInterface which extends the PSR-7 ServerRequestInterface with some useful, JSON:API related methods. For further information about the available methods, please refer to the documentation of JsonApiRequestInterface.

Advanced Usage

This section guides you through the advanced features of Yin.

Pagination

Yin is able to help you paginate your collection of resources. First, it provides some shortcuts for querying the request query parameters when page-based, offset-based, or cursor-based pagination strategies are used.

Page-based pagination

Yin looks for the page[number] and the page[size] query parameters and parses their value. If any of them is missing then the default page number or size will be used ("1" and "10" in the following example).

$pagination = $jsonApi->getPaginationFactory()->createPageBasedPagination(1, 10);

Fixed page-based pagination

Yin looks for the page[number] query parameter and parses its value. If it is missing then the default page number will be used ("1" in the following example). This strategy can be useful if you do not want to expose the page size at all.

$pagination = $jsonApi->getPaginationFactory()->createFixedPageBasedPagination(1);

Offset-based pagination

Yin looks for the page[offset] and the page[limit] query parameters and parses their value. If any of them is missing then the default offset or limit will be used ("1" and "10" in the following example).

$pagination = $jsonApi->getPaginationFactory()->createOffsetBasedPagination(1, 10);

Cursor-based pagination

Yin looks for the page[cursor] and the page[size] query parameters and parses their value. If any of them is missing then the default cursor or size will be used ("2016-10-01" or 10 in the following example).

$pagination = $jsonApi->getPaginationFactory()->createCursorBasedPagination("2016-10-01", 10);

Fixed cursor-based pagination

Yin looks for the page[cursor] query parameter and parses its value. If it is missing then the default cursor will be used ("2016-10-01" in the following example).

$pagination = $jsonApi->getPaginationFactory()->createFixedCursorBasedPagination("2016-10-01");

Custom pagination

If you need a custom pagination strategy, you may use the JsonApiRequestInterface::getPagination() method which returns an array of pagination parameters.

$paginationParams = $jsonApi->getRequest()->getPagination();

$pagination = new CustomPagination($paginationParams["from"] ?? 1, $paginationParams["to"] ?? 1);

Usage

As soon as you have the appropriate pagination object, you may use them when you fetch your data from a data source:

$users = UserRepository::getUsers($pagination->getPage(), $pagination->getSize());

Pagination links

The JSON:API spec makes it available to provide pagination links for your resource collections. Yin is able to help you in this regard too. You have use the DocumentLinks::setPagination() method when you define links for your documents. It expects the paginated URI and an object implementing the PaginationLinkProviderInterface as seen in the following example:

public function getLinks(): ?DocumentLinks
{
    return DocumentLinks::createWithoutBaseUri()->setPagination("/users", $this->object);
}

To make things even easier, there are some LinkProvider traits in order to ease the development of PaginationLinkProviderInterface implementations of the built-in pagination strategies. For example a collection for the User objects can use the PageBasedPaginationLinkProviderTrait. This way, only three abstract methods has to be implemented:

class UserCollection implements PaginationLinkProviderInterface
{
    use PageBasedPaginationLinkProviderTrait;

    public function getTotalItems(): int
    {
        // ...
    }

    public function getPage(): int
    {
        // ...
    }

    public function getSize(): int
    {
        // ...
    }

    // ...
}

You can find the full example here.

Loading relationship data efficiently

Sometimes it can be beneficial or necessary to fine-tune data retrieval of relationshipS. A possible scenario might be when you have a "to-many" relationship containing gazillion items. If this relationship isn't always needed than you might only want to return a data key of a relationship when the relationship itself is included in the response. This optimization can save you bandwidth by omitting resource linkage.

An example is extracted from the UserResource example class:

public function getRelationships($user): array
{
    return [
        "contacts" => function (array $user) {
            return
                ToManyRelationship::create()
                    ->setData($user["contacts"], $this->contactTransformer)
                    ->omitDataWhenNotIncluded();
        },
    ];
}

By using the omitDataWhenNotIncluded() method, the relationship data will be omitted when the relationship is not included. However, sometimes this optimization is not enough on its own. Even though we can save bandwidth with the prior technique, the relationship still has to be loaded from the data source (probably from a database), because we pass it to the relationship object with the setData() method.

This problem can be mitigated by lazy-loading the relationship. To do so, you have to use setDataAsCallable() method instead of setData():

public function getRelationships($user): array
{
    return [
        "contacts" => function (array $user) {
            return
                ToManyRelationship::create()
                    ->setDataAsCallable(
                        function () use ($user) {
                            // Lazily load contacts from the data source
                            return $user->loadContactsFromDataSource();
                        },
                        $this->contactTransformer
                    )
                    ->omitDataWhenNotIncluded()
                ;
        },
    ];
}

This way, the contacts of a user will only be loaded when the given relationship's data key is present in the response, allowing your API to be as efficient as possible.

Injecting metadata into documents

Metadata can be injected into documents on-the-fly. This comes handy if you want to customize or decorate your responses. For example if you would like to inject a cache ID into the response document, you could use the following:

// Calculate the cache ID
$cacheId = calculateCacheId();

// Respond with "200 Ok" status code along with the book document containing the cache ID in the meta data
return $jsonApi->respond()->ok($document, $book, ["cache_id" => $cacheId]);

Usually, the last argument of each responder method can be used to add meta data to your documents.

Content negotiation

The JSON:API standard specifies some rules about content negotiation. Woohoo Labs. Yin tries to help you enforce them with the RequestValidator class. Let's first create a request validator to see it in action:

$requestValidator = new RequestValidator(new DefaultExceptionFactory(), $includeOriginalMessageInResponse);

In order to customize the exceptions which can be thrown, it is necessary to provide an Exception Factory. On the other hand, the $includeOriginalMessageInResponse argument can be useful in a development environment when you also want to return the original request body that triggered the exception in the error response.

In order to validate whether the current request's Accept and Content-Type headers conform to the JSON:API specification, use this method:

$requestValidator->negotiate($request);

Request/response validation

You can use the following method to check if the query parameters of the current request are in line with the naming rules:

$requestValidator->validateQueryParams($request);

Note: In order to apply the following validations, remember to install the optional dependencies of Yin.

Furthermore, the request body can be validated if it is a well-formed JSON document:

$requestValidator->validateJsonBody($request);

Similarly, responses can be validated too. Let's create a response validator first:

$responseValidator = new ResponseValidator(
    new JsonSerializer(),
    new DefaultExceptionFactory(),
    $includeOriginalMessageInResponse
);

To ensure that the response body is a well-formed JSON document, one can use the following method:

$responseValidator->validateJsonBody($response);

To ensure that the response body is a well-formed JSON:API document, one can use the following method:

$responseValidator->validateJsonApiBody($response);

Validating the responses can be useful in a development environment to find possible bugs early.

Custom serialization

You can configure Yin to serialize responses in a custom way instead of using the default serializer (JsonSerializer) that utilizes the json_encode() function to write JSON:API documents into the response body.

In the majority of the use-cases, the default serializer should be sufficient for your needs, but sometimes you might need more sophistication. Or sometimes you want to do nasty things like returning your JSON:API response as an array without any serialization in case your API endpoint was called "internally".

In order to use a custom serializer, create a class implementing SerializerInterface and setup your JsonApi instance accordingly (pay attention to the last argument):

$jsonApi = new JsonApi(new JsonApiRequest(), new Response(), new DefaultExceptionFactory(), new CustomSerializer());

Custom deserialization

You can configure Yin to deserialize requests in a custom way instead of using the default deserializer (JsonDeserializer) that utilizes the json_decode() function to parse the contents of the request body.

In the majority of the use-cases, the default deserializer should be sufficient for your needs, but sometimes you might need more sophistication. Or sometimes you want to do nasty things like calling your JSON:API endpoints "internally" without converting your request body to JSON format.

In order to use a custom deserializer, create a class implementing DeserializerInterface and setup your JsonApiRequest instance accordingly (pay attention to the last argument):

$request = new JsonApiRequest(ServerRequestFactory::fromGlobals(), new DefaultExceptionFactory(), new CustomDeserializer());

Middleware

If you use a middleware-oriented framework (like Woohoo Labs. Harmony, Zend-Stratigility, Zend-Expressive or Slim Framework 3), you will find the Yin-middleware library quite useful. Read the documentation to learn about its advantages!

Examples

Fetching a single resource

public function getBook(JsonApi $jsonApi): ResponseInterface
{
    // Getting the "id" of the currently requested book
    $id = $jsonApi->getRequest()->getAttribute("id");

    // Retrieving a book domain object with an ID of $id
    $book = BookRepository::getBook($id);

    // Instantiating a book document
    $document = new BookDocument(
        new BookResource(
            new AuthorResource(),
            new PublisherResource()
        )
    );

    // Responding with "200 Ok" status code along with the book document
    return $jsonApi->respond()->ok($document, $book);
}

Fetching a collection of resources

public function getUsers(JsonApi $jsonApi): ResponseInterface
{
    // Extracting pagination information from the request, page = 1, size = 10 if it is missing
    $pagination = $jsonApi->getPaginationFactory()->createPageBasedPagination(1, 10);

    // Fetching a paginated collection of user domain objects
    $users = UserRepository::getUsers($pagination->getPage(), $pagination->getSize());

    // Instantiating a users document
    $document = new UsersDocument(new UserResource(new ContactResource()));

    // Responding with "200 Ok" status code along with the users document
    return $jsonApi->respond()->ok($document, $users);
}

Fetching a relationship

public function getBookRelationships(JsonApi $jsonApi): ResponseInterface
{
    // Getting the "id" of the currently requested book
    $id = $jsonApi->getRequest()->getAttribute("id");

    // Getting the currently requested relationship's name
    $relationshipName = $jsonApi->getRequest()->getAttribute("rel");

    // Retrieving a book domain object with an ID of $id
    $book = BookRepository::getBook($id);

    // Instantiating a book document
    $document = new BookDocument(
        new BookResource(
            new AuthorResource(),
            new PublisherResource(
                new RepresentativeResource()
            )
        )
    );

    // Responding with "200 Ok" status code along with the requested relationship document
    return $jsonApi->respond()->okWithRelationship($relationshipName, $document, $book);
}

Creating a new resource

public function createBook(JsonApi $jsonApi): ResponseInterface
{
    // Hydrating a new book domain object from the request
    $book = $jsonApi->hydrate(new BookHydrator(), []);

    // Saving the newly created book
    // ...

    // Creating the book document to be sent as the response
    $document = new BookDocument(
        new BookResource(
            new AuthorResource(),
            new PublisherResource(
                new RepresentativeResource()
            )
        )
    );

    // Responding with "201 Created" status code along with the book document
    return $jsonApi->respond()->created($document, $book);
}

Updating a resource

public function updateBook(JsonApi $jsonApi): ResponseInterface
{
    // Retrieving a book domain object with an ID of $id
    $id = $jsonApi->getRequest()->getResourceId();
    $book = BookRepository::getBook($id);

    // Hydrating the retrieved book domain object from the request
    $book = $jsonApi->hydrate(new BookHydrator(), $book);

    // Updating the book
    // ...

    // Instantiating the book document
    $document = new BookDocument(
        new BookResource(
            new AuthorResource(),
            new PublisherResource(
                new RepresentativeResource()
            )
        )
    );

    // Responding with "200 Ok" status code along with the book document
    return $jsonApi->respond()->ok($document, $book);
}

Updating a relationship of a resource

public function updateBookRelationship(JsonApi $jsonApi): ResponseInterface
{
    // Checking the name of the currently requested relationship
    $relationshipName = $jsonApi->getRequest()->getAttribute("rel");

    // Retrieving a book domain object with an ID of $id
    $id = $jsonApi->getRequest()->getAttribute("id");
    $book = BookRepository::getBook($id);
    if ($book === null) {
        die("A book with an ID of '$id' can't be found!");
    }

    // Hydrating the retrieved book domain object from the request
    $book = $jsonApi->hydrateRelationship($relationshipName, new BookHydrator(), $book);

    // Instantiating a book document
    $document = new BookDocument(
        new BookResource(
            new AuthorResource(),
            new PublisherResource(
                new RepresentativeResource()
            )
        )
    );

    // Responding with "200 Ok" status code along with the book document
    return $jsonApi->respond()->ok($document, $book);
}

How to try it out

If you want to see how Yin works, have a look at the examples. If docker-compose and make is available on your system, then just run the following commands in order to try out the example API:

cp .env.dist .env      # You can now edit the settings in the .env file
make composer-install  # Install the Composer dependencies
make up                # Start the webserver

And finally, just visit the following URL: localhost:8080. You can even restrict the retrieved fields and relationships via the fields and include parameters as specified by JSON:API.

Example URIs for the book examples:

  • GET /books/1: Fetch a book
  • GET /books/1/relationships/authors: Fetch the authors relationship
  • GET /books/1/relationships/publisher: Fetch the publisher relationship
  • GET /books/1/authors: Fetch the authors of a book
  • POST /books: Create a new book
  • PATCH /books/1: Update a book
  • PATCH /books/1/relationships/author: Update the authors of the book
  • PATCH /books/1/relationships/publisher: Update the publisher of the book

Example URIs for the user examples:

  • GET /users: Fetch users
  • GET /users/1: Fetch a user
  • GET /users/1/relationships/contacts: Fetch the contacts relationship

When you finished your work, simply stop the webserver:

make down

If the prerequisites are not available for you, you have to set up a webserver, and install PHP on your host system as well as the dependencies via Composer.

Integrations

Versioning

This library follows SemVer v2.0.0.

Change Log

Please see CHANGELOG for more information on recent changes.

Testing

Woohoo Labs. Yin has a PHPUnit test suite. To run the tests, run the following command from the project folder:

$ phpunit

Additionally, you may run docker-compose up or make test in order to execute the tests.

Contributing

Please see CONTRIBUTING for details.

Support

Please see SUPPORT for details.

Credits

License

The MIT License (MIT). Please see the License File for more information.

yin's People

Contributors

arrayiterator avatar art4 avatar atkrad avatar b1rdex avatar chasingsublimity avatar dimvic avatar djuki avatar emil-nasso avatar holtkamp avatar jkrzefski avatar jnamenyi avatar kocsismate avatar lunika avatar michaelcontento avatar mym avatar pablorsk avatar piotrbelina avatar pol-valentin avatar qpautrat avatar tiborjaszi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yin's Issues

Overriding AbstractResourceTransformer->transformAttributesObject()

Is there a reason why the methods in AbstractResourceTransformer are private? It causes some problems overriding them, for example you can't override transformAttributesObject() because it is being called elsewhere in the same scope and you need to override those private methods as well.

For the record, what I want to do is extend the class and have this:

public function getAttributes($domainObject)
    {
        $ret = [];
        foreach ($domainObject->attributes as $k=>$v) {
            if ($k!=$domainObject->primaryKey()) {
                $ret[$k] = function(CActiveRecord $domainObject, $attr) { return $domainObject->{$attr}; };
            }
        }
        return $ret;
    }

I actually believe the fingerprint for the closure there could include the attribute name by default, but that's something you might have considered and rejected already so...

Example of how to do multi-level relationship?

Do you have any examples of how to do a multi-level includes?

For example include=comments,comments.authors? (and have it return the right things)

The problem we're seeing is when you try to do multi-level documents it seems to break on validateRelationships -

e.g.

$article = new ArticleDocument(new ArticleResourceTransformer(new CommentResourceTransformer(new AuthorResourceTransformer())));

When CommentResourceTransformer defines a getRelationships($comment) of type "author", it seems to also get validated looking for "comments" in this case and then throws an exception out of "validateRelationships".

Instruction lacking information on examples

I followed the instructions on how to install yin. However, I can't run examples as the instruction is lacking information on how to do that. It'w written that I should run composer install inside yin. OK, did it, it created another vendor folder inside yin and yin was in another vendor folder already as I used composer to install yin for my project. Installing yin using composer doesn't install the folder examples, only src. And inside installed yin folder, running composer install installs a lot of stuff but not the examples folder. Please fix that. I want to use a library for JSON API standard that has validation and everything implemented, however yin and yang seem to be overly complicated as there's no easy tutorial that covers all the cases of CRUD unless it's the folder examples that I can't get to work.

Relationship not in `include` parameter nor `getDefaultRelationships()` is still being evaluated

I'm unsure if this is the intended behavior or not but I was a bit surprised to discover that relationships returned by the transform's getRelationships() method are still being evaluated even though the relationship name is not present in the include query parameter nor in the array returned from the transform's getDefaultRelationships().

I did a bit of digging and found that when a relationship is being transformed there's a check here that calls both isIncludedField() and isIncludedRelationship() to figure out if the relationship should be transformed or not.

However, isIncludedField() returns true since the default behavior for fields is to be included if no fields are present in the fields query parameter, causing the the check to fail and transform to continue.

My assumption would be that if my transformer has two relationships defined in getRelationships() and only one of them in getDefaultRelationships(), both relationships should not be evaluated.

ResourceIdentifier does not consider "data" key

Hi there,

As JSON API specification says

If a relationship is provided in the relationships member of the resource object, its value MUST be a relationship object with a data member.

Correct me if i'm wrong, but ResourceIdentifier does not care about this data key.
And as we pass complete array in Request it results as null.

You can try it with this simple example from JSON API documentation:

{
  "data": {
    "type": "photos",
    "attributes": {
      "title": "Ember Hamster",
      "src": "http://example.com/images/productivity.png"
    },
    "relationships": {
      "photographer": {
        "data": { "type": "people", "id": "9" }
      }
    }
  }
}

Custom Responder, Document without Response and some more.

Hi,

I use this library for the last 2 weeks, it helps me a lot and I would like to discuss with you about some choice you made and understand why.

First of all, why did you choose to create the Responder in the JsonApi class ? it makes hard to create our own responder because it is not possible to use it with the original JsonApi class. Doing this, we have 2 choices :

  • extends JsonApi class and change its behaviour
  • use directly our own reponder. After all the JsonApi class is just a factory which instanciate a new Responder injecting a Request, a Response, an ExceptionFactory and a Serializer.

Secondly, why did you choose to couple the Document witht the serializer ? AFAIK the serializer is only here to hydrate the Response, it doesn't transform the Document in a JsonApi content. It should be great to remove the response in the Document transformation process, I think it's more the Responder responsability to do this. The Responder receive a Document, transform it and then hydrate the response and return it. Just like you did with the Hydrator.

I would be happy to discuss about that and if you want I can help by providing a PoC, contribute to the library, etc.

Use a ResponderInterface instead of concrete type Responder

Would it be possible to change the return type of respond to an interface instead? I would like to create a LaravelResponder that would put the results through a psr7 response bridge first. If you agree I will make a merge request with the code changes needed.

    public function respond(): Responder
    {
        return new Responder($this->request, $this->response, $this->exceptionFactory, $this->serializer);
    }

Source from JsonApi: https://github.com/woohoolabs/yin/blob/master/src/JsonApi/JsonApi.php#L83-L86

Exception code 0

Hi!

Exceptions in namespace WoohooLabs\Yin\JsonApi\Exception don't have correct codes, they all use default code 0, without the possibility of overriding. This makes it harder to handle these errors. For example, FullReplacementProhibited should have code 403.

Libraries like jsonapi bundle, that is commonly used with yours, depend on the code to format errors correctly, so it would be nice to have this fixed.

I could make a PR containing the necessary changes if you agree.

Installation fails because of missing psr/http-message-implementation

Hi, when i try to install your package using composer i receive the following error message:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - woohoolabs/yin 1.0.2 requires psr/http-message-implementation ^1.0.0 -> no matching package found.
    - woohoolabs/yin 1.0.1 requires psr/http-message-implementation ^1.0.0 -> no matching package found.
    - woohoolabs/yin 1.0.0 requires psr/http-message-implementation ^1.0.0 -> no matching package found.
    - Installation request for woohoolabs/yin ~1.0 -> satisfiable by woohoolabs/yin[1.0.0, 1.0.1, 1.0.2].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

A package psr/http-message-implementation does not exists, so i think it should be psr/http-message, correct?

Injecting a SerializerInterface

Hello Woohoolabs !
How are you ?

How do you think about instead hard coded json_encode() using a SerializerInterface which could be injected in Document ?

Through this we could be able to inject any Serializer (i'm thinking about JMSSerializer right now) and use it.

Thoughts ?

Data member isn't present when fetching a relationship

As found by @emil-nasso in #20 when visiting the following example url: ?path=/users/2/relationships/contacts, the data member doesn't show up:

{
  "links": {
    "related": "/?path=/users/2/contacts",
    "self": "/?path=/users/2/relationships/contacts"
  }
}

However, when including the relationship in question: ?path=/users/1/relationships/contacts&include=contacts it will be visible:

{
  "links": {
    "related": "/?path=/users/1/contacts",
    "self": "/?path=/users/1/relationships/contacts"
  },
  "data": [
    {
      "type": "contact",
      "id": "100"
    },
    {
      "type": "contact",
      "id": "101"
    },
    {
      "type": "contact",
      "id": "102"
    }
  ],
  "included": [
    {
      "type": "contact",
      "id": "100",
      "links": {
        "self": "/?path=/contacts/100"
      },
      "attributes": {
        "phone": "+123456789"
      }
    },
    {
      "type": "contact",
      "id": "101",
      "links": {
        "self": "/?path=/contacts/101"
      },
      "attributes": {
        "email": "[email protected]"
      }
    },
    {
      "type": "contact",
      "id": "102",
      "links": {
        "self": "/?path=/contacts/102"
      },
      "attributes": {
        "email": "[email protected]"
      }
    }
  ]
}

Cannot install via composer

Hi,

I cannot install the package via composer

composer require woohoolabs/yin

Here is the error

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for woohoolabs/yin ^0.10.8 -> satisfiable by woohoolabs/yin[0.10.8].
    - woohoolabs/yin 0.10.8 requires psr/http-message-implementation ^1.0.0 -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Problem with the resource transformer design pattern and cross relations

When using cross relations between 2 resources the current design pattern used by the yin resource transformers has the issue of circular dependencies. I think it is necessary to cross relate objects. For example:

  • You have a book object and want to know the author(s)
  • You have an author object and want two know books written by the author

I solved this in my case outside of the lib with injecting just a container into the transformers which can require the transformers on demand. But in my opinion this should be solved by the lib itself.

The neomerx lib solves this by mapping the transformers "hard" with the models.. but i liked your modular "loose" approach here.. so maybe a factory patter where one needs to register all transformers and a factory where you can get them whenever you need them could solve the problem.

Omitting `data` property from `relationships` information

I'm trying to describe a relationship only by the links for which can be used to fetch the actual data of the related resource.

There are two resources A and B, where A has many Bs. When fetching A the entries of B shouldn't be included.

Performing the following request

GET /api/A/1234 HTTP/1.1
Host: test.dev
Accept: application/json

responds with

{
    "jsonapi": {
        "version": "1.0"
    },
    "links": {
        "self": "/api/A/1234"
    },
    "data": {
        "type": "A",
        "id": "1234",
        "links": {
            "self": "/api/A/1234"
        },
        "attributes": {
            "name": "Resource 1"
        },
        "relationships": {
            "B": {
                "links": {
                    "self": "/api/A/1234/relationships/B",
                    "related": "/api/A/1234/B"
                },
                "data": []
            }
        }
    }
}

where I'm trying to get a response without the data.relationships.B.data property (the empty array).

The relationship is described in the transformer for A by:

ToManyRelationship::create()
    ->setLinks(
        Links::createWithoutBaseUri([
            'self'    => new Link('/api/A/' . $this->getId($a) . '/relationships/B'),
            'related' => new Link('/api/A/' . $this->getId($a) . '/B'),
        ])
    )
    ->omitWhenNotIncluded()

The documentation states that a relationship must contain at least one of the three properties: links, data, or meta. (it's valid without the data property).

It seems like commit 1aef043 forces the data property to be present. It was implemented to resolve #22. The commit basically assigns a variable $x = $y, and then later compares the two $x === $y.

I'm not sure about what the Transformation::$fetchedRelationship variable should express, but comparing issue #22 with the analogy of my case, my best guess is that it should represent resource A, thereby ensuring that the data property of A is present at the outer scope.

Sparse field sets return empty arrays for null attributes (shouldn't it be empty hashes)?

Back to the articles, comments, authors example:

What I'd like to do, for example, is to retrieve either all the body of comments on an article (but no information/attributes for the article), or all the first-names of authors on an article (again returning no attributes for the article).

According to this discussion:
http://discuss.jsonapi.org/t/clarification-on-the-sparse-fieldset-response/221/2

It seems that the proper way to do this is something like this:

GET /articles/1?include=comments&fields[articles]=&fields[comments]=body

It should return something like this (as copied/interpreted form the discussion linked above):

{
  "data": {
     "type": "articles",
     "id": "1",
   },
  "included": [{
    "type": "comments",
    "id": "1",
    "attributes": { "body": "yadayada"},
  }]
}

However with yin, it seems it's not removing the articles attributes, relationships etc but returning them...

Update 1/19/2016:

It's been determined this was due to user error. Yin does seem to properly null out attributes (cool!). There's a small other issue which I've highlighted below in a new comment (updating the title of this issue to reflect it)

Laravel 5 Integration help

Hello I have finally integrated Yin into laravel 5.6 with dingo API But stuck here.

Below is my code.

public function show()
{

    // Find the current route
    $exceptionFactory = new DefaultExceptionFactory();
    $deserializer = new JsonDeserializer();
    $request = new Request(ServerRequestFactory::fromGlobals(), $exceptionFactory, $deserializer);
    // Invoking the current action
    $jsonApi = new JsonApi($request, new Response(), $exceptionFactory);

    $id = $jsonApi->getRequest()->getAttribute("id");

    ////country
    $country = CountryRepository::getCountry($id);

    // Instantiating a book document
    $document = new CountryDocument(
        new CountryResourceTransformer()
    );
    // Responding with "200 Ok" status code along with the book document
    return $jsonApi->respond()->ok($document, $country);

} 

$id = $jsonApi->getRequest()->getAttribute("id");
returns null

my url is of the form http://api.example.com/countries/281615

Are mine implementing this the right way or do i have to use laravel/Dingo Request class Dingo\Api\Http\Request

my route

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
    $api->get('countries/{country}', 'App\Api\Controllers\CountryController@show');
}

Works fine if manually set the id
for instance on my user class

$user = UserRepository::getUser(1233);

    // Instantiating a book document
    $document = new UserDocument(
        new UserResourceTransformer(
            new CountryResourceTransformer()
        )
    );
    // Responding with "200 Ok" status code along with the book document
    return $jsonApi->respond()->ok($document, $user);

using the request url

http://api.example.com/users/11122?include=country&limit=1

I get the response

{
"jsonapi": {
    "version": "1.0"
},
"links": {
    "self": "/?path=/user/1233"
},
"data": {
    "type": "users",
    "id": "1233",
    "links": {
        "self": "/?path=/users/1233"
    },
    "attributes": {
        "title": "Prof.",
        "firstname": "Theo",
        "lastname": "Parisian",
        "othernames": "Sr.",
        "email": "[email protected]",
        
    },
    "relationships": {
        "country": {
            "links": {
                "self": "/?path=/users/1233/relationships/country"
            },
            "data": {
                "type": "countries",
                "id": "560515"
            }
        }
    }
},
"included": [
    {
        "type": "countries",
        "id": "560515",
        "links": {
            "self": "/?path=/countries/560515"
        },
        "attributes": {
            "id": 560515,
            "long_name": "Armenia",
            "short_name": "Sudan",
           
        }
    }
]
}

Thanks just need some guidance to complete this.

Example of a document that uses AbstractSimpleResourceDocument

Hi,

I started implementing yin into my project and thought lets start with the "simple", but I don't seem to be able to figure out how to implement it. It's mainly the (uncommented) abstract getResource()-method that's causing the problem.

I haven't tried the AbstractSingleDocument yet, but I am sure that's going to be easy to use (because of the great readme and examples ๐Ÿ‘ ).

So my question (request) is if you could provide use with an example of how to use AbstractSimpleResourceDocument.

Thanks in advance!

PageBasedPaginationProviderTrait getPrevLink and getNextLink generate wrong links

Hi,

first thank you for the great library! I use it in my project with Zend Expressive and it helped me a lot to implement JSONAPI.

I use the PageBasedPaginationProviderTrait to generate pagination links and I found out it generates Prev and Next links wrong.

The Prev link is null on the last page and the Next link is null on the page before the last page.
The problem is here and here.
I believe that || $this->getPage() >= $this->getLastPage() should be removed from line 66 and $this->getPage() + 1 >= $this->getLastPage() should become $this->getPage() >= $this->getLastPage() on line 79.

Please let me know if this is correct and if I should make a PR to fix it. Thanks!

PATCH a relationship with {"data":null}

According to the specification issuing a PATCH request which includes a relationship with a {"data":null} body should clear the relationship, but in HydratorTrait->hydrateRelationships() this is found:

if (empty($data["relationships"])) {
    return $domainObject;
}

which results in the relationship hydrator never being called, is that intentional?

Of course one can override hydrateRelationships(), but shouldn't the defaults conform to the standards?

Hydrate attribute with NULL

Hi fellows,

I need your POV on this one.
Correct me if i'm wrong but I should be able to set an attribute to my domain object to null if want to.
But as we can see there hydration will be forgotten.
Thereby I'm not able to delete my field description for example.

Thx.

Recommandation for a symfony based implementation

Hi,

I want to create a symfony 4 based hateos api that follow jsonapi specs

I can find to valuable implementations :

Those implementations are very similar. On documentation, I can see a link for https://repo.packagist.org/packages/qpautrat/woohoolabs-yin-bundle.

@qpautrat @paknahad Your implementations are very similar.

Is there a way to combine efforts made ?

Regards,

Expressing empty relationships in the response

In the json response format used by the current version of yin, i am running into problems that i think is caused by not following the json api specification.

The problem is in the relationships data. Lets take a look at this example:

"data": {
    "type": "stuffs",
    "id": "st1234",
    "links": {
      "self": "/stuffs/st1234"
    },
    "attributes": {
      "name": "some stuff",
    },
    "relationships": {
      "account": [],
    }
  }

In this case, the account-relationsship is not included, and is empty, as can be seen here (or above):

"account": [],

When including the data by adding a include query parameter with the value account, you get this:

"account": {
  "data": {
    "type": "accounts",
    "id": "lb1959846"
  }
},

The behaviour that is causing the issues is when the relationship is empty, when there is no data for the relationship. I that case, this will be returned by yin:

"account": [],

This looks identical to what you get when you don't include the relationship at all. Therefor, it is impossible for a client to judge if the relationship has been empty, or if it has simply not been included.

In my case, my client warns the user if they are trying to use data from a relationship that has not been loaded. This make it impossible to know if the object has a relationship with an account, or if it's empty simply because the user choose not to include it.

This is in the specification here:
http://jsonapi.org/format/#fetching-relationships-responses-200

There are examples for both a to-one relationship and a to-many relationship.

If the relationship is included but empty, the data of the response should be like this for a to-one:

"account": {
  "data": null
}

and like this for a to-many:

"account": {
  "data": []
}

With this, a client would see that the data field is in the response and know that the relationship has been included. If the data is null or an empty array, it just means that the relationship is empty.

I have a working patch for this. I will try to create a pull-request out of it. It needs more sets of eyes.

Sorting always happens on primary key in resource

In the WoohooLabs\Yin\JsonApi\Schema\Data\CollectionData class a ksort is performed on the $ids.
I want to order the results the way I setup my SQL (using an 'order by') but this ksort is causing unexpected behaviour. Am I missing something?

Forcing api mime type ?

Hi @kocsismate,

jsonapi specs define the mime type application/vnd.api+json.

It could be interesting to force consumer to use this mime type, I mean return an HTTP 406 if not.

It let the developer use an other response formalism, for example msgpack ...

What do you think ?

Regards,

Possible bug in OffsetBasedPagination

From my tests I'm getting wrong results here: https://github.com/woohoolabs/yin/blob/master/src/JsonApi/Schema/Pagination/OffsetBasedPaginationLinkProviderTrait.php#L35

In case of 5 total items and limit 100, it will return a negative offset.
In case of 5 total items, offset = 0, limit = 1, it will return offset 3, limit 1, therefore missing the last item.

And here: https://github.com/woohoolabs/yin/blob/master/src/JsonApi/Schema/Pagination/OffsetBasedPaginationLinkProviderTrait.php#L39

With 5 total items, offset 4, limit 1, I get no prev link (should be offset 3, limit 1).

I'll try to check it out later on.

ResourceIdentifier::fromArray returning null not being handled gracefully

If you need to fetch a relationship from a request, you would normally do it like this:

$resource = $jsonApi->getRequest()->getResourceToOneRelationship('spaceship');

This returns a ToOneRelationShip-object, if the relationship is found, or null if it is not.

The getResourceToOneRelationship method in the Request class looks like this

public function getResourceToOneRelationship($relationship)
    {
        $data = $this->getResource();
        if (isset($data["relationships"][$relationship]["data"]) === false) {
            return null;
        }
        return new ToOneRelationship(ResourceIdentifier::fromArray($data["relationships"][$relationship]["data"]));
    }

The last line calls the fromArray method. The problem is that the fromArray method does this check:

if (isset($array["type"]) === false || isset($array["id"]) === false) {
            return null;
        }

So an invalid relationship returns null, but the ToOneRelationship object gets created anyway. I think it would be clearer if getResourceToOneRelationship returned null in this case.

To catch the case where the input is malformed, you would have to write code like this with the current code:

 $resource = $jsonApi->getRequest()->getResourceToOneRelationship('spaceship');
        if (isset($resource)) {
           $resourceIdentifier = $resource->getResourceIdentifier();
            if ( isset($resourceIdentifier) ) {
                //get the id from the resourceIdentifier
            }
       }

If you don't, you will very likely get an Fatal Error in php.

I would propose that getResourceToOneRelationship was changed to make sure that ResourceIdentifier:fromArray considers the data valid, something like this:

public function getResourceToOneRelationship($relationship)
    {
        $data = $this->getResource();

        if (isset($data["relationships"][$relationship]["data"]) === false) {
            return null;
        }

        $resourceIdentifier = ResourceIdentifier::fromArray($data["relationships"][$relationship]["data"]);

        if (isset($resourceIdentifier) === false) {
            return null;
        }

        return new ToOneRelationship($resourceIdentifier);
    }

With this in place, getResourceToOneRelationship would return null if the relationship didn't exist, or one of the fields type or id was missing.

The getResourceToManyRelationship would need to be fixed too. I'm not 100% sure on how though. Skip non valid relationships? Return null from the method if one of the identifiers are invalid? Rise some kind of exception? Exceptions could perhaps be used in the getResourceToOneRelationship case too? Some kind of malformed input exception.

I didn't consider this fully thought through, so i didn't create a PR. What do you think about all this?

ResourceNotFound should have 404 status (?)

Hello,

Currently the ResourceNotFound exception bears a 400 status.
I believe it would make more sense to make it a 404.
Or maybe there's a specific reason behind this?

Cheers

Improve docs

If you are a native or fluent English-speaker, please proofread the read me and let's make it more helpful and easy-to-read.

Body sent via POST is not retrievable

Hello,

Starting a project with current 2.0.2, I'm facing an issue when trying to send POST requests.
Basically the retrieved body ends up being empty, which causes fatal errors.

I've identified the issue to be coming from WoohooLabs\Yin\JsonApi\Request\Request::getParsedBody, I'll post a PR shortly.

Question about sorting of included resources by id

Hi,

I noticed, that in my JSONAPI response the included resources are sorted by id, instead by their original order.
After looking in the code I found out that this line sorts them by id.

I have a question, why is this behavior implemented? In my case I would like to have them sorted in the same way, in which they come from the DB and like they are sorted in the relationships data array. Am I missing something?

Thanks in advance!

Don't ignore attribute in hydrator if not present in the request

The Hydrator ignores attribute if they are not present in the request, the callable is never call.

This is annoying if an attribute is required for example.
I think it should be great to execute all the callable and let the developer decide what it should do, ignore the attribute, set it to null, throw an exception, etc.

I made a commit on my repo lunika@d695581

This is yet again a BC break. An example how ti use it :

    protected function getAttributeHydrator($user)
    {
        return [
            'firstname' => function ($user, $attributeValue, $data, $attribute, $isMissing) {
                if (true === $isMissing) {
                    throw new MissingMandatoryAttributeException($attribute);
                }

                $user['firstname'] = $attributeValue;

                return $user;
            },
            'lastname' => function ($user, $attributeValue, $data, $attribute, $isMissing) {
                if (false === $isMissing) {
                    $user['lastname'] = $attributeValue;
                }

                return $user;
            }
        ];
    }

OffsetPagination bug, offset and limit mixup

Hi,

It looks like $defaultOffset and $defaultLimit is sent in the wrong order here

...($this->getPagination(), $defaultLimit, $defaultOffset);
should be
...($this->getPagination(), $defaultOffset, $defaultLimit);

Allow to set options to the json_encode method

It should be great to configure a little bit how the json_encode method is used in the Serializer. Configure all the options and the depth.
You can maybe add this in your v2 roadmap ? :-)

Resource schema validating

Hello.

When you POST or PATCH "id" with integer value (for example {"id": 23}) the library generates system exception because of new stricts (strict_types=1) in file \WoohooLabs\Yin\JsonApi\Schema\ResourceIdentifier line 38.

Old version worked with integers because of autocasting in php. I think new version "must" generate "4XX Bad Request, id must be a string" (jsonapi 1.0 standard) or in fast way just to cast value to string, like:

line 38: $resourceIdentifier->setId((string)$array["id"]);

Anyway it's not cool to get 500 when the mistake is in client's requests.

Thanks for your work and library!

Using same temp stream in multiple requests

During api testing with Codeception I tried to test multiple routes in same test using @DataProvider. If I specified 1 route, for example:

/**
 * @param FunctionalTester $
 * @param Example $example
 * @dataProvider getRoutes
 */
public function testSomeRoute(FunctionalTester $I, Example $example): void
{
    $I->expect('Data is not empty');

    $I->sendGET($example['url']);
    $data = $I->grabDataFromResponseByJsonPath('$.data')[0];

    $I->assertNotEmpty($data);
}

protected function getRoutes(): array
{
    return [
      ['url' => '/some/route'],
    ];
}

test will work as expected.

After adding 2 or more routes in data provider, for example:

protected function getRoutes(): array
{
    return [
        ['url' => '/some/route'],
        ['url' => '/some/other/route'],
        ['url' => '/example/route'],
    ];
}

second and third route test will fail because invalid json was returned.

After some debugging I found out that same php://temp stream is being used for writing response of every route. Response of the second route will be written over response of the first route and if the second response is shorter than the first, part of the first response will still be returned and fail the test because of invalid format.

Fatal on book-rel example

I'm trying to run the example:

?example=book-rel&id=1&rel=authors

However I'm encountering a fatal:

PHP Catchable fatal error:  Argument 1 passed to WoohooLabs\\Yin\\Examples\\Book\\JsonApi\\Resource\\PublisherResourceTransformer::__construct() must be an instance of WoohooLabs\\Yin\\Examples\\Book\\JsonApi\\Resource\\RepresentativeResourceTransformer, none given, called in [...]/yin/examples/Book/Action/GetBookRelationshipsAction.php on line 36 and defined in [...]/yin/examples/Book/JsonApi/Resource/PublisherResourceTransformer.php on line 17

Example how to grab a sub-resource.

It seems you have examples on how to do:

/books/{id}

and

/books/{id}/relationships/authors

But not:

/books/{id}/authors

Unless I'm missing something? Do you natively support this type of call?

Default value will be used it the value of the request body data field is null

I just had a look at this commit:
c2ace26#diff-8b9b082f8f14fc68d1683252b988283eR486

Won't that cause an issue when you send null as the value? Like in this case: http://jsonapi.org/format/#crud-updating-to-one-relationships

PATCH /articles/1/relationships/author HTTP/1.1
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json

{
  "data": null
}

Would perhaps be better to use the array_key_exists method.

How to skip a level in a multi-level relationship

If I want to include a sub-level but skip the intermediary level, it doesn't seem to work.

However I want to preface this with two things:

  1. I may be reading the jsonapi spec incorrectly on this (I don't know if there's a good concrete example)
  2. I may be misunderstanding how to use woohoolabs/yin

What I want to do in the following example is to include comments.authors, but not comments. I'm presuming (and here where I could be wrong, so feel free to correct me), but I'm guessing that the right way to do this, according to the spec is simply:

include=comments.authors

However with yin, it seems that I get back both the comments and the authors, instead of just the authors.

Bug in request header validation

Following line in "protected function isValidMediaTypeHeader" in src/JsonApi/Request/Request.php
return strpos($header, "application/vnd.api+json") === false || $header === "application/vnd.api+json";
returns true even if the header is wrong. It should be:
return strpos($header, "application/vnd.api+json") !== false || $header === "application/vnd.api+json";

And i think the second statement is not necessary.
return strpos($header, "application/vnd.api+json") !== false;
should be enough.

Links for paginations should include filter and sorting parameters

Hi,
this is basically an improvement.
I think it would be really cool if the sorting and filter params would automatically be included in the links of the pagination. Basically a pagination is useless if those parameters are not included. Because those values are already available inside the lib, it should be possible. For sure one can solve this in the environment, but it would be a nice improvement of your lib.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.