GraphQL\Utils::invariant PHP Method

invariant() public static method

public static invariant ( $test, string $message = '' )
$test
$message string
    public static function invariant($test, $message = '')
    {
        if (!$test) {
            if (func_num_args() > 2) {
                $args = func_get_args();
                array_shift($args);
                $message = call_user_func_array('sprintf', $args);
            }
            throw new InvariantViolation($message);
        }
    }

Usage Example

Example #1
0
 /**
  * Prepares an object map of variables of the correct type based on the provided
  * variable definitions and arbitrary input. If the input cannot be coerced
  * to match the variable definitions, a Error will be thrown.
  *
  * @param Schema $schema
  * @param VariableDefinitionNode[] $definitionNodes
  * @param array $inputs
  * @return array
  * @throws Error
  */
 public static function getVariableValues(Schema $schema, $definitionNodes, array $inputs)
 {
     $coercedValues = [];
     foreach ($definitionNodes as $definitionNode) {
         $varName = $definitionNode->variable->name->value;
         $varType = Utils\TypeInfo::typeFromAST($schema, $definitionNode->type);
         if (!Type::isInputType($varType)) {
             throw new Error('Variable "$' . $varName . '" expected value of type ' . '"' . Printer::doPrint($definitionNode->type) . '" which cannot be used as an input type.', [$definitionNode->type]);
         }
         if (!array_key_exists($varName, $inputs)) {
             $defaultValue = $definitionNode->defaultValue;
             if ($defaultValue) {
                 $coercedValues[$varName] = Utils\AST::valueFromAST($defaultValue, $varType);
             }
             if ($varType instanceof NonNull) {
                 throw new Error('Variable "$' . $varName . '" of required type ' . '"' . Utils::printSafe($varType) . '" was not provided.', [$definitionNode]);
             }
         } else {
             $value = $inputs[$varName];
             $errors = self::isValidPHPValue($value, $varType);
             if (!empty($errors)) {
                 $message = "\n" . implode("\n", $errors);
                 throw new Error('Variable "$' . $varName . '" got invalid value ' . json_encode($value) . '.' . $message, [$definitionNode]);
             }
             $coercedValue = self::coerceValue($varType, $value);
             Utils::invariant($coercedValue !== Utils::undefined(), 'Should have reported error.');
             $coercedValues[$varName] = $coercedValue;
         }
     }
     return $coercedValues;
 }
All Usage Examples Of GraphQL\Utils::invariant