Skip to content

Commit d7361e0

Browse files
authored
Avoid sprintf (#1083)
1 parent 914d91e commit d7361e0

File tree

10 files changed

+37
-57
lines changed

10 files changed

+37
-57
lines changed

src/Error/SyntaxError.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,13 @@
33
namespace GraphQL\Error;
44

55
use GraphQL\Language\Source;
6-
use function sprintf;
76

87
class SyntaxError extends Error
98
{
10-
/**
11-
* @param int $position
12-
* @param string $description
13-
*/
14-
public function __construct(Source $source, $position, $description)
9+
public function __construct(Source $source, int $position, string $description)
1510
{
1611
parent::__construct(
17-
sprintf('Syntax Error: %s', $description),
12+
"Syntax Error: {$description}",
1813
null,
1914
$source,
2015
[$position]

src/Executor/ReferenceExecutor.php

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@
4747
use function is_string;
4848
use RuntimeException;
4949
use SplObjectStorage;
50-
use function sprintf;
5150
use stdClass;
5251
use Throwable;
5352

@@ -186,11 +185,10 @@ protected static function buildExecutionContext(
186185
}
187186

188187
if ($operation === null) {
189-
if ($operationName === null) {
190-
$errors[] = new Error('Must provide an operation.');
191-
} else {
192-
$errors[] = new Error(sprintf('Unknown operation named "%s".', $operationName));
193-
}
188+
$message = $operationName === null
189+
? 'Must provide an operation.'
190+
: "Unknown operation named \"{$operationName}\".";
191+
$errors[] = new Error($message);
194192
} elseif ($hasMultipleAssumedOperations) {
195193
$errors[] = new Error(
196194
'Must provide operation name if query contains multiple operations.'
@@ -822,9 +820,7 @@ protected function completeValue(
822820
$result
823821
);
824822
if ($completed === null) {
825-
throw new InvariantViolation(
826-
sprintf('Cannot return null for non-nullable field "%s.%s".', $info->parentType, $info->fieldName)
827-
);
823+
throw new InvariantViolation("Cannot return null for non-nullable field \"{$info->parentType}.{$info->fieldName}\".");
828824
}
829825

830826
return $completed;
@@ -1089,15 +1085,9 @@ protected function defaultTypeResolver($value, $contextValue, ResolveInfo $info,
10891085
}
10901086

10911087
if ($abstractType instanceof InterfaceType && $info->schema->getConfig()->typeLoader !== null) {
1088+
$safeValue = Utils::printSafe($value);
10921089
Warning::warnOnce(
1093-
sprintf(
1094-
'GraphQL Interface Type `%s` returned `null` from its `resolveType` function '
1095-
. 'for value: %s. Switching to slow resolution method using `isTypeOf` '
1096-
. 'of all possible implementations. It requires full schema scan and degrades query performance significantly. '
1097-
. ' Make sure your `resolveType` always returns valid implementation or throws.',
1098-
$abstractType->name,
1099-
Utils::printSafe($value)
1100-
),
1090+
"GraphQL Interface Type `{$abstractType->name}` returned `null` from its `resolveType` function for value: {$safeValue}. Switching to slow resolution method using `isTypeOf` of all possible implementations. It requires full schema scan and degrades query performance significantly. Make sure your `resolveType` always returns valid implementation or throws.",
11011091
Warning::WARNING_FULL_SCHEMA_SCAN
11021092
);
11031093
}

src/Language/Parser.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@
5858
use GraphQL\Language\AST\ValueNode;
5959
use GraphQL\Language\AST\VariableDefinitionNode;
6060
use GraphQL\Language\AST\VariableNode;
61-
use function sprintf;
6261

6362
/**
6463
* Parses string containing GraphQL query language or [schema definition language](schema-definition-language.md) to Abstract Syntax Tree.
@@ -369,7 +368,7 @@ private function expect(string $kind): Token
369368
throw new SyntaxError(
370369
$this->lexer->source,
371370
$token->start,
372-
sprintf('Expected %s, found %s', $kind, $token->getDescription())
371+
"Expected {$kind}, found {$token->getDescription()}"
373372
);
374373
}
375374

src/Utils/BreakingChangesFinder.php

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
use GraphQL\Type\Definition\Type;
2121
use GraphQL\Type\Definition\UnionType;
2222
use GraphQL\Type\Schema;
23-
use function sprintf;
2423
use TypeError;
2524

2625
/**
@@ -406,7 +405,7 @@ public static function findTypesRemovedFromUnions(
406405
if (! isset($typeNamesInNewUnion[$type->name])) {
407406
$typesRemovedFromUnion[] = [
408407
'type' => self::BREAKING_CHANGE_TYPE_REMOVED_FROM_UNION,
409-
'description' => sprintf('%s was removed from union type %s.', $type->name, $typeName),
408+
'description' => "{$type->name} was removed from union type {$typeName}.",
410409
];
411410
}
412411
}
@@ -444,7 +443,7 @@ public static function findValuesRemovedFromEnums(
444443
if (! isset($valuesInNewEnum[$value->name])) {
445444
$valuesRemovedFromEnums[] = [
446445
'type' => self::BREAKING_CHANGE_VALUE_REMOVED_FROM_ENUM,
447-
'description' => sprintf('%s was removed from enum type %s.', $value->name, $typeName),
446+
'description' => "{$value->name} was removed from enum type {$typeName}.",
448447
];
449448
}
450449
}
@@ -611,7 +610,7 @@ public static function findRemovedDirectives(Schema $oldSchema, Schema $newSchem
611610
if (! isset($newSchemaDirectiveMap[$directive->name])) {
612611
$removedDirectives[] = [
613612
'type' => self::BREAKING_CHANGE_DIRECTIVE_REMOVED,
614-
'description' => sprintf('%s was removed', $directive->name),
613+
'description' => "{$directive->name} was removed",
615614
];
616615
}
617616
}
@@ -653,7 +652,7 @@ public static function findRemovedDirectiveArgs(Schema $oldSchema, Schema $newSc
653652
) {
654653
$removedDirectiveArgs[] = [
655654
'type' => self::BREAKING_CHANGE_DIRECTIVE_ARG_REMOVED,
656-
'description' => sprintf('%s was removed from %s', $arg->name, $newDirective->name),
655+
'description' => "{$arg->name} was removed from {$newDirective->name}",
657656
];
658657
}
659658
}
@@ -758,7 +757,7 @@ public static function findRemovedDirectiveLocations(Schema $oldSchema, Schema $
758757
) {
759758
$removedLocations[] = [
760759
'type' => self::BREAKING_CHANGE_DIRECTIVE_LOCATION_REMOVED,
761-
'description' => sprintf('%s was removed from %s', $location, $newDirective->name),
760+
'description' => "{$location} was removed from {$newDirective->name}",
762761
];
763762
}
764763
}
@@ -908,7 +907,7 @@ public static function findTypesAddedToUnions(
908907
if (! isset($typeNamesInOldUnion[$type->name])) {
909908
$typesAddedToUnion[] = [
910909
'type' => self::DANGEROUS_CHANGE_TYPE_ADDED_TO_UNION,
911-
'description' => sprintf('%s was added to union type %s.', $type->name, $typeName),
910+
'description' => "{$type->name} was added to union type {$typeName}.",
912911
];
913912
}
914913
}

src/Utils/SchemaPrinter.php

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232
use function implode;
3333
use function ksort;
3434
use function mb_strlen;
35-
use function sprintf;
3635
use function str_replace;
3736

3837
/**
@@ -105,7 +104,8 @@ public static function printType(Type $type, array $options = []): string
105104
return static::printInputObject($type, $options);
106105
}
107106

108-
throw new Error(sprintf('Unknown type: %s.', Utils::printSafe($type)));
107+
$unknownType = Utils::printSafe($type);
108+
throw new Error("Unknown type: {$unknownType}.");
109109
}
110110

111111
/**
@@ -145,20 +145,22 @@ protected static function printSchemaDefinition(Schema $schema): string
145145

146146
$queryType = $schema->getQueryType();
147147
if ($queryType !== null) {
148-
$operationTypes[] = sprintf(' query: %s', $queryType->name);
148+
$operationTypes[] = " query: {$queryType->name}";
149149
}
150150

151151
$mutationType = $schema->getMutationType();
152152
if ($mutationType !== null) {
153-
$operationTypes[] = sprintf(' mutation: %s', $mutationType->name);
153+
$operationTypes[] = " mutation: {$mutationType->name}";
154154
}
155155

156156
$subscriptionType = $schema->getSubscriptionType();
157157
if ($subscriptionType !== null) {
158-
$operationTypes[] = sprintf(' subscription: %s', $subscriptionType->name);
158+
$operationTypes[] = " subscription: {$subscriptionType->name}";
159159
}
160160

161-
return sprintf("schema {\n%s\n}", implode("\n", $operationTypes));
161+
$typesString = implode("\n", $operationTypes);
162+
163+
return "schema {\n{$typesString}\n}";
162164
}
163165

164166
/**
@@ -398,7 +400,7 @@ protected static function printImplementedInterfaces(ImplementingType $type): st
398400
protected static function printInterface(InterfaceType $type, array $options): string
399401
{
400402
return static::printDescription($options, $type)
401-
. sprintf('interface %s', $type->name)
403+
. "interface {$type->name}"
402404
. self::printImplementedInterfaces($type)
403405
. static::printFields($options, $type);
404406
}
@@ -436,7 +438,7 @@ static function (EnumValueDefinition $value, int $i) use ($options): string {
436438
);
437439

438440
return static::printDescription($options, $type)
439-
. sprintf('enum %s', $type->name)
441+
. "enum {$type->name}"
440442
. static::printBlock($values);
441443
}
442444

tests/GraphQLTest.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
use GraphQL\Type\Definition\Type;
1010
use GraphQL\Type\Schema;
1111
use PHPUnit\Framework\TestCase;
12-
use function sprintf;
1312

1413
class GraphQLTest extends TestCase
1514
{
@@ -30,7 +29,7 @@ public function testPromiseToExecute(): void
3029
],
3130
],
3231
'resolve' => static function ($rootValue, $args) use ($promiseAdapter): Promise {
33-
return $promiseAdapter->createFulfilled(sprintf('Hi %s!', $args['name']));
32+
return $promiseAdapter->createFulfilled("Hi {$args['name']}!");
3433
},
3534
],
3635
],

tests/Server/QueryExecutionTest.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
use GraphQL\Validator\DocumentValidator;
1919
use GraphQL\Validator\Rules\CustomValidationRule;
2020
use GraphQL\Validator\ValidationContext;
21-
use function sprintf;
2221
use stdClass;
2322

2423
class QueryExecutionTest extends ServerTestCase
@@ -539,12 +538,12 @@ public function testDeferredsAreSharedAmongAllBatchedQueries(): void
539538
->setRootValue('1')
540539
->setContext([
541540
'buffer' => static function ($num) use (&$calls): void {
542-
$calls[] = sprintf('buffer: %d', $num);
541+
$calls[] = "buffer: {$num}";
543542
},
544543
'load' => static function ($num) use (&$calls): string {
545-
$calls[] = sprintf('load: %d', $num);
544+
$calls[] = "load: {$num}";
546545

547-
return sprintf('loaded: %d', $num);
546+
return "loaded: {$num}";
548547
},
549548
]);
550549

tests/Type/DefinitionTest.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
use GraphQL\Type\Schema;
3030
use RuntimeException;
3131
use function Safe\json_encode;
32-
use function sprintf;
3332
use stdClass;
3433

3534
final class DefinitionTest extends TestCaseBase
@@ -586,7 +585,7 @@ public function testIdentifiesInputTypes(): void
586585
self::assertSame(
587586
$entry[1],
588587
Type::isInputType($entry[0]),
589-
sprintf('Type %s was detected incorrectly', $entry[0])
588+
"Type {$entry[0]} was detected incorrectly"
590589
);
591590
}
592591
}
@@ -619,7 +618,7 @@ public function testIdentifiesOutputTypes(): void
619618
self::assertSame(
620619
$entry[1],
621620
Type::isOutputType($entry[0]),
622-
sprintf('Type %s was detected incorrectly', $entry[0])
621+
"Type {$entry[0]} was detected incorrectly"
623622
);
624623
}
625624
}

tests/Type/IntrospectionTest.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@
99
use GraphQL\Type\Definition\EnumType;
1010
use GraphQL\Type\Definition\InputObjectType;
1111
use GraphQL\Type\Definition\ObjectType;
12+
use GraphQL\Type\Definition\ResolveInfo;
1213
use GraphQL\Type\Definition\Type;
1314
use GraphQL\Type\Introspection;
1415
use GraphQL\Type\Schema;
1516
use GraphQL\Validator\Rules\ProvidedRequiredArguments;
1617
use PHPUnit\Framework\TestCase;
1718
use function Safe\json_encode;
18-
use function sprintf;
1919

2020
class IntrospectionTest extends TestCase
2121
{
@@ -1452,9 +1452,8 @@ public function testExecutesAnIntrospectionQueryWithoutCallingGlobalFieldResolve
14521452
$source = Introspection::getIntrospectionQuery(['directiveIsRepeatable' => true]);
14531453

14541454
$calledForFields = [];
1455-
/* istanbul ignore next */
1456-
$fieldResolver = static function ($value, $_1, $_2, $info) use (&$calledForFields) {
1457-
$calledForFields[sprintf('%s::%s', $info->parentType->name, $info->fieldName)] = true;
1455+
$fieldResolver = static function ($value, array $_1, $_2, ResolveInfo $info) use (&$calledForFields) {
1456+
$calledForFields["{$info->parentType->name}::{$info->fieldName}"] = true;
14581457

14591458
return $value;
14601459
};

tests/Utils/BreakingChangesFinderTest.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
use GraphQL\Type\Schema;
1414
use GraphQL\Utils\BreakingChangesFinder;
1515
use PHPUnit\Framework\TestCase;
16-
use function sprintf;
1716

1817
class BreakingChangesFinderTest extends TestCase
1918
{
@@ -1373,7 +1372,7 @@ public function testShouldDetectIfADirectiveWasExplicitlyRemoved(): void
13731372
$expectedBreakingChanges = [
13741373
[
13751374
'type' => BreakingChangesFinder::BREAKING_CHANGE_DIRECTIVE_REMOVED,
1376-
'description' => sprintf('%s was removed', $includeDirective->name),
1375+
'description' => "{$includeDirective->name} was removed",
13771376
],
13781377
];
13791378

@@ -1399,7 +1398,7 @@ public function testShouldDetectIfADirectiveWasImplicitlyRemoved(): void
13991398
$expectedBreakingChanges = [
14001399
[
14011400
'type' => BreakingChangesFinder::BREAKING_CHANGE_DIRECTIVE_REMOVED,
1402-
'description' => sprintf('%s was removed', $deprecatedDirective->name),
1401+
'description' => "{$deprecatedDirective->name} was removed",
14031402
],
14041403
];
14051404

0 commit comments

Comments
 (0)