Skip to content

Commit

Permalink
Big 💥
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod committed Nov 5, 2018
0 parents commit a498643
Show file tree
Hide file tree
Showing 23 changed files with 1,049 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/vendor/
/composer.lock
/.phpcs-cache
/phpcs.xml
/phpstan.neon
/phpunit.xml
32 changes: 32 additions & 0 deletions .scrutinizer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
build:
nodes:
analysis:
environment:
php:
version: 7.2
cache:
disabled: false
directories:
- ~/.composer/cache
project_setup:
override: true
tests:
override:
- php-scrutinizer-run
- phpcs-run
dependencies:
override:
- composer install --no-interaction --prefer-dist

checks:
php:
code_rating: true

tools:
external_code_coverage: true

build_failure_conditions:
- 'elements.rating(<= C).new.exists' # No new classes/methods with a rating of C or worse allowed
- 'issues.severity(>= MAJOR).new.exists' # New issues of major or higher severity
- 'project.metric_change("scrutinizer.test_coverage", < 0)' # Code Coverage decreased from previous inspection
- 'patches.label("Unused Use Statements").new.exists' # No new unused imports patches allowed
47 changes: 47 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
dist: trusty
language: php
sudo: false

cache:
directories:
- $HOME/.composer/cache

php:
- 7.2
- nightly

before_install:
- composer self-update
- mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{,.disabled} || echo "xdebug not available"

install:
- travis_retry composer update --prefer-dist

script: ./vendor/bin/phpunit

jobs:
include:
- stage: Test
env: COVERAGE
php: 7.2
before_script:
- mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{.disabled,}
- if [[ ! $(php -m | grep -si xdebug) ]]; then echo "xdebug required for coverage"; exit 1; fi
script:
- ./vendor/bin/phpunit --coverage-clover ./build/logs/clover.xml
after_script:
- wget https://github.com/scrutinizer-ci/ocular/releases/download/1.5.2/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml

- stage: Code Quality
env: CODING_STANDARD
php: 7.2
script:
- ./vendor/bin/phpcs

- stage: Code Quality
env: STATIC_ANALYSIS
php: 7.2
script:
- ./vendor/bin/phpstan analyse

19 changes: 19 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2018 Šimon Podlipský <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
189 changes: 189 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
# PHP GraphQL Utils for graphql-php

[![Build Status](https://travis-ci.org/simPod/GraphQL-Utils.svg)](https://travis-ci.org/simPod/GraphQL-Utils)
[![Downloads](https://poser.pugx.org/simpod/graphql-utils/d/total.svg)](https://packagist.org/packages/simpod/graphql-utils)
[![Packagist](https://poser.pugx.org/simpod/graphql-utils/v/stable.svg)](https://packagist.org/packages/simpod/graphql-utils)
[![Licence](https://poser.pugx.org/simpod/graphql-utils/license.svg)](https://packagist.org/packages/simpod/graphql-utils)
[![Quality Score](https://scrutinizer-ci.com/g/simPod/GraphQL-Utils/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/simPod/GraphQL-Utils)
[![Code Coverage](https://scrutinizer-ci.com/g/simPod/GraphQL-Utils/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/simPod/GraphQL-Utils)
[![GitHub Issues](https://img.shields.io/github/issues/simPod/GraphQL-Utils.svg?style=flat-square)](https://github.com/simPod/GraphQL-Utils/issues)


## Contents
- [Installation](#installation)
- [Features](#features)
- [Schema Builders](#schema-builders)
- [Types](#types)
- [Error Handling](#error-handling)

## Installation

Add as [Composer](https://getcomposer.org/) dependency:

```sh
composer require simpod/graphql-utils
```

## Features

### Schema Builders

Instead of defining your schema as an array, use can use more objective-oriented approach.
This library provides set of strictly typed builders that help you build your schema.

#### ObjectBuilder and FieldBuilder

✔️ Standard way with `webonyx/graphql-php`

```php
$userType = new ObjectType([
'name' => 'User',
'description' => 'Our blog visitor',
'fields' => [
'firstName' => [
'type' => Type::string(),
'description' => 'User first name'
],
'email' => Type::string()
]
]);
```

✨ The same can be produced in objective way

```php
use SimPod\GraphQLUtils\Builder\ObjectBuilder;

...

$userType = ObjectBuilder::create('User')
->setDescription('Our blog visitor')
->setFields([
FieldBuilder::create('firstName', Type::string())
->setDescription('User first name')
->build(),
FieldBuilder::create('email', Type::string())
->build(),
])
->build();

```

#### EnumBuilder

✔️ Standard way with `webonyx/graphql-php`

```php
use SimPod\GraphQLUtils\Builder\EnumBuilder;

...

$episodeEnum = new EnumType([
'name' => 'Episode',
'description' => 'One of the films in the Star Wars Trilogy',
'values' => [
'NEWHOPE' => [
'value' => 4,
'description' => 'Released in 1977.'
],
'EMPIRE' => [
'value' => 5,
'description' => 'Released in 1980.'
],
'JEDI' => [
'value' => 6,
'description' => 'Released in 1983.'
],
]
]);
```

✨ The same can be produced in objective way

```php
$episodeEnum = EnumBuilder::create('Episode')
->setDescription('One of the films in the Star Wars Trilogy')
->addValue(4, 'NEWHOPE', 'Released in 1977.')
->addValue(5, 'EMPIRE', 'Released in 1980.')
->addValue(6, 'JEDI', 'Released in 1983.')
->build();
```

### Types

#### 🕰️ DateTime

scalar type that produces `scalar DateTime` in your schema.

[`SimPod\GraphQLUtils\Type\DateTimeType`](https://github.com/simPod/GraphQL-Utils/blob/master/src/Type/DateTimeType.php)

### Error Handling

Extending your exception with `SimPod\GraphQLUtils\Error\Error` forces you to implement `getType()` method.

Example Error class

```php
use SimPod\GraphQLUtils\Error\Error;
use function sprintf;

final class InvalidCustomerIdProvided extends Error
{
public const TYPE = 'INVALID_CUSTOMER_ID_PROVIDED';

public static function noneGiven() : self
{
return new self('No CustomerId provided');
}

public function getType() : string
{
return self::TYPE;
}

public function isClientSafe() : bool
{
return true;
}
}
```

Create your formatter

```php
use SimPod\GraphQLUtils\Error\FormattedError;

$formatError = function formatError(Error $error) : array
{
if (!$error->isClientSafe()) {
// eg. log error
}

return FormattedError::createFromException($error);
};

$errorFormatterCallback = static function (Error $error) use ($formatError) : array {
return $formatError($error);
};

$config = GraphQL::executeQuery(/* $args */)
...
->setErrorFormatter($errorFormatterCallback)
->setErrorsHandler(
static function (array $errors, callable $formatter) : array {
return array_map($formatter, $errors);
}
)
```

Error types will then be provided in your response so client can easier identify the error type

```json
{
"errors": [
{
"type": "INVALID_CUSTOMER_ID_PROVIDED",
"message": "No CustomerId provided",
"category": "graphql",
...
```
36 changes: 36 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "simpod/graphql-utils",
"description": "GraphQL Utils for graphql-php",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Simon Podlipsky",
"email": "[email protected]"
}
],
"config": {
"sort-packages": true
},
"require": {
"php": "^7.2",
"webonyx/graphql-php": "^0.12"
},
"require-dev": {
"doctrine/coding-standard": "^5.0",
"phpstan/phpstan": "^0.10.3",
"phpstan/phpstan-phpunit": "^0.10.0",
"phpstan/phpstan-strict-rules": "^0.10.1",
"phpunit/phpunit": "^7.0"
},
"autoload": {
"psr-4": {
"SimPod\\GraphQLUtils\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"SimPod\\GraphQLUtils\\Tests\\": "tests/"
}
}
}
15 changes: 15 additions & 0 deletions phpcs.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0"?>
<ruleset>
<arg name="basepath" value="."/>
<arg name="extensions" value="php"/>
<arg name="parallel" value="80"/>
<arg name="cache" value=".phpcs-cache"/>
<arg name="colors"/>

<!-- Ignore warnings, show progress of the run and show sniff names -->
<arg value="nps"/>

<file>src</file>

<rule ref="Doctrine"/>
</ruleset>
13 changes: 13 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
parameters:
level: max
paths:
- %currentWorkingDirectory%/src
- %currentWorkingDirectory%/tests
tmpDir: %currentWorkingDirectory%/var/phpstan
ignoreErrors:
- "~Method SimPod\\\\GraphQLUtils\\\\Error\\\\FormattedError::createFromException\\(\\) has parameter \\$\\w+ with no typehint specified~"

includes:
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
- vendor/phpstan/phpstan-strict-rules/rules.neon
32 changes: 32 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>

<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
colors="true"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<logging>
<log
showOnlySummary="true"
showUncoveredFiles="true"
target="php://stdout"
type="coverage-text"
/>
<log type="coverage-clover" target="temp/clover.xml"/>
<log type="coverage-html" target="temp/coverage-html"/>
</logging>
</phpunit>
Loading

0 comments on commit a498643

Please sign in to comment.