Skip to content

SF 6 support #166

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jun 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ jobs:
name: test
strategy:
matrix:
install-args: ['', '--prefer-lowest']
php-version: ['7.4', '8.0']
install-args: ['']
php-version: ['8.1']
fail-fast: false
steps:
# Cancel previous runs of the same branch
Expand Down
11 changes: 0 additions & 11 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,10 @@ matrix:
- php: 8.1
env: PHPSTAN=true COVERAGE=true PHPUNIT_FLAGS="-v --coverage-text"

- php: 8.0

# Test the oldest possible release - SF 5.4, PHP 7.4, without security-bundle
- php: 7.4
env: PHPSTAN=true COMPOSER1=true TESTNOSECURITYBUNDLE=true COMPOSER_FLAGS="--prefer-stable --prefer-lowest"

allow_failures:
# Minimum supported dependencies with the latest and oldest PHP version
- php: 8.1
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" SYMFONY_DEPRECATIONS_HELPER="weak_vendors"
- php: 7.4
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" SYMFONY_DEPRECATIONS_HELPER="weak_vendors"
# Dev-master is allowed to fail.
- env: STABILITY="dev"

Expand All @@ -39,10 +31,7 @@ before_install:
- if ! [ -v "$DEPENDENCIES" ]; then composer require --no-update ${DEPENDENCIES}; fi;

install:
# To be removed when this issue will be resolved: https://github.com/composer/composer/issues/5355
- if [[ "$COMPOSER_FLAGS" == *"--prefer-lowest"* ]]; then composer update --prefer-dist --no-interaction --prefer-stable --quiet; fi
- composer update ${COMPOSER_FLAGS} --prefer-dist --no-interaction
#- ./vendor/bin/simple-phpunit install

script:
- composer validate --strict --no-check-lock
Expand Down
39 changes: 14 additions & 25 deletions Command/DumpSchemaCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

namespace TheCodingMachine\GraphQLite\Bundle\Command;

use GraphQL\Type\Definition\TypeWithFields;
use GraphQL\Type\Schema as TypeSchema;
use GraphQL\Utils\SchemaPrinter;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
Expand All @@ -16,10 +17,9 @@
/**
* Shamelessly stolen from Api Platform
*/
#[AsCommand('graphqlite:dump-schema')]
class DumpSchemaCommand extends Command
{
protected static $defaultName = 'graphqlite:dump-schema';

/**
* @var Schema
*/
Expand All @@ -43,10 +43,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);

// Trying to guarantee deterministic order
$this->sortSchema();

$schemaExport = SchemaPrinter::doPrint($this->schema);
$schemaExport = SchemaPrinterForGraphQLite::doPrint($this->schema, ['sortTypes' => true]);

$filename = $input->getOption('output');
if (\is_string($filename)) {
Expand All @@ -58,24 +55,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int

return 0;
}
}

private function sortSchema(): void
{
$config = $this->schema->getConfig();

$refl = new \ReflectionProperty(TypeWithFields::class, 'fields');
$refl->setAccessible(true);

if ($config->query) {
$fields = $config->query->getFields();
ksort($fields);
$refl->setValue($config->query, $fields);
}
class SchemaPrinterForGraphQLite extends SchemaPrinter {

if ($config->mutation) {
$fields = $config->mutation->getFields();
ksort($fields);
$refl->setValue($config->mutation, $fields);
}
protected static function hasDefaultRootOperationTypes(TypeSchema $schema): bool
{
return $schema->getQueryType() === $schema->getType('Query')
&& $schema->getMutationType() === $schema->getType('Mutation')
// Commenting this out because graphqlite cannot map Subscription type
// && $schema->getSubscriptionType() === $schema->getType('Subscription');
;
}
}
}
3 changes: 3 additions & 0 deletions Controller/GraphQLiteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ public function handleRequest(Request $request): Response
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON received in POST body: '.json_last_error_msg());
}
if (!is_array($parsedBody)){
throw new \RuntimeException('Expecting associative array from request, got ' . gettype($parsedBody));
}
$psr7Request = $psr7Request->withParsedBody($parsedBody);
}

Expand Down
3 changes: 3 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

class Configuration implements ConfigurationInterface
{
/**
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('graphqlite');
Expand Down
30 changes: 24 additions & 6 deletions DependencyInjection/GraphQLiteCompilerPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use TheCodingMachine\GraphQLite\Mappers\StaticClassListTypeMapperFactory;
use Webmozart\Assert\Assert;
use function assert;
use function class_exists;
use Doctrine\Common\Annotations\AnnotationReader as DoctrineAnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
Expand Down Expand Up @@ -75,18 +76,18 @@ public function process(ContainerBuilder $container): void
{
$reader = $this->getAnnotationReader();
$cacheDir = $container->getParameter('kernel.cache_dir');
Assert::string($cacheDir);
assert(is_string($cacheDir));
$this->cacheDir = $cacheDir;
//$inputTypeUtils = new InputTypeUtils($reader, $namingStrategy);

// Let's scan the whole container and tag the services that belong to the namespace we want to inspect.
$controllersNamespaces = $container->getParameter('graphqlite.namespace.controllers');
Assert::isIterable($controllersNamespaces);
$typesNamespaces = $container->getParameter('graphqlite.namespace.types');
Assert::isIterable($typesNamespaces);
assert(is_iterable($controllersNamespaces));
assert(is_iterable($typesNamespaces));

$firewallName = $container->getParameter('graphqlite.security.firewall_name');
Assert::string($firewallName);
assert(is_string($firewallName));
$firewallConfigServiceName = 'security.firewall.map.config.'.$firewallName;

// 2 seconds of TTL in environment mode. Otherwise, let's cache forever!
Expand Down Expand Up @@ -128,7 +129,11 @@ public function process(ContainerBuilder $container): void

if ($disableLogin === false) {
// Let's do some dark magic. We need the user provider. We need its name. It is stored in the "config" object.
$provider = $container->findDefinition('security.firewall.map.config.'.$firewallName)->getArgument(5);
$providerConfigKey = 'security.firewall.map.config.'.$firewallName;
$provider = $container->findDefinition($providerConfigKey)->getArgument(5);
if (!is_string($provider)){
throw new GraphQLException('Expecting to find user provider name from ' . $providerConfigKey);
}

$container->findDefinition(LoginController::class)->setArgument(0, new Reference($provider));

Expand Down Expand Up @@ -157,7 +162,7 @@ public function process(ContainerBuilder $container): void
// ServerConfig rules
$serverConfigDefinition = $container->findDefinition(ServerConfig::class);
$rulesDefinition = [];
if ($container->getParameter('graphqlite.security.introspection') === false) {
if ($container->getParameter('graphqlite.security.disableIntrospection')) {
$rulesDefinition[] = $container->findDefinition(DisableIntrospection::class);
}

Expand Down Expand Up @@ -191,6 +196,9 @@ public function process(ContainerBuilder $container): void
// Let's register the mapping with UserInterface if UserInterface is available.
if (interface_exists(UserInterface::class)) {
$staticTypes = $container->getDefinition(StaticClassListTypeMapperFactory::class)->getArgument(0);
if (!is_array($staticTypes)){
throw new GraphQLException(sprintf('Expecting array in %s, arg #1', StaticClassListTypeMapperFactory::class));
}
$staticTypes[] = SymfonyUserInterfaceType::class;
$container->getDefinition(StaticClassListTypeMapperFactory::class)->setArgument(0, $staticTypes);
}
Expand Down Expand Up @@ -294,6 +302,9 @@ private function registerController(string $controllerClassName, ContainerBuilde
{
$aggregateQueryProvider = $container->findDefinition(AggregateControllerQueryProviderFactory::class);
$controllersList = $aggregateQueryProvider->getArgument(0);
if (!is_array($controllersList)){
throw new GraphQLException(sprintf('Expecting array in %s, arg #1', AggregateControllerQueryProviderFactory::class));
}
$controllersList[] = $controllerClassName;
$aggregateQueryProvider->setArgument(0, $controllersList);
}
Expand Down Expand Up @@ -336,7 +347,14 @@ private function makePublicInjectedServices(ReflectionClass $refClass, Annotatio
return $services;
});

if (!is_array($services)){
throw new GraphQLException('An error occurred in compiler pass');
}

foreach ($services as $service) {
if (!is_string($service)){
throw new GraphQLException('expecting string as service');
}
if ($container->hasAlias($service)) {
$container->getAlias($service)->setPublic(true);
} else {
Expand Down
2 changes: 1 addition & 1 deletion DependencyInjection/GraphQLiteExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function($namespace): string {
$container->setParameter('graphqlite.namespace.types', $namespaceType);
$container->setParameter('graphqlite.security.enable_login', $enableLogin);
$container->setParameter('graphqlite.security.enable_me', $enableMe);
$container->setParameter('graphqlite.security.introspection', $config['security']['introspection'] ?? true);
$container->setParameter('graphqlite.security.disableIntrospection', !($config['security']['introspection'] ?? true));
$container->setParameter('graphqlite.security.maximum_query_complexity', $config['security']['maximum_query_complexity'] ?? null);
$container->setParameter('graphqlite.security.maximum_query_depth', $config['security']['maximum_query_depth'] ?? null);
$container->setParameter('graphqlite.security.firewall_name', $config['security']['firewall_name'] ?? 'main');
Expand Down
10 changes: 8 additions & 2 deletions GraphiQL/EndpointResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Overblog\GraphiQLBundle\Config\GraphiQLControllerEndpoint;
use Overblog\GraphiQLBundle\Config\GraphQLEndpoint\GraphQLEndpointInvalidSchemaException;
use Symfony\Component\HttpFoundation\RequestStack;
use Webmozart\Assert\Assert;
use function assert;

final class EndpointResolver implements GraphiQLControllerEndpoint
{
Expand All @@ -19,18 +19,24 @@ public function __construct(RequestStack $requestStack)
$this->requestStack = $requestStack;
}

/**
* @return string
*/
public function getBySchema($name)
{
if ('default' === $name) {
$request = $this->requestStack->getCurrentRequest();
Assert::notNull($request);
assert(!is_null($request));

return $request->getBaseUrl().'/graphql';
}

throw GraphQLEndpointInvalidSchemaException::forSchemaAndResolver($name, self::class);
}

/**
* @return string
*/
public function getDefault()
{
return $this->getBySchema('default');
Expand Down
4 changes: 1 addition & 3 deletions Mappers/RequestParameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@ class RequestParameter implements ParameterInterface
/**
* @param array<string, mixed> $args
* @param mixed $context
*
* @return mixed
*/
public function resolve(?object $source, array $args, $context, ResolveInfo $info)
public function resolve(?object $source, array $args, $context, ResolveInfo $info): mixed
{
if (!$context instanceof SymfonyRequestContextInterface) {
throw new GraphQLException('Cannot type-hint on a Symfony Request object in your query/mutation/field. The request context must implement SymfonyRequestContextInterface.');
Expand Down
4 changes: 3 additions & 1 deletion Resources/config/container/graphqlite.xml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@
</call>
</service>

<service id="GraphQL\Validator\Rules\DisableIntrospection" />
<service id="GraphQL\Validator\Rules\DisableIntrospection">
<argument key="$enabled">%graphqlite.security.disableIntrospection%</argument>
</service>

<service id="GraphQL\Validator\Rules\QueryComplexity" />

Expand Down
4 changes: 1 addition & 3 deletions Server/ServerConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@ class ServerConfig extends \GraphQL\Server\ServerConfig
*
* @param ValidationRule[]|callable $validationRules
*
* @return \GraphQL\Server\ServerConfig
*
* @api
*/
public function setValidationRules($validationRules)
public function setValidationRules($validationRules): \GraphQL\Server\ServerConfig
{
parent::setValidationRules(
function (OperationParams $params, DocumentNode $doc, string $operationType) use ($validationRules): array {
Expand Down
21 changes: 5 additions & 16 deletions Tests/Fixtures/Controller/MyException.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,23 @@
namespace TheCodingMachine\GraphQLite\Bundle\Tests\Fixtures\Controller;


use GraphQL\Error\ClientAware;
use TheCodingMachine\GraphQLite\Exceptions\GraphQLExceptionInterface;

class MyException extends \Exception implements ClientAware
class MyException extends \Exception implements GraphQLExceptionInterface
{

/**
* Returns true when exception message is safe to be displayed to a client.
*
* @return bool
*
* @api
*/
public function isClientSafe()
public function isClientSafe(): bool
{
return true;
}

/**
* Returns string describing a category of the error.
*
* Value "graphql" is reserved for errors produced by query parsing or validation, do not use it.
*
* @return string
*
* @api
*/
public function getCategory()
public function getExtensions(): array
{
return 'foobar';
return ['category' => 'foobar'];
}
}
2 changes: 1 addition & 1 deletion Tests/Fixtures/Controller/TestGraphqlController.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function triggerException(int $code = 0): string
public function triggerAggregateException(): string
{
$exception1 = new GraphQLException('foo', 401);
$exception2 = new GraphQLException('bar', 404, null, 'MyCat', ['field' => 'baz']);
$exception2 = new GraphQLException('bar', 404, null, 'MyCat', ['field' => 'baz', 'category' => 'MyCat']);
throw new GraphQLAggregateException([$exception1, $exception2]);
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ public function testWithIntrospection(): void

public function testDisableIntrospection(): void
{
$kernel = new GraphQLiteTestingKernel(true, null, true, null, false, 2, 2);
$kernel = new GraphQLiteTestingKernel(true, null, true, null, false, 3, 2);
$kernel->boot();

$parameters = ['query' => '
Expand Down
Loading