Download the PHP package spawnia/sailor without Composer

On this page you can find all versions of the php package spawnia/sailor. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package sailor

[![CI Status](https://github.com/spawnia/sailor/workflows/Continuous%20Integration/badge.svg)](https://github.com/spawnia/sailor/actions) [![codecov](https://codecov.io/gh/spawnia/sailor/branch/master/graph/badge.svg)](https://codecov.io/gh/spawnia/sailor) [![Latest Stable Version](https://poser.pugx.org/spawnia/sailor/v/stable)](https://packagist.org/packages/spawnia/sailor) [![Total Downloads](https://poser.pugx.org/spawnia/sailor/downloads)](https://packagist.org/packages/spawnia/sailor) A typesafe GraphQL client for PHP

Motivation

GraphQL provides typesafe API access through the schema definition each server provides through introspection. Sailor leverages that information to enable an ergonomic workflow and reduce type-related bugs in your code.

The native GraphQL query language is the most universally used tool to formulate GraphQL queries and works natively with the entire ecosystem of GraphQL tools. Sailor takes the plain queries you write and generates executable PHP code, using the server schema to generate typesafe operations and results.

Installation

Install Sailor through composer by running:

composer require spawnia/sailor

If you want to use the built-in default Client (see Client implementations):

composer require guzzlehttp/guzzle

If you want to use the PSR-18 Client and don't have PSR-17 Request and Stream factory implementations (see Client implementations):

composer require nyholm/psr7

Configuration

Run vendor/bin/sailor to set up the configuration. A file called sailor.php will be created in your project root.

You can take a look at the example configuration to see what options are available for configuration: sailor.php.

If you would like to use multiple configuration files, specify which file to use through the -c/--config option.

It is quite useful to include dynamic values in your configuration. You might use PHP dotenv to load environment variables (run composer require vlucas/phpdotenv if you do not have it installed already.).

Client implementations

Sailor provides a few built-in clients:

You can bring your own by implementing the interface Spawnia\Sailor\Client.

Dynamic clients

You can configure clients dynamically for specific operations or per request:

Custom types

Custom scalars are commonly serialized as strings, but may also use other representations. Without knowing about the contents of the type, Sailor can not do any conversions or provide more accurate type hints, so it uses mixed.

Enums are only supported from PHP 8.1. Many projects simply used scalar values or an implementation that approximates enums through some kind of value class. Sailor is not opinionated and generates enums as a class with string constants and does no conversion - useful but not perfect. For an improved experience, it is recommended to customize the enum generation/conversion.

Overwrite EndpointConfig::configureTypes() to specialize how Sailor deals with the types within your schema. See examples/custom-types.

Error conversion

Errors sent within the GraphQL response must follow the response errors specification. Sailor converts the plain stdClass obtained from decoding the JSON response into instances of \Spawnia\Sailor\Error\Error by default.

If one of your endpoints returns structured data in extensions, you can customize how the plain errors are decoded into class instances by overwriting EndpointConfig::parseError().

Usage

Introspection

Run vendor/bin/sailor introspect to update your schema with the latest changes from the server by running an introspection query. As an example, a very simple server might result in the following file being placed in your project:

Define operations

Put your queries and mutations into .graphql files and place them anywhere within your configured project directory. You are free to name and structure the files in any way. Let's query the example schema from above:

You must give all your operations unique names, the following example is invalid:

Generate code

Run vendor/bin/sailor to generate PHP code for your operations. For the example above, Sailor will generate a class called HelloSailor, place it in the configured namespace and write it to the configured location.

There are additional generated classes that represent the results of calling the operations. The plain data from the server is wrapped up and contained within those value classes, so you can access them in a typesafe way.

Execute queries

You are now set up to run a query against the server, just call the execute() function of the new query class:

The returned $result is going to be a class that extends \Spawnia\Sailor\Result and holds the decoded response returned from the server. You can just grab the $data, $errors or $extensions off of it:

Error handling

You can ensure your query returned the proper data and contained no errors:

If you don't need any data, but want to ensure a mutation succeeded:

Queries with arguments

Your generated operation classes will be annotated with the arguments your query defines.

Inputs can be built up incrementally:

If you are using PHP 8, instantiation with named arguments can be quite useful to ensure your input is completely filled:

Partial inputs

GraphQL often uses a pattern of partial inputs - the equivalent of an HTTP PATCH. Consider the following input:

Suppose we allow instantiation in PHP with the following implementation:

The following call:

Should produce the following JSON payload:

However, from within make() there is no way to differentiate between an explicitly passed optional named argument and one that has been assigned the default value. Thus, the resulting JSON payload will unintentionally modify firstOptional too, erasing whatever value it previously held.

A naive solution to this would be to filter out any argument that is null. However, we would also like to be able to explicitly set the first optional value to null. The following call should result in the previous JSON payload.

In order to generate partial inputs by default, optional named arguments have a special default value:

In the unlikely case where you need to pass exactly this value, you can assign it directly:

Events

Sailor calls EndpointConfig::handleEvent() with the following events during the execution lifecycle:

  1. StartRequest: Fired after calling execute() on an Operation, before invoking the client.
  2. ReceiveResponse: Fired after receiving a GraphQL response from the client.

PHP keyword collisions

Since GraphQL uses a different set of reserved keywords, names of fields or types may collide with PHP keywords. Sailor prevents illegal usages of those names in generated code by prefixing them with a single underscore _.

Testing

Sailor provides first class support for testing by allowing you to mock operations.

Setup

It is assumed you are using PHPUnit and Mockery.

composer require --dev phpunit/phpunit mockery/mockery

Make sure your test class - or one of its parents - uses the following traits:

Otherwise, mocks are not reset between test methods, you might run into very confusing bugs.

Mock results

Mocks are registered per operation class:

When registered, the mock captures all calls to HelloSailor::execute(). Use it to build up expectations for what calls it should receive and mock returned results:

Subsequent calls to ::mock() will return the initially registered mock instance.

You can also simulate a result with errors:

For PHP 8 users, it is recommended to use named arguments to build complex mocked results:

Integration

If you want to perform integration testing for a service that uses Sailor without actually hitting an external API, you can swap out your client with the Log client. It writes all requests made through Sailor to a file of your choice.

The Log client can not know what constitutes a valid response for a given request, so it always responds with an error.

Each request goes on a new line and contains a JSON string that holds the query and variables:

This allows you to perform assertions on the calls that were made. The Log client offers a convenient method of reading the requests as structured data:

To clean up the log after performing tests, use Log::clear().

Examples

You can find examples of how a project would use Sailor within examples.

Changelog

See CHANGELOG.md.

Contributing

See CONTRIBUTING.md.

License

This package is licensed using the MIT License.


All versions of sailor with dependencies

PHP Build Version
Package Version
Requires php Version ^7.4 || ^8
ext-json Version *
nette/php-generator Version ^3.6.7 || ^4
psr/http-client Version ^1
symfony/console Version ^5 || ^6 || ^7
symfony/var-exporter Version ^5.3 || ^6 || ^7
thecodingmachine/safe Version ^1 || ^2
webonyx/graphql-php Version ^14.11.3 || ^15
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package spawnia/sailor contains the following files

Loading the files please wait ....