PHP code example of woohoolabs / yang

1. Go to this page and download the library: Download woohoolabs/yang library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

woohoolabs / yang example snippets


use GuzzleHttp\Psr7\Request;
use WoohooLabs\Yang\JsonApi\Request\JsonApiRequestBuilder;

// Instantiate an empty PSR-7 request, note that the default HTTP method must be provided
$request = new Request('GET', '');

// Instantiate the request builder
$requestBuilder = new JsonApiRequestBuilder($request);

// Setup the request with general properties
$requestBuilder
    ->setProtocolVersion("1.1")
    ->setMethod("GET")
    ->setUri("https://www.example.com/api/users")
    ->setHeader("Accept-Charset", "utf-8");

// Setup the request with JSON:API specific properties
$requestBuilder
    ->setJsonApiFields(                                      // To define sparse fieldset
        [
            "users" => ["first_name", "last_name"],
            "address" => ["country", "city", "postal_code"]
        ]
    )
    ->setJsonApiIncludes(                                    // To include related resources
        ["address", "friends"]
    )
    ->setJsonApiIncludes(                                    // Or you can pass a string instead
        "address,friends"
    )
    ->setJsonApiSort(                                        // To sort resource collections
        ["last_name", "first_name"]
    )
    ->setJsonApiPage(                                        // To paginate the primary data
        ["number" => 1, "size" => 100]
    )
    ->setJsonApiFilter(                                      // To filter the primary data
        ["first_name" => "John"]
    )
    ->addJsonApiAppliedProfile(                              // To add a profile to the request (JSON:API 1.1 feature)
        ["https://example.com/profiles/last-modified"]
    )
    ->addJsonApiRequestedProfile(                            // To request the server to apply a profile (JSON:API 1.1 feature)
        ["https://example.com/profiles/last-modified"]
    )
    ->addJsonApiRequiredProfile(                             // To 

$request = new Request('GET', '');
$request = $request
    ->withProtocolVersion("1.1")
    ->withUri(new Uri("https://example.com/api/users?fields[users]=first_name,last_name"))
    ->withHeader("Accept", "application/vnd.api+json")
    ->withHeader("Content-Type", "application/vnd.api+json");

use Http\Adapter\Guzzle6\Client;

// Instantiate the Guzzle HTTP Client
$guzzleClient = Client::createWithConfig([]);

// Instantiate the syncronous JSON:API Client
$client = new JsonApiClient($guzzleClient);

// Send the request syncronously to retrieve the response
$response = $client->sendRequest($request);

// Instantiate the asyncronous JSON:API Client
$client = new JsonApiAsyncClient($guzzleClient);

// Send the request asyncronously to retrieve a promise
$promise = $client->sendAsyncRequest($request);

// Send multiple request asyncronously to retrieve an array of promises
$promises = $client->sendConcurrentAsyncRequests([$request, $request]);

// Instantiate a JSON:API response object from a PSR-7 response object with the default deserializer
$response = new JsonApiResponse($psr7Response);

// Checks if the response doesn't contain any errors
$isSuccessful = $response->isSuccessful();

// Checks if the response doesn't contain any errors, and has the status codes listed below
$isSuccessful = $response->isSuccessful([200, 202]);

// The same as the isSuccessful() method, but also ensures the response contains a document
$isSuccessfulDocument = $response->isSuccessfulDocument();

// Checks if the response contains a JSON:API document
$hasDocument = $response->hasDocument();

// Retrieves and deserializes the JSON:API document in the response body
$document = $response->document();

// Retrieves the "jsonapi" member as a JsonApiObject instance
$jsonApi = $document->jsonApi();

$jsonApiVersion = $jsonApi->version();
$jsonApiMeta = $jsonApi->meta();

// Checks if the document has the "meta" member
$hasMeta = $document->hasMeta();

// Retrieves the "meta" member as an array
$meta = $document->meta();

// Checks if the document has any links
$hasLinks = $document->hasLinks();

// Retrieves the "links" member as a DocumentLinks object
$links = $document->links();

// Checks if the document has any errors
$hasErrors = $document->hasErrors();

// Counts the number of errors in the document
$errorCount = $document->errorCount();

// Retrieves the "errors" member as an array of Error objects
$errors = $document->errors();

// Retrieves the first error as an Error object or throws an exception if it is missing
$firstError = $document->error(0);

// Checks if the document contains a single resource as its primary data
$isSingleResourceDocument = $document->isSingleResourceDocument();

// Checks if the document contains a collection of resources as its primary data
$isResourceCollectionDocument = $document->isResourceCollectionDocument();

// Checks if the document contains any primary data
$hasPrimaryData = $document->hasAnyPrimaryResources();

// Returns the primary resource as a ResourceObject instance if the document is a single-resource document
// or throws an exception otherwise or when the document is empty
$primaryResource = $document->primaryResource();

// Returns the primary resources as an array of ResourceObject instances if the document is a collection document
// or throws an exception otherwise
$primaryResources = $document->primaryResources();

// Checks if there are any 

// Checks if the "self" link is present
$hasSelf = $links->hasSelf();

// Returns the "self" link as a Link object or throws an exception if it is missing
$selfLink = $links->self();

// Checks if the "related" link is present
$hasRelated = $links->hasRelated();

// Returns the "related" link as a Link object or throws an exception if it is missing
$relatedLink = $links->related();

// Checks if the "first" link is present
$hasFirst = $links->hasFirst();

// Returns the "first" link as a Link object or throws an exception if it is missing
$firstLink = $links->first();

// Checks if the "last" link is present
$hasLast = $links->hasLast();

// Returns the "last" link as a Link object or throws an exception if it is missing
$lastLink = $links->last();

// Checks if the "prev" link is present
$hasPrev = $links->hasPrev();

// Returns the "prev" link as a Link object or throws an exception if it is missing
$prevLink = $links->prev();

// Checks if the "next" link is present
$hasNext = $links->hasNext();

// Returns the "next" link as a Link object or throws an exception if it is missing
$nextLink = $links->next();

// Checks if a specific link is present
$hasLink = $links->hasLink("next");

// Returns a specific link as a Link object or throws an exception if it is missing
$link = $links->link("next");

// Checks if the there is any profile defined
$hasProfiles = $links->hasAnyProfiles();

// Retrieves the profiles as an array of ProfileLink objects
$profiles = $links->profiles();

// Checks if there is a specific profile defined
$hasProfile = $links->hasProfile("https://example.com/profiles/last-modified");

// Retrieves a specific profile as a ProfileLink object
$profile = $links->profile("https://example.com/profiles/last-modified");

// Returns the "id" member of the error
$id = $firstError->id();

// Checks if the error has the "meta" member
$hasMeta = $firstError->hasMeta();

// Retrieves the "meta" member as an array
$meta = $firstError->meta();

// Checks if the error has any links
$hasLinks = $firstError->hasLinks();

// Retrieves the "links" member as an ErrorLinks object
$links = $firstError->links();

// Returns the "status" member
$status = $firstError->status();

// Returns the "code" member
$code = $firstError->code();

// Returns the "title" member
$title = $firstError->title();

// Returns the "detail" member
$detail = $firstError->detail();

// Checks if the error has the "source" member
$hasSource = $firstError->hasSource();

// Returns the "source" member as an ErrorSource object
$source = $firstError->source();

// Returns the type of the resource
$type = $primaryResource->type();

// Returns the id of the resource
$id = $primaryResource->id();

// Checks if the resource has the "meta" member
$hasMeta = $primaryResource->hasMeta();

// Returns the "meta" member as an array
$meta = $primaryResource->meta();

// Checks if the resource has any links
$hasLinks = $primaryResource->hasLinks();

// Returns the "links" member as a ResourceLinks object
$links = $primaryResource->links();

// Returns the attributes of the resource as an array
$attributes = $primaryResource->attributes();

// Returns the ID and attributes of the resource as an array
$idAndAttributes = $primaryResource->idAndAttributes();

// Checks if the resource has a specific attribute
$hasFirstName = $primaryResource->hasAttribute("first_name");

// Returns an attribute of the resource or null if it is missing
$firstName = $primaryResource->attribute("first_name");

// Returns an attribute of the resource or the default value if it is missing
$lastName = $primaryResource->attribute("last_name", "");

// Returns all relationships of the resource as an array of Relationship objects
$relationships = $primaryResource->relationships();

// Checks if the resource has a specific relationship
$hasAddress = $primaryResource->hasRelationship("address");

// Returns a relationship of the resource as a Relationship object or throws an exception if it is missing
$relationship = $primaryResource->relationship("address");

// Checks if it is a to-one relationship
$isToOneRelationship = $relationship->isToOneRelationship();

// Checks if it is a to-many relationship
$isToManyRelationship = $relationship->isToManyRelationship();

// Returns the name of the relationship
$name = $relationship->name();

// Checks if the relationship has the "meta" member
$hasMeta = $relationship->hasMeta();

// Returns the "meta" member of the relationship as an array
$meta = $relationship->meta();

// Returns the "links" member of the relationship as a RelationshipLinks object
$links = $relationship->links();

// Returns the first resource linkage of the relationship as an array (e.g.: ["type" => "address", "id" => "123"])
// or null if there isn't any related data
$resourceLinkage = $relationship->firstResourceLink();

// Returns the resource linkage as an array of array (e.g.: [["type" => "address", "id" => "123"]])
$resourceLinkage = $relationship->resourceLinks();

// Checks if a specific resource object is 

$dogResource = $response->document()->primaryResource();

$breedName = $dogResource->relationship("breed")->resource()->attribute("name");

$dogResource = $response->document()->primaryResource();

$dog = new stdClass();
$dog->name = $dogResource->attribute("name");
$dog->age = $dogResource->attribute("age");
$dog->breed = $dogResource->relationship("breed")->resource()->attribute("name");
foreach ($dogResource->relationship("owners")->resources() as $ownerResource) {
    $owner = new stdClass();
    $owner->name = $ownerResource->attribute("name");

    $addressResource = $ownerResource->relationship("address")->resource();
    $owner->address = new stdClass();
    $owner->address->city = $addressResource->attribute("city");
    $owner->address->addressLine = $addressResource->attribute("city");

    $dog->owners[] = $owner;
}

// Check if hydration is possible
if ($document->hasAnyPrimaryResources() === false) {
    return;
}

// Hydrate the document to an stdClass
$hydrator = new ClassDocumentHydrator();
$dog = $hydrator->hydrateSingleResource($response->document());

echo "Dog:\n";
echo "Name : " . $dog->name . "\n";
echo "Breed: " . $dog->breed->name . "\n\n";

echo "Owners:\n";
foreach ($dog->owners as $owner) {
    echo "Name   : " . $dog->owner->name . "\n";
    echo "Address: " . $dog->owner->address->city . ", " . $dog->owner->address->addressLine . "\n";
    echo "------------------\n";
}

// Check if hydration is possible
if ($document->isSingleResourceDocument()) {
    return;
}

// Hydrate the document to an array of stdClass
$hydrator = new ClassDocumentHydrator();
$dogs = $hydrator->hydrateCollection($response->document());

// Instantiate a PSR-7 request
$request = new Request();

// Instantiate your custom serializer
$mySerializer = new MyCustomSerializer();

// Instantiate the request builder with a custom serializer
$requestBuilder = new JsonApiRequestBuilder($request, $mySerializer);

use Http\Adapter\Guzzle7\Client;

// Instantiate the Guzzle HTTP Client
$guzzleClient = Client::createWithConfig([]);

// Instantiate your custom deserializer
$myDeserializer = new MyCustomDeserializer();

// Instantiate the syncronous JSON:API Client with a custom deserializer
$syncClient = new JsonApiClient($guzzleClient, $myDeserializer);

// Instantiate the asyncronous JSON:API Client with a custom deserializer
$asyncClient = new JsonApiAsyncClient($guzzleClient, $myDeserializer);

// Instantiate a JSON:API response from a PSR-7 response with a custom deserializer
$response = new JsonApiResponse($psr7Response, new MyCustomDeserializer());