_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q242200
Charge.cancel
validation
public function cancel() { if (!$this->isType(self::CHARGE_ONETIME) && !$this->isType(self::CHARGE_RECURRING)) { throw new Exception('Cancel may only be called for single and recurring charges.'); } $this->status = self::STATUS_CANCELLED; $this->cancelled_on = Carbon::today()->format('Y-m-d'); return $this->save(); }
php
{ "resource": "" }
q242201
Billable.handle
validation
public function handle(Request $request, Closure $next) { if (Config::get('shopify-app.billing_enabled') === true) { $shop = ShopifyApp::shop(); if (!$shop->isFreemium() && !$shop->isGrandfathered() && !$shop->plan) { // They're not grandfathered in, and there is no charge or charge was declined... redirect to billing return Redirect::route('billing'); } } // Move on, everything's fine return $next($request); }
php
{ "resource": "" }
q242202
WebhookControllerTrait.handle
validation
public function handle($type) { // Get the job class and dispatch $jobClass = '\\App\\Jobs\\'.str_replace('-', '', ucwords($type, '-')).'Job'; $jobClass::dispatch( Request::header('x-shopify-shop-domain'), json_decode(Request::getContent()) ); return Response::make('', 201); }
php
{ "resource": "" }
q242203
AuthShopHandler.buildAuthUrl
validation
public function buildAuthUrl($mode = null) { // Determine the type of mode // Grab the authentication URL return $this->api->getAuthUrl( Config::get('shopify-app.api_scopes'), URL::secure(Config::get('shopify-app.api_redirect')), $mode ?? 'offline' ); }
php
{ "resource": "" }
q242204
AuthShopHandler.postProcess
validation
public function postProcess() { if (!$this->shop->trashed()) { return; } // Trashed, fix it $this->shop->restore(); $this->shop->charges()->restore(); $this->shop->save(); }
php
{ "resource": "" }
q242205
AuthShopHandler.dispatchWebhooks
validation
public function dispatchWebhooks() { $webhooks = Config::get('shopify-app.webhooks'); if (count($webhooks) > 0) { WebhookInstaller::dispatch($this->shop)->onQueue(Config::get('shopify-app.job_queues.webhooks')); } }
php
{ "resource": "" }
q242206
AuthShopHandler.dispatchScripttags
validation
public function dispatchScripttags() { $scripttags = Config::get('shopify-app.scripttags'); if (count($scripttags) > 0) { ScripttagInstaller::dispatch($this->shop, $scripttags)->onQueue(Config::get('shopify-app.job_queues.scripttags')); } }
php
{ "resource": "" }
q242207
AuthShopHandler.dispatchAfterAuthenticate
validation
public function dispatchAfterAuthenticate() { // Grab the jobs config $jobsConfig = Config::get('shopify-app.after_authenticate_job'); /** * Fires the job. * * @param array $config The job's configuration * * @return bool */ $fireJob = function ($config) { $job = $config['job']; if (isset($config['inline']) && $config['inline'] === true) { // Run this job immediately $job::dispatchNow($this->shop); } else { // Run later $job::dispatch($this->shop)->onQueue(Config::get('shopify-app.job_queues.after_authenticate')); } return true; }; // We have multi-jobs if (isset($jobsConfig[0])) { foreach ($jobsConfig as $jobConfig) { // We have a job, pass the shop object to the contructor $fireJob($jobConfig); } return true; } // We have a single job if (isset($jobsConfig['job'])) { return $fireJob($jobsConfig); } return false; }
php
{ "resource": "" }
q242208
AppUninstalledJob.cleanShop
validation
protected function cleanShop() { $this->shop->shopify_token = null; $this->shop->plan_id = null; $this->shop->save(); }
php
{ "resource": "" }
q242209
AppUninstalledJob.cancelCharge
validation
protected function cancelCharge() { $planCharge = $this->shop->planCharge(); if ($planCharge && !$planCharge->isDeclined() && !$planCharge->isCancelled()) { $planCharge->cancel(); } }
php
{ "resource": "" }
q242210
ShopSession.getType
validation
public function getType() { $config = Config::get('shopify-app.api_grant_mode'); if ($config === self::GRANT_PERUSER) { return self::GRANT_PERUSER; } return self::GRANT_OFFLINE; }
php
{ "resource": "" }
q242211
ShopSession.setDomain
validation
public function setDomain(string $shopDomain) { $this->fixLifetime(); Session::put(self::DOMAIN, $shopDomain); }
php
{ "resource": "" }
q242212
ShopSession.getToken
validation
public function getToken(bool $strict = false) { // Tokens $tokens = [ self::GRANT_PERUSER => Session::get(self::TOKEN), self::GRANT_OFFLINE => $this->shop->{self::TOKEN}, ]; if ($strict) { // We need the token matching the type return $tokens[$this->getType()]; } // We need a token either way... return $tokens[self::GRANT_PERUSER] ?? $tokens[self::GRANT_OFFLINE]; }
php
{ "resource": "" }
q242213
ShopSession.forget
validation
public function forget() { $keys = [self::DOMAIN, self::USER, self::TOKEN]; foreach ($keys as $key) { Session::forget($key); } }
php
{ "resource": "" }
q242214
ShopObserver.creating
validation
public function creating($shop) { if (!isset($shop->namespace)) { // Automatically add the current namespace to new records $shop->namespace = Config::get('shopify-app.namespace'); } if (Config::get('shopify-app.billing_freemium_enabled') === true && !isset($shop->freemium)) { // Add the freemium flag to the shop $shop->freemium = true; } }
php
{ "resource": "" }
q242215
AuthWebhook.handle
validation
public function handle(Request $request, Closure $next) { $hmac = $request->header('x-shopify-hmac-sha256') ?: ''; $shop = $request->header('x-shopify-shop-domain'); $data = $request->getContent(); $hmacLocal = ShopifyApp::createHmac(['data' => $data, 'raw' => true, 'encode' => true]); if (!hash_equals($hmac, $hmacLocal) || empty($shop)) { // Issue with HMAC or missing shop header return Response::make('Invalid webhook signature.', 401); } // All good, process webhook return $next($request); }
php
{ "resource": "" }
q242216
WebhookManager.shopWebhooks
validation
public function shopWebhooks() { if (!$this->shopWebhooks) { $this->shopWebhooks = $this->api->rest( 'GET', '/admin/webhooks.json', [ 'limit' => 250, 'fields' => 'id,address', ] )->body->webhooks; } return $this->shopWebhooks; }
php
{ "resource": "" }
q242217
WebhookManager.deleteWebhooks
validation
public function deleteWebhooks() { $shopWebhooks = $this->shopWebhooks(); $deleted = []; foreach ($shopWebhooks as $webhook) { // Its a webhook in the config, delete it $this->api->rest('DELETE', "/admin/webhooks/{$webhook->id}.json"); $deleted[] = $webhook; } // Reset $this->shopWebhooks = null; return $deleted; }
php
{ "resource": "" }
q242218
WebhookJobMakeCommand.getUrlFromName
validation
protected function getUrlFromName(string $name) { if (Str::endsWith($name, 'Job')) { $name = substr($name, 0, -3); } return strtolower(preg_replace('/(?<!^)[A-Z]/', '-$0', $name)); }
php
{ "resource": "" }
q242219
AuthShop.validateShop
validation
protected function validateShop(Request $request) { $shopParam = ShopifyApp::sanitizeShopDomain($request->get('shop')); $shop = ShopifyApp::shop($shopParam); $session = new ShopSession($shop); // Check if shop has a session, also check the shops to ensure a match if ( $shop === null || $shop->trashed() || empty($session->getToken(true)) || ($shopParam && $shopParam !== $shop->shopify_domain) === true ) { // Either no shop session or shops do not match $session->forget(); // Set the return-to path so we can redirect after successful authentication Session::put('return_to', $request->fullUrl()); return Redirect::route('authenticate', ['shop' => $shopParam]); } return true; }
php
{ "resource": "" }
q242220
AuthShop.response
validation
protected function response(Request $request, Closure $next) { // Shop is OK, now check if ESDK is enabled and this is not a JSON/AJAX request... $response = $next($request); if ( Config::get('shopify-app.esdk_enabled') && ($request->ajax() || $request->expectsJson() || $request->isJson()) === false ) { if (($response instanceof BaseResponse) === false) { // Not an instance of a Symfony response, override $response = new Response($response); } // Attempt to modify headers applicable to ESDK (does not work in all cases) $response->headers->set('P3P', 'CP="Not used"'); $response->headers->remove('X-Frame-Options'); } return $response; }
php
{ "resource": "" }
q242221
ShopModelTrait.api
validation
public function api() { if (!$this->api) { // Get the domain and token $shopDomain = $this->shopify_domain; $token = $this->session()->getToken(); // Create new API instance $this->api = ShopifyApp::api(); $this->api->setSession($shopDomain, $token); } // Return existing instance return $this->api; }
php
{ "resource": "" }
q242222
ShopModelTrait.planCharge
validation
public function planCharge() { return $this->charges() ->whereIn('type', [Charge::CHARGE_RECURRING, Charge::CHARGE_ONETIME]) ->where('plan_id', $this->plan_id) ->orderBy('created_at', 'desc') ->first(); }
php
{ "resource": "" }
q242223
BillingControllerTrait.index
validation
public function index(Plan $plan) { // If the plan is null, get a plan if (is_null($plan) || ($plan && !$plan->exists)) { $plan = Plan::where('on_install', true)->first(); } // Get the confirmation URL $bp = new BillingPlan(ShopifyApp::shop(), $plan); $url = $bp->confirmationUrl(); // Do a fullpage redirect return View::make('shopify-app::billing.fullpage_redirect', compact('url')); }
php
{ "resource": "" }
q242224
BillingControllerTrait.process
validation
public function process(Plan $plan) { // Activate the plan and save $shop = ShopifyApp::shop(); $bp = new BillingPlan($shop, $plan); $bp->setChargeId(Request::query('charge_id')); $bp->activate(); $bp->save(); // All good, update the shop's plan and take them off freemium (if applicable) $shop->update([ 'freemium' => false, 'plan_id' => $plan->id, ]); // Go to homepage of app return Redirect::route('home')->with('success', 'billing'); }
php
{ "resource": "" }
q242225
BillingControllerTrait.usageCharge
validation
public function usageCharge(StoreUsageCharge $request) { // Activate and save the usage charge $validated = $request->validated(); $uc = new UsageCharge(ShopifyApp::shop(), $validated); $uc->activate(); $uc->save(); // All done, return with success return isset($validated['redirect']) ? Redirect::to($validated['redirect'])->with('success', 'usage_charge') : Redirect::back()->with('success', 'usage_charge'); }
php
{ "resource": "" }
q242226
BillingPlan.getCharge
validation
public function getCharge() { // Check if we have a charge ID to use if (!$this->chargeId) { throw new Exception('Can not get charge information without charge ID.'); } // Run API to grab details return $this->api->rest( 'GET', "/admin/{$this->plan->typeAsString(true)}/{$this->chargeId}.json" )->body->{$this->plan->typeAsString()}; }
php
{ "resource": "" }
q242227
BillingPlan.confirmationUrl
validation
public function confirmationUrl() { // Begin the charge request $charge = $this->api->rest( 'POST', "/admin/{$this->plan->typeAsString(true)}.json", ["{$this->plan->typeAsString()}" => $this->chargeParams()] )->body->{$this->plan->typeAsString()}; return $charge->confirmation_url; }
php
{ "resource": "" }
q242228
BillingPlan.chargeParams
validation
public function chargeParams() { // Build the charge array $chargeDetails = [ 'name' => $this->plan->name, 'price' => $this->plan->price, 'test' => $this->plan->isTest(), 'trial_days' => $this->plan->hasTrial() ? $this->plan->trial_days : 0, 'return_url' => URL::secure(Config::get('shopify-app.billing_redirect'), ['plan_id' => $this->plan->id]), ]; // Handle capped amounts for UsageCharge API if (isset($this->plan->capped_amount) && $this->plan->capped_amount > 0) { $chargeDetails['capped_amount'] = $this->plan->capped_amount; $chargeDetails['terms'] = $this->plan->terms; } return $chargeDetails; }
php
{ "resource": "" }
q242229
BillingPlan.activate
validation
public function activate() { // Check if we have a charge ID to use if (!$this->chargeId) { throw new Exception('Can not activate plan without a charge ID.'); } // Activate and return the API response $this->response = $this->api->rest( 'POST', "/admin/{$this->plan->typeAsString(true)}/{$this->chargeId}/activate.json" )->body->{$this->plan->typeAsString()}; return $this->response; }
php
{ "resource": "" }
q242230
BillingPlan.save
validation
public function save() { if (!$this->response) { throw new Exception('No activation response was recieved.'); } // Cancel the last charge $planCharge = $this->shop->planCharge(); if ($planCharge && !$planCharge->isDeclined() && !$planCharge->isCancelled()) { $planCharge->cancel(); } // Create a charge $charge = Charge::firstOrNew([ 'charge_id' => $this->chargeId, 'shop_id' => $this->shop->id, ]); $charge->plan_id = $this->plan->id; $charge->type = $this->plan->type; $charge->status = $this->response->status; if ($this->plan->isType(Plan::PLAN_RECURRING)) { // Recurring plan specifics $charge->billing_on = $this->response->billing_on; $charge->trial_ends_on = $this->response->trial_ends_on; } // Set the activated on, try for the API, fallback to today $charge->activated_on = $this->response->activated_on ?? Carbon::today()->format('Y-m-d'); // Merge in the plan details since the fields match the database columns $planDetails = $this->chargeParams(); unset($planDetails['return_url']); foreach ($planDetails as $key => $value) { $charge->{$key} = $value; } // Finally, save the charge return $charge->save(); }
php
{ "resource": "" }
q242231
DocumentValidator.validate
validation
public static function validate( Schema $schema, DocumentNode $ast, ?array $rules = null, ?TypeInfo $typeInfo = null ) { if ($rules === null) { $rules = static::allRules(); } if (is_array($rules) === true && count($rules) === 0) { // Skip validation if there are no rules return []; } $typeInfo = $typeInfo ?: new TypeInfo($schema); return static::visitUsingRules($schema, $typeInfo, $ast, $rules); }
php
{ "resource": "" }
q242232
DocumentValidator.allRules
validation
public static function allRules() { if (! self::$initRules) { static::$rules = array_merge(static::defaultRules(), self::securityRules(), self::$rules); static::$initRules = true; } return self::$rules; }
php
{ "resource": "" }
q242233
DocumentValidator.visitUsingRules
validation
public static function visitUsingRules(Schema $schema, TypeInfo $typeInfo, DocumentNode $documentNode, array $rules) { $context = new ValidationContext($schema, $documentNode, $typeInfo); $visitors = []; foreach ($rules as $rule) { $visitors[] = $rule->getVisitor($context); } Visitor::visit($documentNode, Visitor::visitWithTypeInfo($typeInfo, Visitor::visitInParallel($visitors))); return $context->getErrors(); }
php
{ "resource": "" }
q242234
DocumentValidator.isValidLiteralValue
validation
public static function isValidLiteralValue(Type $type, $valueNode) { $emptySchema = new Schema([]); $emptyDoc = new DocumentNode(['definitions' => []]); $typeInfo = new TypeInfo($emptySchema, $type); $context = new ValidationContext($emptySchema, $emptyDoc, $typeInfo); $validator = new ValuesOfCorrectType(); $visitor = $validator->getVisitor($context); Visitor::visit($valueNode, Visitor::visitWithTypeInfo($typeInfo, $visitor)); return $context->getErrors(); }
php
{ "resource": "" }
q242235
ASTDefinitionBuilder.getDescription
validation
private function getDescription($node) { if ($node->description) { return $node->description->value; } if (isset($this->options['commentDescriptions'])) { $rawValue = $this->getLeadingCommentBlock($node); if ($rawValue !== null) { return BlockString::value("\n" . $rawValue); } } return null; }
php
{ "resource": "" }
q242236
ASTDefinitionBuilder.getDeprecationReason
validation
private function getDeprecationReason($node) { $deprecated = Values::getDirectiveValues(Directive::deprecatedDirective(), $node); return $deprecated['reason'] ?? null; }
php
{ "resource": "" }
q242237
MixedStore.offsetExists
validation
public function offsetExists($offset) { if ($offset === false) { return $this->falseValueIsSet; } if ($offset === true) { return $this->trueValueIsSet; } if (is_int($offset) || is_string($offset)) { return array_key_exists($offset, $this->standardStore); } if (is_float($offset)) { return array_key_exists((string) $offset, $this->floatStore); } if (is_object($offset)) { return $this->objectStore->offsetExists($offset); } if (is_array($offset)) { foreach ($this->arrayKeys as $index => $entry) { if ($entry === $offset) { $this->lastArrayKey = $offset; $this->lastArrayValue = $this->arrayValues[$index]; return true; } } } if ($offset === null) { return $this->nullValueIsSet; } return false; }
php
{ "resource": "" }
q242238
MixedStore.offsetUnset
validation
public function offsetUnset($offset) { if ($offset === true) { $this->trueValue = null; $this->trueValueIsSet = false; } elseif ($offset === false) { $this->falseValue = null; $this->falseValueIsSet = false; } elseif (is_int($offset) || is_string($offset)) { unset($this->standardStore[$offset]); } elseif (is_float($offset)) { unset($this->floatStore[(string) $offset]); } elseif (is_object($offset)) { $this->objectStore->offsetUnset($offset); } elseif (is_array($offset)) { $index = array_search($offset, $this->arrayKeys, true); if ($index !== false) { array_splice($this->arrayKeys, $index, 1); array_splice($this->arrayValues, $index, 1); } } elseif ($offset === null) { $this->nullValue = null; $this->nullValueIsSet = false; } }
php
{ "resource": "" }
q242239
Schema.getTypeMap
validation
public function getTypeMap() { if (! $this->fullyLoaded) { $this->resolvedTypes = $this->collectAllTypes(); $this->fullyLoaded = true; } return $this->resolvedTypes; }
php
{ "resource": "" }
q242240
Schema.getType
validation
public function getType($name) { if (! isset($this->resolvedTypes[$name])) { $type = $this->loadType($name); if (! $type) { return null; } $this->resolvedTypes[$name] = $type; } return $this->resolvedTypes[$name]; }
php
{ "resource": "" }
q242241
Schema.getDirective
validation
public function getDirective($name) { foreach ($this->getDirectives() as $directive) { if ($directive->name === $name) { return $directive; } } return null; }
php
{ "resource": "" }
q242242
TypeComparators.doTypesOverlap
validation
public static function doTypesOverlap(Schema $schema, CompositeType $typeA, CompositeType $typeB) { // Equivalent types overlap if ($typeA === $typeB) { return true; } if ($typeA instanceof AbstractType) { if ($typeB instanceof AbstractType) { // If both types are abstract, then determine if there is any intersection // between possible concrete types of each. foreach ($schema->getPossibleTypes($typeA) as $type) { if ($schema->isPossibleType($typeB, $type)) { return true; } } return false; } // Determine if the latter type is a possible concrete type of the former. return $schema->isPossibleType($typeA, $typeB); } if ($typeB instanceof AbstractType) { // Determine if the former type is a possible concrete type of the latter. return $schema->isPossibleType($typeB, $typeA); } // Otherwise the types do not overlap. return false; }
php
{ "resource": "" }
q242243
Visitor.visitWithTypeInfo
validation
public static function visitWithTypeInfo(TypeInfo $typeInfo, $visitor) { return [ 'enter' => static function (Node $node) use ($typeInfo, $visitor) { $typeInfo->enter($node); $fn = self::getVisitFn($visitor, $node->kind, false); if ($fn) { $result = call_user_func_array($fn, func_get_args()); if ($result !== null) { $typeInfo->leave($node); if ($result instanceof Node) { $typeInfo->enter($result); } } return $result; } return null; }, 'leave' => static function (Node $node) use ($typeInfo, $visitor) { $fn = self::getVisitFn($visitor, $node->kind, true); $result = $fn ? call_user_func_array($fn, func_get_args()) : null; $typeInfo->leave($node); return $result; }, ]; }
php
{ "resource": "" }
q242244
Helper.parseHttpRequest
validation
public function parseHttpRequest(?callable $readRawBodyFn = null) { $method = $_SERVER['REQUEST_METHOD'] ?? null; $bodyParams = []; $urlParams = $_GET; if ($method === 'POST') { $contentType = $_SERVER['CONTENT_TYPE'] ?? null; if ($contentType === null) { throw new RequestError('Missing "Content-Type" header'); } if (stripos($contentType, 'application/graphql') !== false) { $rawBody = $readRawBodyFn ? $readRawBodyFn() : $this->readRawBody(); $bodyParams = ['query' => $rawBody ?: '']; } elseif (stripos($contentType, 'application/json') !== false) { $rawBody = $readRawBodyFn ? $readRawBodyFn() : $this->readRawBody(); $bodyParams = json_decode($rawBody ?: '', true); if (json_last_error()) { throw new RequestError('Could not parse JSON: ' . json_last_error_msg()); } if (! is_array($bodyParams)) { throw new RequestError( 'GraphQL Server expects JSON object or array, but got ' . Utils::printSafeJson($bodyParams) ); } } elseif (stripos($contentType, 'application/x-www-form-urlencoded') !== false) { $bodyParams = $_POST; } elseif (stripos($contentType, 'multipart/form-data') !== false) { $bodyParams = $_POST; } else { throw new RequestError('Unexpected content type: ' . Utils::printSafeJson($contentType)); } } return $this->parseRequestParams($method, $bodyParams, $urlParams); }
php
{ "resource": "" }
q242245
Helper.parseRequestParams
validation
public function parseRequestParams($method, array $bodyParams, array $queryParams) { if ($method === 'GET') { $result = OperationParams::create($queryParams, true); } elseif ($method === 'POST') { if (isset($bodyParams[0])) { $result = []; foreach ($bodyParams as $index => $entry) { $op = OperationParams::create($entry); $result[] = $op; } } else { $result = OperationParams::create($bodyParams); } } else { throw new RequestError('HTTP Method "' . $method . '" is not supported'); } return $result; }
php
{ "resource": "" }
q242246
Helper.toPsrResponse
validation
public function toPsrResponse($result, ResponseInterface $response, StreamInterface $writableBodyStream) { if ($result instanceof Promise) { return $result->then(function ($actualResult) use ($response, $writableBodyStream) { return $this->doConvertToPsrResponse($actualResult, $response, $writableBodyStream); }); } return $this->doConvertToPsrResponse($result, $response, $writableBodyStream); }
php
{ "resource": "" }
q242247
UnionType.resolveType
validation
public function resolveType($objectValue, $context, ResolveInfo $info) { if (isset($this->config['resolveType'])) { $fn = $this->config['resolveType']; return $fn($objectValue, $context, $info); } return null; }
php
{ "resource": "" }
q242248
Utils.isValidNameError
validation
public static function isValidNameError($name, $node = null) { self::invariant(is_string($name), 'Expected string'); if (isset($name[1]) && $name[0] === '_' && $name[1] === '_') { return new Error( sprintf('Name "%s" must not begin with "__", which is reserved by ', $name) . 'GraphQL introspection.', $node ); } if (! preg_match('/^[_a-zA-Z][_a-zA-Z0-9]*$/', $name)) { return new Error( sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name), $node ); } return null; }
php
{ "resource": "" }
q242249
Utils.suggestionList
validation
public static function suggestionList($input, array $options) { $optionsByDistance = []; $inputThreshold = mb_strlen($input) / 2; foreach ($options as $option) { if ($input === $option) { $distance = 0; } else { $distance = (strtolower($input) === strtolower($option) ? 1 : levenshtein($input, $option)); } $threshold = max($inputThreshold, mb_strlen($option) / 2, 1); if ($distance > $threshold) { continue; } $optionsByDistance[$option] = $distance; } asort($optionsByDistance); return array_keys($optionsByDistance); }
php
{ "resource": "" }
q242250
Executor.defaultFieldResolver
validation
public static function defaultFieldResolver($source, $args, $context, ResolveInfo $info) { $fieldName = $info->fieldName; $property = null; if (is_array($source) || $source instanceof ArrayAccess) { if (isset($source[$fieldName])) { $property = $source[$fieldName]; } } elseif (is_object($source)) { if (isset($source->{$fieldName})) { $property = $source->{$fieldName}; } } return $property instanceof Closure ? $property($source, $args, $context, $info) : $property; }
php
{ "resource": "" }
q242251
Lexer.readName
validation
private function readName($line, $col, Token $prev) { $value = ''; $start = $this->position; [$char, $code] = $this->readChar(); while ($code && ( $code === 95 || // _ $code >= 48 && $code <= 57 || // 0-9 $code >= 65 && $code <= 90 || // A-Z $code >= 97 && $code <= 122 // a-z )) { $value .= $char; [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); } return new Token( Token::NAME, $start, $this->position, $line, $col, $prev, $value ); }
php
{ "resource": "" }
q242252
Lexer.readNumber
validation
private function readNumber($line, $col, Token $prev) { $value = ''; $start = $this->position; [$char, $code] = $this->readChar(); $isFloat = false; if ($code === 45) { // - $value .= $char; [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); } // guard against leading zero's if ($code === 48) { // 0 $value .= $char; [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); if ($code >= 48 && $code <= 57) { throw new SyntaxError( $this->source, $this->position, 'Invalid number, unexpected digit after 0: ' . Utils::printCharCode($code) ); } } else { $value .= $this->readDigits(); [$char, $code] = $this->readChar(); } if ($code === 46) { // . $isFloat = true; $this->moveStringCursor(1, 1); $value .= $char; $value .= $this->readDigits(); [$char, $code] = $this->readChar(); } if ($code === 69 || $code === 101) { // E e $isFloat = true; $value .= $char; [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); if ($code === 43 || $code === 45) { // + - $value .= $char; $this->moveStringCursor(1, 1); } $value .= $this->readDigits(); } return new Token( $isFloat ? Token::FLOAT : Token::INT, $start, $this->position, $line, $col, $prev, $value ); }
php
{ "resource": "" }
q242253
Lexer.readDigits
validation
private function readDigits() { [$char, $code] = $this->readChar(); if ($code >= 48 && $code <= 57) { // 0 - 9 $value = ''; do { $value .= $char; [$char, $code] = $this->moveStringCursor(1, 1)->readChar(); } while ($code >= 48 && $code <= 57); // 0 - 9 return $value; } if ($this->position > $this->source->length - 1) { $code = null; } throw new SyntaxError( $this->source, $this->position, 'Invalid number, expected digit but got: ' . Utils::printCharCode($code) ); }
php
{ "resource": "" }
q242254
Lexer.readComment
validation
private function readComment($line, $col, Token $prev) { $start = $this->position; $value = ''; $bytes = 1; do { [$char, $code, $bytes] = $this->moveStringCursor(1, $bytes)->readChar(); $value .= $char; } while ($code && // SourceCharacter but not LineTerminator ($code > 0x001F || $code === 0x0009) ); return new Token( Token::COMMENT, $start, $this->position, $line, $col, $prev, $value ); }
php
{ "resource": "" }
q242255
Lexer.moveStringCursor
validation
private function moveStringCursor($positionOffset, $byteStreamOffset) { $this->position += $positionOffset; $this->byteStreamPosition += $byteStreamOffset; return $this; }
php
{ "resource": "" }
q242256
ServerConfig.setValidationRules
validation
public function setValidationRules($validationRules) { if (! is_callable($validationRules) && ! is_array($validationRules) && $validationRules !== null) { throw new InvariantViolation( 'Server config expects array of validation rules or callable returning such array, but got ' . Utils::printSafe($validationRules) ); } $this->validationRules = $validationRules; return $this; }
php
{ "resource": "" }
q242257
Type.isBuiltInType
validation
public static function isBuiltInType(Type $type) { return in_array($type->name, array_keys(self::getAllBuiltInTypes()), true); }
php
{ "resource": "" }
q242258
Type.getAllBuiltInTypes
validation
public static function getAllBuiltInTypes() { if (self::$builtInTypes === null) { self::$builtInTypes = array_merge( Introspection::getTypes(), self::getStandardTypes() ); } return self::$builtInTypes; }
php
{ "resource": "" }
q242259
QueryPlan.arrayMergeDeep
validation
private function arrayMergeDeep(array $array1, array $array2) : array { $merged = $array1; foreach ($array2 as $key => & $value) { if (is_numeric($key)) { if (! in_array($value, $merged, true)) { $merged[] = $value; } } elseif (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) { $merged[$key] = $this->arrayMergeDeep($merged[$key], $value); } else { $merged[$key] = $value; } } return $merged; }
php
{ "resource": "" }
q242260
Error.createLocatedError
validation
public static function createLocatedError($error, $nodes = null, $path = null) { if ($error instanceof self) { if ($error->path && $error->nodes) { return $error; } $nodes = $nodes ?: $error->nodes; $path = $path ?: $error->path; } $source = $positions = $originalError = null; $extensions = []; if ($error instanceof self) { $message = $error->getMessage(); $originalError = $error; $nodes = $error->nodes ?: $nodes; $source = $error->source; $positions = $error->positions; $extensions = $error->extensions; } elseif ($error instanceof Exception || $error instanceof Throwable) { $message = $error->getMessage(); $originalError = $error; } else { $message = (string) $error; } return new static( $message ?: 'An unknown error occurred.', $nodes, $source, $positions, $path, $originalError, $extensions ); }
php
{ "resource": "" }
q242261
Error.getLocations
validation
public function getLocations() { if ($this->locations === null) { $positions = $this->getPositions(); $source = $this->getSource(); $nodes = $this->nodes; if ($positions && $source) { $this->locations = array_map( static function ($pos) use ($source) { return $source->getLocation($pos); }, $positions ); } elseif ($nodes) { $locations = array_filter( array_map( static function ($node) { if ($node->loc && $node->loc->source) { return $node->loc->source->getLocation($node->loc->start); } }, $nodes ) ); $this->locations = array_values($locations); } else { $this->locations = []; } } return $this->locations; }
php
{ "resource": "" }
q242262
Error.toSerializableArray
validation
public function toSerializableArray() { $arr = [ 'message' => $this->getMessage(), ]; $locations = Utils::map( $this->getLocations(), static function (SourceLocation $loc) { return $loc->toSerializableArray(); } ); if (! empty($locations)) { $arr['locations'] = $locations; } if (! empty($this->path)) { $arr['path'] = $this->path; } if (! empty($this->extensions)) { $arr['extensions'] = $this->extensions; } return $arr; }
php
{ "resource": "" }
q242263
ReferenceExecutor.buildExecutionContext
validation
private static function buildExecutionContext( Schema $schema, DocumentNode $documentNode, $rootValue, $contextValue, $rawVariableValues, $operationName = null, ?callable $fieldResolver = null, ?PromiseAdapter $promiseAdapter = null ) { $errors = []; $fragments = []; /** @var OperationDefinitionNode $operation */ $operation = null; $hasMultipleAssumedOperations = false; foreach ($documentNode->definitions as $definition) { switch ($definition->kind) { case NodeKind::OPERATION_DEFINITION: if (! $operationName && $operation) { $hasMultipleAssumedOperations = true; } if (! $operationName || (isset($definition->name) && $definition->name->value === $operationName)) { $operation = $definition; } break; case NodeKind::FRAGMENT_DEFINITION: $fragments[$definition->name->value] = $definition; break; } } if ($operation === null) { if ($operationName) { $errors[] = new Error(sprintf('Unknown operation named "%s".', $operationName)); } else { $errors[] = new Error('Must provide an operation.'); } } elseif ($hasMultipleAssumedOperations) { $errors[] = new Error( 'Must provide operation name if query contains multiple operations.' ); } $variableValues = null; if ($operation !== null) { [$coercionErrors, $coercedVariableValues] = Values::getVariableValues( $schema, $operation->variableDefinitions ?: [], $rawVariableValues ?: [] ); if (empty($coercionErrors)) { $variableValues = $coercedVariableValues; } else { $errors = array_merge($errors, $coercionErrors); } } if (! empty($errors)) { return $errors; } Utils::invariant($operation, 'Has operation if no errors.'); Utils::invariant($variableValues !== null, 'Has variables if no errors.'); return new ExecutionContext( $schema, $fragments, $rootValue, $contextValue, $operation, $variableValues, $errors, $fieldResolver, $promiseAdapter ); }
php
{ "resource": "" }
q242264
ReferenceExecutor.executeOperation
validation
private function executeOperation(OperationDefinitionNode $operation, $rootValue) { $type = $this->getOperationRootType($this->exeContext->schema, $operation); $fields = $this->collectFields($type, $operation->selectionSet, new ArrayObject(), new ArrayObject()); $path = []; // Errors from sub-fields of a NonNull type may propagate to the top level, // at which point we still log the error and null the parent field, which // in this case is the entire response. // // Similar to completeValueCatchingError. try { $result = $operation->operation === 'mutation' ? $this->executeFieldsSerially($type, $rootValue, $path, $fields) : $this->executeFields($type, $rootValue, $path, $fields); if ($this->isPromise($result)) { return $result->then( null, function ($error) { $this->exeContext->addError($error); return $this->exeContext->promises->createFulfilled(null); } ); } return $result; } catch (Error $error) { $this->exeContext->addError($error); return null; } }
php
{ "resource": "" }
q242265
ReferenceExecutor.getOperationRootType
validation
private function getOperationRootType(Schema $schema, OperationDefinitionNode $operation) { switch ($operation->operation) { case 'query': $queryType = $schema->getQueryType(); if (! $queryType) { throw new Error( 'Schema does not define the required query root type.', [$operation] ); } return $queryType; case 'mutation': $mutationType = $schema->getMutationType(); if (! $mutationType) { throw new Error( 'Schema is not configured for mutations.', [$operation] ); } return $mutationType; case 'subscription': $subscriptionType = $schema->getSubscriptionType(); if (! $subscriptionType) { throw new Error( 'Schema is not configured for subscriptions.', [$operation] ); } return $subscriptionType; default: throw new Error( 'Can only execute queries, mutations and subscriptions.', [$operation] ); } }
php
{ "resource": "" }
q242266
ReferenceExecutor.getFieldEntryKey
validation
private static function getFieldEntryKey(FieldNode $node) { return $node->alias ? $node->alias->value : $node->name->value; }
php
{ "resource": "" }
q242267
ReferenceExecutor.doesFragmentConditionMatch
validation
private function doesFragmentConditionMatch( $fragment, ObjectType $type ) { $typeConditionNode = $fragment->typeCondition; if ($typeConditionNode === null) { return true; } $conditionalType = TypeInfo::typeFromAST($this->exeContext->schema, $typeConditionNode); if ($conditionalType === $type) { return true; } if ($conditionalType instanceof AbstractType) { return $this->exeContext->schema->isPossibleType($conditionalType, $type); } return false; }
php
{ "resource": "" }
q242268
ReferenceExecutor.executeFieldsSerially
validation
private function executeFieldsSerially(ObjectType $parentType, $sourceValue, $path, $fields) { $result = $this->promiseReduce( array_keys($fields->getArrayCopy()), function ($results, $responseName) use ($path, $parentType, $sourceValue, $fields) { $fieldNodes = $fields[$responseName]; $fieldPath = $path; $fieldPath[] = $responseName; $result = $this->resolveField($parentType, $sourceValue, $fieldNodes, $fieldPath); if ($result === self::$UNDEFINED) { return $results; } $promise = $this->getPromise($result); if ($promise) { return $promise->then(static function ($resolvedResult) use ($responseName, $results) { $results[$responseName] = $resolvedResult; return $results; }); } $results[$responseName] = $result; return $results; }, [] ); if ($this->isPromise($result)) { return $result->then(static function ($resolvedResults) { return self::fixResultsIfEmptyArray($resolvedResults); }); } return self::fixResultsIfEmptyArray($result); }
php
{ "resource": "" }
q242269
ReferenceExecutor.resolveField
validation
private function resolveField(ObjectType $parentType, $source, $fieldNodes, $path) { $exeContext = $this->exeContext; $fieldNode = $fieldNodes[0]; $fieldName = $fieldNode->name->value; $fieldDef = $this->getFieldDef($exeContext->schema, $parentType, $fieldName); if (! $fieldDef) { return self::$UNDEFINED; } $returnType = $fieldDef->getType(); // The resolve function's optional third argument is a collection of // information about the current execution state. $info = new ResolveInfo( $fieldName, $fieldNodes, $returnType, $parentType, $path, $exeContext->schema, $exeContext->fragments, $exeContext->rootValue, $exeContext->operation, $exeContext->variableValues ); if ($fieldDef->resolveFn !== null) { $resolveFn = $fieldDef->resolveFn; } elseif ($parentType->resolveFieldFn !== null) { $resolveFn = $parentType->resolveFieldFn; } else { $resolveFn = $this->exeContext->fieldResolver; } // The resolve function's optional third argument is a context value that // is provided to every resolve function within an execution. It is commonly // used to represent an authenticated user, or request-specific caches. $context = $exeContext->contextValue; // Get the resolve function, regardless of if its result is normal // or abrupt (error). $result = $this->resolveOrError( $fieldDef, $fieldNode, $resolveFn, $source, $context, $info ); $result = $this->completeValueCatchingError( $returnType, $fieldNodes, $info, $path, $result ); return $result; }
php
{ "resource": "" }
q242270
ReferenceExecutor.resolveOrError
validation
private function resolveOrError($fieldDef, $fieldNode, $resolveFn, $source, $context, $info) { try { // Build hash of arguments from the field.arguments AST, using the // variables scope to fulfill any variable references. $args = Values::getArgumentValues( $fieldDef, $fieldNode, $this->exeContext->variableValues ); return $resolveFn($source, $args, $context, $info); } catch (Exception $error) { return $error; } catch (Throwable $error) { return $error; } }
php
{ "resource": "" }
q242271
ReferenceExecutor.completeValueCatchingError
validation
private function completeValueCatchingError( Type $returnType, $fieldNodes, ResolveInfo $info, $path, $result ) { $exeContext = $this->exeContext; // If the field type is non-nullable, then it is resolved without any // protection from errors. if ($returnType instanceof NonNull) { return $this->completeValueWithLocatedError( $returnType, $fieldNodes, $info, $path, $result ); } // Otherwise, error protection is applied, logging the error and resolving // a null value for this field if one is encountered. try { $completed = $this->completeValueWithLocatedError( $returnType, $fieldNodes, $info, $path, $result ); $promise = $this->getPromise($completed); if ($promise) { return $promise->then( null, function ($error) use ($exeContext) { $exeContext->addError($error); return $this->exeContext->promises->createFulfilled(null); } ); } return $completed; } catch (Error $err) { // If `completeValueWithLocatedError` returned abruptly (threw an error), log the error // and return null. $exeContext->addError($err); return null; } }
php
{ "resource": "" }
q242272
ReferenceExecutor.completeValueWithLocatedError
validation
public function completeValueWithLocatedError( Type $returnType, $fieldNodes, ResolveInfo $info, $path, $result ) { try { $completed = $this->completeValue( $returnType, $fieldNodes, $info, $path, $result ); $promise = $this->getPromise($completed); if ($promise) { return $promise->then( null, function ($error) use ($fieldNodes, $path) { return $this->exeContext->promises->createRejected(Error::createLocatedError( $error, $fieldNodes, $path )); } ); } return $completed; } catch (Exception $error) { throw Error::createLocatedError($error, $fieldNodes, $path); } catch (Throwable $error) { throw Error::createLocatedError($error, $fieldNodes, $path); } }
php
{ "resource": "" }
q242273
ReferenceExecutor.completeValue
validation
private function completeValue( Type $returnType, $fieldNodes, ResolveInfo $info, $path, &$result ) { $promise = $this->getPromise($result); // If result is a Promise, apply-lift over completeValue. if ($promise) { return $promise->then(function (&$resolved) use ($returnType, $fieldNodes, $info, $path) { return $this->completeValue($returnType, $fieldNodes, $info, $path, $resolved); }); } if ($result instanceof Exception || $result instanceof Throwable) { throw $result; } // If field type is NonNull, complete for inner type, and throw field error // if result is null. if ($returnType instanceof NonNull) { $completed = $this->completeValue( $returnType->getWrappedType(), $fieldNodes, $info, $path, $result ); if ($completed === null) { throw new InvariantViolation( 'Cannot return null for non-nullable field ' . $info->parentType . '.' . $info->fieldName . '.' ); } return $completed; } // If result is null-like, return null. if ($result === null) { return null; } // If field type is List, complete each item in the list with the inner type if ($returnType instanceof ListOfType) { return $this->completeListValue($returnType, $fieldNodes, $info, $path, $result); } // Account for invalid schema definition when typeLoader returns different // instance than `resolveType` or $field->getType() or $arg->getType() if ($returnType !== $this->exeContext->schema->getType($returnType->name)) { $hint = ''; if ($this->exeContext->schema->getConfig()->typeLoader) { $hint = sprintf( 'Make sure that type loader returns the same instance as defined in %s.%s', $info->parentType, $info->fieldName ); } throw new InvariantViolation( sprintf( 'Schema must contain unique named types but contains multiple types named "%s". %s ' . '(see http://webonyx.github.io/graphql-php/type-system/#type-registry).', $returnType, $hint ) ); } // If field type is Scalar or Enum, serialize to a valid value, returning // null if serialization is not possible. if ($returnType instanceof LeafType) { return $this->completeLeafValue($returnType, $result); } if ($returnType instanceof AbstractType) { return $this->completeAbstractValue($returnType, $fieldNodes, $info, $path, $result); } // Field type must be Object, Interface or Union and expect sub-selections. if ($returnType instanceof ObjectType) { return $this->completeObjectValue($returnType, $fieldNodes, $info, $path, $result); } throw new RuntimeException(sprintf('Cannot complete value of unexpected type "%s".', $returnType)); }
php
{ "resource": "" }
q242274
ReferenceExecutor.getPromise
validation
private function getPromise($value) { if ($value === null || $value instanceof Promise) { return $value; } if ($this->exeContext->promises->isThenable($value)) { $promise = $this->exeContext->promises->convertThenable($value); if (! $promise instanceof Promise) { throw new InvariantViolation(sprintf( '%s::convertThenable is expected to return instance of GraphQL\Executor\Promise\Promise, got: %s', get_class($this->exeContext->promises), Utils::printSafe($promise) )); } return $promise; } return null; }
php
{ "resource": "" }
q242275
ReferenceExecutor.completeListValue
validation
private function completeListValue(ListOfType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) { $itemType = $returnType->getWrappedType(); Utils::invariant( is_array($result) || $result instanceof Traversable, 'User Error: expected iterable, but did not find one for field ' . $info->parentType . '.' . $info->fieldName . '.' ); $containsPromise = false; $i = 0; $completedItems = []; foreach ($result as $item) { $fieldPath = $path; $fieldPath[] = $i++; $completedItem = $this->completeValueCatchingError($itemType, $fieldNodes, $info, $fieldPath, $item); if (! $containsPromise && $this->getPromise($completedItem)) { $containsPromise = true; } $completedItems[] = $completedItem; } return $containsPromise ? $this->exeContext->promises->all($completedItems) : $completedItems; }
php
{ "resource": "" }
q242276
ReferenceExecutor.completeLeafValue
validation
private function completeLeafValue(LeafType $returnType, &$result) { try { return $returnType->serialize($result); } catch (Exception $error) { throw new InvariantViolation( 'Expected a value of type "' . Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result), 0, $error ); } catch (Throwable $error) { throw new InvariantViolation( 'Expected a value of type "' . Utils::printSafe($returnType) . '" but received: ' . Utils::printSafe($result), 0, $error ); } }
php
{ "resource": "" }
q242277
ReferenceExecutor.completeAbstractValue
validation
private function completeAbstractValue(AbstractType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) { $exeContext = $this->exeContext; $runtimeType = $returnType->resolveType($result, $exeContext->contextValue, $info); if ($runtimeType === null) { $runtimeType = self::defaultTypeResolver($result, $exeContext->contextValue, $info, $returnType); } $promise = $this->getPromise($runtimeType); if ($promise) { return $promise->then(function ($resolvedRuntimeType) use ( $returnType, $fieldNodes, $info, $path, &$result ) { return $this->completeObjectValue( $this->ensureValidRuntimeType( $resolvedRuntimeType, $returnType, $info, $result ), $fieldNodes, $info, $path, $result ); }); } return $this->completeObjectValue( $this->ensureValidRuntimeType( $runtimeType, $returnType, $info, $result ), $fieldNodes, $info, $path, $result ); }
php
{ "resource": "" }
q242278
ReferenceExecutor.completeObjectValue
validation
private function completeObjectValue(ObjectType $returnType, $fieldNodes, ResolveInfo $info, $path, &$result) { // If there is an isTypeOf predicate function, call it with the // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. $isTypeOf = $returnType->isTypeOf($result, $this->exeContext->contextValue, $info); if ($isTypeOf !== null) { $promise = $this->getPromise($isTypeOf); if ($promise) { return $promise->then(function ($isTypeOfResult) use ( $returnType, $fieldNodes, $path, &$result ) { if (! $isTypeOfResult) { throw $this->invalidReturnTypeError($returnType, $result, $fieldNodes); } return $this->collectAndExecuteSubfields( $returnType, $fieldNodes, $path, $result ); }); } if (! $isTypeOf) { throw $this->invalidReturnTypeError($returnType, $result, $fieldNodes); } } return $this->collectAndExecuteSubfields( $returnType, $fieldNodes, $path, $result ); }
php
{ "resource": "" }
q242279
ReferenceExecutor.executeFields
validation
private function executeFields(ObjectType $parentType, $source, $path, $fields) { $containsPromise = false; $finalResults = []; foreach ($fields as $responseName => $fieldNodes) { $fieldPath = $path; $fieldPath[] = $responseName; $result = $this->resolveField($parentType, $source, $fieldNodes, $fieldPath); if ($result === self::$UNDEFINED) { continue; } if (! $containsPromise && $this->getPromise($result)) { $containsPromise = true; } $finalResults[$responseName] = $result; } // If there are no promises, we can just return the object if (! $containsPromise) { return self::fixResultsIfEmptyArray($finalResults); } // Otherwise, results is a map from field name to the result // of resolving that field, which is possibly a promise. Return // a promise that will return this same map, but with any // promises replaced with the values they resolved to. return $this->promiseForAssocArray($finalResults); }
php
{ "resource": "" }
q242280
Value.printPath
validation
private static function printPath(?array $path = null) { $pathStr = ''; $currentPath = $path; while ($currentPath) { $pathStr = (is_string($currentPath['key']) ? '.' . $currentPath['key'] : '[' . $currentPath['key'] . ']') . $pathStr; $currentPath = $currentPath['prev']; } return $pathStr ? 'value' . $pathStr : ''; }
php
{ "resource": "" }
q242281
StandardServer.processPsrRequest
validation
public function processPsrRequest( ServerRequestInterface $request, ResponseInterface $response, StreamInterface $writableBodyStream ) { $result = $this->executePsrRequest($request); return $this->helper->toPsrResponse($result, $response, $writableBodyStream); }
php
{ "resource": "" }
q242282
SyncPromiseAdapter.wait
validation
public function wait(Promise $promise) { $this->beforeWait($promise); $dfdQueue = Deferred::getQueue(); $promiseQueue = SyncPromise::getQueue(); while ($promise->adoptedPromise->state === SyncPromise::PENDING && ! ($dfdQueue->isEmpty() && $promiseQueue->isEmpty()) ) { Deferred::runQueue(); SyncPromise::runQueue(); $this->onWait($promise); } /** @var SyncPromise $syncPromise */ $syncPromise = $promise->adoptedPromise; if ($syncPromise->state === SyncPromise::FULFILLED) { return $syncPromise->result; } if ($syncPromise->state === SyncPromise::REJECTED) { throw $syncPromise->result; } throw new InvariantViolation('Could not resolve promise'); }
php
{ "resource": "" }
q242283
Printer.printBlockString
validation
private function printBlockString($value, $isDescription) { $escaped = str_replace('"""', '\\"""', $value); return ($value[0] === ' ' || $value[0] === "\t") && strpos($value, "\n") === false ? ('"""' . preg_replace('/"$/', "\"\n", $escaped) . '"""') : ('"""' . "\n" . ($isDescription ? $escaped : $this->indent($escaped)) . "\n" . '"""'); }
php
{ "resource": "" }
q242284
FormattedError.printError
validation
public static function printError(Error $error) { $printedLocations = []; if ($error->nodes) { /** @var Node $node */ foreach ($error->nodes as $node) { if (! $node->loc) { continue; } if ($node->loc->source === null) { continue; } $printedLocations[] = self::highlightSourceAtLocation( $node->loc->source, $node->loc->source->getLocation($node->loc->start) ); } } elseif ($error->getSource() && $error->getLocations()) { $source = $error->getSource(); foreach ($error->getLocations() as $location) { $printedLocations[] = self::highlightSourceAtLocation($source, $location); } } return ! $printedLocations ? $error->getMessage() : implode("\n\n", array_merge([$error->getMessage()], $printedLocations)) . "\n"; }
php
{ "resource": "" }
q242285
FormattedError.highlightSourceAtLocation
validation
private static function highlightSourceAtLocation(Source $source, SourceLocation $location) { $line = $location->line; $lineOffset = $source->locationOffset->line - 1; $columnOffset = self::getColumnOffset($source, $location); $contextLine = $line + $lineOffset; $contextColumn = $location->column + $columnOffset; $prevLineNum = (string) ($contextLine - 1); $lineNum = (string) $contextLine; $nextLineNum = (string) ($contextLine + 1); $padLen = strlen($nextLineNum); $lines = preg_split('/\r\n|[\n\r]/', $source->body); $lines[0] = self::whitespace($source->locationOffset->column - 1) . $lines[0]; $outputLines = [ sprintf('%s (%s:%s)', $source->name, $contextLine, $contextColumn), $line >= 2 ? (self::lpad($padLen, $prevLineNum) . ': ' . $lines[$line - 2]) : null, self::lpad($padLen, $lineNum) . ': ' . $lines[$line - 1], self::whitespace(2 + $padLen + $contextColumn - 1) . '^', $line < count($lines) ? self::lpad($padLen, $nextLineNum) . ': ' . $lines[$line] : null, ]; return implode("\n", array_filter($outputLines)); }
php
{ "resource": "" }
q242286
FormattedError.createFromException
validation
public static function createFromException($e, $debug = false, $internalErrorMessage = null) { Utils::invariant( $e instanceof Exception || $e instanceof Throwable, 'Expected exception, got %s', Utils::getVariableType($e) ); $internalErrorMessage = $internalErrorMessage ?: self::$internalErrorMessage; if ($e instanceof ClientAware) { $formattedError = [ 'message' => $e->isClientSafe() ? $e->getMessage() : $internalErrorMessage, 'extensions' => [ 'category' => $e->getCategory(), ], ]; } else { $formattedError = [ 'message' => $internalErrorMessage, 'extensions' => [ 'category' => Error::CATEGORY_INTERNAL, ], ]; } if ($e instanceof Error) { $locations = Utils::map( $e->getLocations(), static function (SourceLocation $loc) { return $loc->toSerializableArray(); } ); if (! empty($locations)) { $formattedError['locations'] = $locations; } if (! empty($e->path)) { $formattedError['path'] = $e->path; } if (! empty($e->getExtensions())) { $formattedError['extensions'] = $e->getExtensions() + $formattedError['extensions']; } } if ($debug) { $formattedError = self::addDebugEntries($formattedError, $e, $debug); } return $formattedError; }
php
{ "resource": "" }
q242287
FormattedError.toSafeTrace
validation
public static function toSafeTrace($error) { $trace = $error->getTrace(); if (isset($trace[0]['function']) && isset($trace[0]['class']) && // Remove invariant entries as they don't provide much value: ($trace[0]['class'] . '::' . $trace[0]['function'] === 'GraphQL\Utils\Utils::invariant')) { array_shift($trace); } elseif (! isset($trace[0]['file'])) { // Remove root call as it's likely error handler trace: array_shift($trace); } return array_map( static function ($err) { $safeErr = array_intersect_key($err, ['file' => true, 'line' => true]); if (isset($err['function'])) { $func = $err['function']; $args = ! empty($err['args']) ? array_map([self::class, 'printVar'], $err['args']) : []; $funcStr = $func . '(' . implode(', ', $args) . ')'; if (isset($err['class'])) { $safeErr['call'] = $err['class'] . '::' . $funcStr; } else { $safeErr['function'] = $funcStr; } } return $safeErr; }, $trace ); }
php
{ "resource": "" }
q242288
OperationParams.create
validation
public static function create(array $params, bool $readonly = false) : OperationParams { $instance = new static(); $params = array_change_key_case($params, CASE_LOWER); $instance->originalInput = $params; $params += [ 'query' => null, 'queryid' => null, 'documentid' => null, // alias to queryid 'id' => null, // alias to queryid 'operationname' => null, 'variables' => null, 'extensions' => null, ]; if ($params['variables'] === '') { $params['variables'] = null; } // Some parameters could be provided as serialized JSON. foreach (['extensions', 'variables'] as $param) { if (! is_string($params[$param])) { continue; } $tmp = json_decode($params[$param], true); if (json_last_error()) { continue; } $params[$param] = $tmp; } $instance->query = $params['query']; $instance->queryId = $params['queryid'] ?: $params['documentid'] ?: $params['id']; $instance->operation = $params['operationname']; $instance->variables = $params['variables']; $instance->extensions = $params['extensions']; $instance->readOnly = $readonly; // Apollo server/client compatibility: look for the queryid in extensions if (isset($instance->extensions['persistedQuery']['sha256Hash']) && empty($instance->query) && empty($instance->queryId)) { $instance->queryId = $instance->extensions['persistedQuery']['sha256Hash']; } return $instance; }
php
{ "resource": "" }
q242289
BlockString.value
validation
public static function value($rawString) { // Expand a block string's raw value into independent lines. $lines = preg_split("/\\r\\n|[\\n\\r]/", $rawString); // Remove common indentation from all lines but first. $commonIndent = null; $linesLength = count($lines); for ($i = 1; $i < $linesLength; $i++) { $line = $lines[$i]; $indent = self::leadingWhitespace($line); if ($indent >= mb_strlen($line) || ($commonIndent !== null && $indent >= $commonIndent) ) { continue; } $commonIndent = $indent; if ($commonIndent === 0) { break; } } if ($commonIndent) { for ($i = 1; $i < $linesLength; $i++) { $line = $lines[$i]; $lines[$i] = mb_substr($line, $commonIndent); } } // Remove leading and trailing blank lines. while (count($lines) > 0 && trim($lines[0], " \t") === '') { array_shift($lines); } while (count($lines) > 0 && trim($lines[count($lines) - 1], " \t") === '') { array_pop($lines); } // Return a string of the lines joined with U+000A. return implode("\n", $lines); }
php
{ "resource": "" }
q242290
Values.getVariableValues
validation
public static function getVariableValues(Schema $schema, $varDefNodes, array $inputs) { $errors = []; $coercedValues = []; foreach ($varDefNodes as $varDefNode) { $varName = $varDefNode->variable->name->value; /** @var InputType|Type $varType */ $varType = TypeInfo::typeFromAST($schema, $varDefNode->type); if (Type::isInputType($varType)) { if (array_key_exists($varName, $inputs)) { $value = $inputs[$varName]; $coerced = Value::coerceValue($value, $varType, $varDefNode); /** @var Error[] $coercionErrors */ $coercionErrors = $coerced['errors']; if (empty($coercionErrors)) { $coercedValues[$varName] = $coerced['value']; } else { $messagePrelude = sprintf( 'Variable "$%s" got invalid value %s; ', $varName, Utils::printSafeJson($value) ); foreach ($coercionErrors as $error) { $errors[] = new Error( $messagePrelude . $error->getMessage(), $error->getNodes(), $error->getSource(), $error->getPositions(), $error->getPath(), $error, $error->getExtensions() ); } } } else { if ($varType instanceof NonNull) { $errors[] = new Error( sprintf( 'Variable "$%s" of required type "%s" was not provided.', $varName, $varType ), [$varDefNode] ); } elseif ($varDefNode->defaultValue) { $coercedValues[$varName] = AST::valueFromAST($varDefNode->defaultValue, $varType); } } } else { $errors[] = new Error( sprintf( 'Variable "$%s" expected value of type "%s" which cannot be used as an input type.', $varName, Printer::doPrint($varDefNode->type) ), [$varDefNode->type] ); } } if (! empty($errors)) { return [$errors, null]; } return [null, $coercedValues]; }
php
{ "resource": "" }
q242291
Values.getDirectiveValues
validation
public static function getDirectiveValues(Directive $directiveDef, $node, $variableValues = null) { if (isset($node->directives) && $node->directives instanceof NodeList) { $directiveNode = Utils::find( $node->directives, static function (DirectiveNode $directive) use ($directiveDef) { return $directive->name->value === $directiveDef->name; } ); if ($directiveNode !== null) { return self::getArgumentValues($directiveDef, $directiveNode, $variableValues); } } return null; }
php
{ "resource": "" }
q242292
Values.getArgumentValues
validation
public static function getArgumentValues($def, $node, $variableValues = null) { if (empty($def->args)) { return []; } $argumentNodes = $node->arguments; if (empty($argumentNodes)) { return []; } $argumentValueMap = []; foreach ($argumentNodes as $argumentNode) { $argumentValueMap[$argumentNode->name->value] = $argumentNode->value; } return static::getArgumentValuesForMap($def, $argumentValueMap, $variableValues, $node); }
php
{ "resource": "" }
q242293
BuildSchema.build
validation
public static function build($source, ?callable $typeConfigDecorator = null, array $options = []) { $doc = $source instanceof DocumentNode ? $source : Parser::parse($source); return self::buildAST($doc, $typeConfigDecorator, $options); }
php
{ "resource": "" }
q242294
BuildSchema.buildAST
validation
public static function buildAST(DocumentNode $ast, ?callable $typeConfigDecorator = null, array $options = []) { $builder = new self($ast, $typeConfigDecorator, $options); return $builder->buildSchema(); }
php
{ "resource": "" }
q242295
VariablesInAllowedPosition.varTypeAllowedForType
validation
private function varTypeAllowedForType($varType, $expectedType) { if ($expectedType instanceof NonNull) { if ($varType instanceof NonNull) { return $this->varTypeAllowedForType($varType->getWrappedType(), $expectedType->getWrappedType()); } return false; } if ($varType instanceof NonNull) { return $this->varTypeAllowedForType($varType->getWrappedType(), $expectedType); } if ($varType instanceof ListOfType && $expectedType instanceof ListOfType) { return $this->varTypeAllowedForType($varType->getWrappedType(), $expectedType->getWrappedType()); } return $varType === $expectedType; }
php
{ "resource": "" }
q242296
BreakingChangesFinder.findBreakingChanges
validation
public static function findBreakingChanges(Schema $oldSchema, Schema $newSchema) { return array_merge( self::findRemovedTypes($oldSchema, $newSchema), self::findTypesThatChangedKind($oldSchema, $newSchema), self::findFieldsThatChangedTypeOnObjectOrInterfaceTypes($oldSchema, $newSchema), self::findFieldsThatChangedTypeOnInputObjectTypes($oldSchema, $newSchema)['breakingChanges'], self::findTypesRemovedFromUnions($oldSchema, $newSchema), self::findValuesRemovedFromEnums($oldSchema, $newSchema), self::findArgChanges($oldSchema, $newSchema)['breakingChanges'], self::findInterfacesRemovedFromObjectTypes($oldSchema, $newSchema), self::findRemovedDirectives($oldSchema, $newSchema), self::findRemovedDirectiveArgs($oldSchema, $newSchema), self::findAddedNonNullDirectiveArgs($oldSchema, $newSchema), self::findRemovedDirectiveLocations($oldSchema, $newSchema) ); }
php
{ "resource": "" }
q242297
BreakingChangesFinder.findRemovedTypes
validation
public static function findRemovedTypes( Schema $oldSchema, Schema $newSchema ) { $oldTypeMap = $oldSchema->getTypeMap(); $newTypeMap = $newSchema->getTypeMap(); $breakingChanges = []; foreach (array_keys($oldTypeMap) as $typeName) { if (isset($newTypeMap[$typeName])) { continue; } $breakingChanges[] = [ 'type' => self::BREAKING_CHANGE_TYPE_REMOVED, 'description' => "${typeName} was removed.", ]; } return $breakingChanges; }
php
{ "resource": "" }
q242298
BreakingChangesFinder.findTypesThatChangedKind
validation
public static function findTypesThatChangedKind( Schema $schemaA, Schema $schemaB ) : iterable { $schemaATypeMap = $schemaA->getTypeMap(); $schemaBTypeMap = $schemaB->getTypeMap(); $breakingChanges = []; foreach ($schemaATypeMap as $typeName => $schemaAType) { if (! isset($schemaBTypeMap[$typeName])) { continue; } $schemaBType = $schemaBTypeMap[$typeName]; if ($schemaAType instanceof $schemaBType) { continue; } if ($schemaBType instanceof $schemaAType) { continue; } $schemaATypeKindName = self::typeKindName($schemaAType); $schemaBTypeKindName = self::typeKindName($schemaBType); $breakingChanges[] = [ 'type' => self::BREAKING_CHANGE_TYPE_CHANGED_KIND, 'description' => "${typeName} changed from ${schemaATypeKindName} to ${schemaBTypeKindName}.", ]; } return $breakingChanges; }
php
{ "resource": "" }
q242299
BreakingChangesFinder.findTypesRemovedFromUnions
validation
public static function findTypesRemovedFromUnions( Schema $oldSchema, Schema $newSchema ) { $oldTypeMap = $oldSchema->getTypeMap(); $newTypeMap = $newSchema->getTypeMap(); $typesRemovedFromUnion = []; foreach ($oldTypeMap as $typeName => $oldType) { $newType = $newTypeMap[$typeName] ?? null; if (! ($oldType instanceof UnionType) || ! ($newType instanceof UnionType)) { continue; } $typeNamesInNewUnion = []; foreach ($newType->getTypes() as $type) { $typeNamesInNewUnion[$type->name] = true; } foreach ($oldType->getTypes() as $type) { if (isset($typeNamesInNewUnion[$type->name])) { continue; } $typesRemovedFromUnion[] = [ 'type' => self::BREAKING_CHANGE_TYPE_REMOVED_FROM_UNION, 'description' => sprintf('%s was removed from union type %s.', $type->name, $typeName), ]; } } return $typesRemovedFromUnion; }
php
{ "resource": "" }