_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q242500
TreeCompiler.write
validation
private function write($str) { $this->source .= $this->indentation; if (func_num_args() == 1) { $this->source .= $str . "\n"; return $this; } $this->source .= vsprintf($str, array_slice(func_get_args(), 1)) . "\n"; return $this; }
php
{ "resource": "" }
q242501
Ups.createAccess
validation
protected function createAccess() { $xml = new DOMDocument(); $xml->formatOutput = true; // Create the AccessRequest element $accessRequest = $xml->appendChild($xml->createElement('AccessRequest')); $accessRequest->setAttribute('xml:lang', 'en-US'); $accessRequest->appendChild($xml->createElement('AccessLicenseNumber', $this->accessKey)); $accessRequest->appendChild($xml->createElement('UserId', $this->userId)); $p = $accessRequest->appendChild($xml->createElement('Password')); $p->appendChild($xml->createTextNode($this->password)); return $xml->saveXML(); }
php
{ "resource": "" }
q242502
Ups.createTransactionNode
validation
protected function createTransactionNode() { $xml = new DOMDocument(); $xml->formatOutput = true; $trxRef = $xml->appendChild($xml->createElement('TransactionReference')); if (null !== $this->context) { $trxRef->appendChild($xml->createElement('CustomerContext', $this->context)); } return $trxRef->cloneNode(true); }
php
{ "resource": "" }
q242503
Ups.compileEndpointUrl
validation
protected function compileEndpointUrl($segment) { $base = ($this->useIntegration ? $this->integrationBaseUrl : $this->productionBaseUrl); return $base.$segment; }
php
{ "resource": "" }
q242504
Shipping.createAcceptRequest
validation
private function createAcceptRequest($shipmentDigest) { $xml = new DOMDocument(); $xml->formatOutput = true; $container = $xml->appendChild($xml->createElement('ShipmentAcceptRequest')); $request = $container->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'ShipAccept')); $container->appendChild($xml->createElement('ShipmentDigest', $shipmentDigest)); return $xml->saveXML(); }
php
{ "resource": "" }
q242505
Shipping.createVoidRequest
validation
private function createVoidRequest($shipmentData) { $xml = new DOMDocument(); $xml->formatOutput = true; $container = $xml->appendChild($xml->createElement('VoidShipmentRequest')); $request = $container->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', '1')); if (is_string($shipmentData)) { $container->appendChild($xml->createElement('ShipmentIdentificationNumber', strtoupper($shipmentData))); } else { $expanded = $container->appendChild($xml->createElement('ExpandedVoidShipment')); $expanded->appendChild($xml->createElement('ShipmentIdentificationNumber', strtoupper($shipmentData['shipmentId']))); if (array_key_exists('trackingNumbers', $shipmentData)) { foreach ($shipmentData['trackingNumbers'] as $tn) { $expanded->appendChild($xml->createElement('TrackingNumber', strtoupper($tn))); } } } return $xml->saveXML(); }
php
{ "resource": "" }
q242506
Shipping.recoverLabel
validation
public function recoverLabel($trackingData, $labelSpecification = null, $labelDelivery = null, $translate = null) { if (is_array($trackingData)) { if (!isset($trackingData['value'])) { throw new InvalidArgumentException('$trackingData parameter is required to contain `value`.'); } if (!isset($trackingData['shipperNumber'])) { throw new InvalidArgumentException('$trackingData parameter is required to contain `shipperNumber`.'); } } if (!empty($translate)) { if (!isset($translateOpts['language'])) { $translateOpts['language'] = 'eng'; } if (!isset($translateOpts['dialect'])) { $translateOpts['dialect'] = 'US'; } } $request = $this->createRecoverLabelRequest($trackingData, $labelSpecification, $labelDelivery, $translate); $response = $this->request($this->createAccess(), $request, $this->compileEndpointUrl($this->recoverLabelEndpoint)); if ($response->Response->ResponseStatusCode == 0) { throw new Exception( "Failure ({$response->Response->Error->ErrorSeverity}): {$response->Response->Error->ErrorDescription}", (int)$response->Response->Error->ErrorCode ); } else { unset($response->Response); return $this->formatResponse($response); } }
php
{ "resource": "" }
q242507
Shipping.createRecoverLabelRequest
validation
private function createRecoverLabelRequest($trackingData, $labelSpecificationOpts = null, $labelDeliveryOpts = null, $translateOpts = null) { $xml = new DOMDocument(); $xml->formatOutput = true; $container = $xml->appendChild($xml->createElement('LabelRecoveryRequest')); $request = $container->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'LabelRecovery')); if (is_string($trackingData)) { $container->appendChild($xml->createElement('TrackingNumber', $trackingData)); } elseif (is_array($trackingData)) { $referenceNumber = $container->appendChild($xml->createElement('ReferenceNumber')); $referenceNumber->appendChild($xml->createElement('Value', $trackingData['value'])); $container->appendChild($xml->createElement('ShipperNumber', $trackingData['shipperNumber'])); } if (!empty($labelSpecificationOpts)) { $labelSpec = $request->appendChild($xml->createElement('LabelSpecification')); if (isset($labelSpecificationOpts['userAgent'])) { $labelSpec->appendChild($xml->createElement('HTTPUserAgent', $labelSpecificationOpts['userAgent'])); } if (isset($labelSpecificationOpts['imageFormat'])) { $format = $labelSpec->appendChild($xml->createElement('LabelImageFormat')); $format->appendChild($xml->createElement('Code', $labelSpecificationOpts['imageFormat'])); } } if (!empty($labelDeliveryOpts)) { $labelDelivery = $request->appendChild($xml->createElement('LabelDelivery')); $labelDelivery->appendChild($xml->createElement('LabelLinkIndicator', $labelDeliveryOpts['link'])); } if (!empty($translateOpts)) { $translate = $request->appendChild($xml->createElement('Translate')); $translate->appendChild($xml->createElement('LanguageCode', $translateOpts['language'])); $translate->appendChild($xml->createElement('DialectCode', $translateOpts['dialect'])); $translate->appendChild($xml->createElement('Code', '01')); } return $xml->saveXML(); }
php
{ "resource": "" }
q242508
LabelRecovery.createRequest
validation
private function createRequest($labelRecoveryRequest) { $xml = new DOMDocument(); $xml->formatOutput = true; $trackRequest = $xml->appendChild($xml->createElement('LabelRecoveryRequest')); $trackRequest->setAttribute('xml:lang', 'en-US'); $request = $trackRequest->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'LabelRecovery')); $labelSpecificationNode = $trackRequest->appendChild($xml->createElement('LabelSpecification')); if (isset($labelRecoveryRequest->LabelSpecification)) { $labelSpecificationNode->appendChild($xml->createElement('HTTPUserAgent', $labelRecoveryRequest->LabelSpecification->HTTPUserAgent)); $labelImageFormatNode = $labelSpecificationNode->appendChild($xml->createElement('LabelImageFormat')); $labelImageFormatNode->appendChild($xml->createElement('Code', $labelRecoveryRequest->LabelSpecification->LabelImageFormat->Code)); } if (isset($labelRecoveryRequest->Translate)) { $translateNode = $trackRequest->appendChild($xml->createElement('Translate')); $translateNode->appendChild($xml->createElement('LanguageCode', $labelRecoveryRequest->Translate->LanguageCode)); $translateNode->appendChild($xml->createElement('DialectCode', $labelRecoveryRequest->Translate->DialectCode)); $translateNode->appendChild($xml->createElement('Code', $labelRecoveryRequest->Translate->Code)); } if (isset($labelRecoveryRequest->LabelLinkIndicator)) { $labelLinkIndicatorNode = $trackRequest->appendChild($xml->createElement('LabelLinkIndicator')); $labelLinkIndicatorNode->appendChild($xml->createElement('LabelLinkIndicator')); } if (isset($labelRecoveryRequest->TrackingNumber)) { $trackRequest->appendChild($xml->createElement('TrackingNumber', $labelRecoveryRequest->TrackingNumber)); } if (isset($labelRecoveryRequest->ReferenceNumber)) { $referenceNumberNode = $trackRequest->appendChild($xml->createElement('ReferenceNumber')); $referenceNumberNode->appendChild($xml->createElement('Value', $labelRecoveryRequest->ReferenceNumber->getValue())); } if (isset($labelRecoveryRequest->ShipperNumber)) { $trackRequest->appendChild($xml->createElement('ShipperNumber', $labelRecoveryRequest->ShipperNumber)); } return $xml->saveXML(); }
php
{ "resource": "" }
q242509
SimpleAddressValidation.createRequest
validation
private function createRequest() { $xml = new DOMDocument(); $xml->formatOutput = true; $avRequest = $xml->appendChild($xml->createElement('AddressValidationRequest')); $avRequest->setAttribute('xml:lang', 'en-US'); $request = $avRequest->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'AV')); if (null !== $this->address) { $addressNode = $avRequest->appendChild($xml->createElement('Address')); if ($this->address->getStateProvinceCode()) { $addressNode->appendChild($xml->createElement('StateProvinceCode', $this->address->getStateProvinceCode())); } if ($this->address->getCity()) { $addressNode->appendChild($xml->createElement('City', $this->address->getCity())); } if ($this->address->getCountryCode()) { $addressNode->appendChild($xml->createElement('CountryCode', $this->address->getCountryCode())); } if ($this->address->getPostalCode()) { $addressNode->appendChild($xml->createElement('PostalCode', $this->address->getPostalCode())); } } return $xml->saveXML(); }
php
{ "resource": "" }
q242510
QuantumView.getSubscription
validation
public function getSubscription($name = null, $beginDateTime = null, $endDateTime = null, $fileName = null, $bookmark = null) { // Format date times if (null !== $beginDateTime) { $beginDateTime = $this->formatDateTime($beginDateTime); } if (null !== $endDateTime) { $endDateTime = $this->formatDateTime($endDateTime); } // If user provided a begin date time but no end date time, we assume the end date time is now if (null !== $beginDateTime && null === $endDateTime) { $endDateTime = $this->formatDateTime(time()); } $this->name = $name; $this->beginDateTime = $beginDateTime; $this->endDateTime = $endDateTime; $this->fileName = $fileName; $this->bookmark = $bookmark; // Create request $access = $this->createAccess(); $request = $this->createRequest(); $this->response = $this->getRequest()->request($access, $request, $this->compileEndpointUrl(self::ENDPOINT)); $response = $this->response->getResponse(); if (null === $response) { throw new Exception('Failure (0): Unknown error', 0); } if ($response->Response->ResponseStatusCode == 0) { throw new Exception( "Failure ({$response->Response->Error->ErrorSeverity}): {$response->Response->Error->ErrorDescription}", (int)$response->Response->Error->ErrorCode ); } else { if (isset($response->Bookmark)) { $this->setBookmark((string)$response->Bookmark); } else { $this->setBookmark(null); } return $this->formatResponse($response); } }
php
{ "resource": "" }
q242511
QuantumView.createRequest
validation
private function createRequest() { $xml = new DOMDocument(); $xml->formatOutput = true; // Create the QuantumViewRequest element $quantumViewRequest = $xml->appendChild($xml->createElement('QuantumViewRequest')); $quantumViewRequest->setAttribute('xml:lang', 'en-US'); // Create the SubscriptionRequest element if (null !== $this->name || null !== $this->beginDateTime || null !== $this->fileName) { $subscriptionRequest = $quantumViewRequest->appendChild($xml->createElement('SubscriptionRequest')); // Subscription name if (null !== $this->name) { $subscriptionRequest->appendChild($xml->createElement('Name', $this->name)); } // Date Time Range if (null !== $this->beginDateTime) { $dateTimeRange = $subscriptionRequest->appendChild($xml->createElement('DateTimeRange')); $dateTimeRange->appendChild($xml->createElement('BeginDateTime', $this->beginDateTime)); $dateTimeRange->appendChild($xml->createElement('EndDateTime', $this->endDateTime)); // File name } elseif (null !== $this->fileName) { $subscriptionRequest->appendChild($xml->createElement('FileName', $this->fileName)); } } // Create the Bookmark element if (null !== $this->bookmark) { $quantumViewRequest->appendChild($xml->createElement('Bookmark', $this->bookmark)); } // Create the Request element $request = $quantumViewRequest->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'QVEvents')); return $xml->saveXML(); }
php
{ "resource": "" }
q242512
AddressValidationResponse.noCandidates
validation
public function noCandidates() { if (AddressValidation::REQUEST_OPTION_ADDRESS_CLASSIFICATION == $this->requestAction) { throw new \BadMethodCallException(__METHOD__.' should not be called on Address Classification only requests.'); } return isset($this->response->NoCandidatesIndicator); }
php
{ "resource": "" }
q242513
AddressValidationResponse.isValid
validation
public function isValid() { if (AddressValidation::REQUEST_OPTION_ADDRESS_CLASSIFICATION == $this->requestAction) { return $this->response->AddressClassification->Code > 0; } return isset($this->response->ValidAddressIndicator); }
php
{ "resource": "" }
q242514
AddressValidationResponse.isAmbiguous
validation
public function isAmbiguous() { if (AddressValidation::REQUEST_OPTION_ADDRESS_CLASSIFICATION == $this->requestAction) { throw new \BadMethodCallException(__METHOD__.' should not be called on Address Classification only requests.'); } return isset($this->response->AmbiguousAddressIndicator); }
php
{ "resource": "" }
q242515
Tradeability.createRequestLandedCost
validation
private function createRequestLandedCost(LandedCostRequest $landedCostRequest) { $xml = new DOMDocument(); $xml->formatOutput = true; $tradeabilityRequest = $xml->appendChild($xml->createElement('LandedCostRequest')); $tradeabilityRequest->setAttribute('xml:lang', 'en-US'); $request = $tradeabilityRequest->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'LandedCost')); if ($landedCostRequest->getQueryRequest() !== null) { $tradeabilityRequest->appendChild($landedCostRequest->getQueryRequest()->toNode($xml)); } return $xml->saveXML(); }
php
{ "resource": "" }
q242516
Tradeability.sendRequest
validation
private function sendRequest($request, $endpoint, $operation, $wsdl) { $endpointurl = $this->compileEndpointUrl($endpoint); $this->response = $this->getRequest()->request( $this->createAccess(), $request, $endpointurl, $operation, $wsdl ); $response = $this->response->getResponse(); if (null === $response) { throw new Exception('Failure (0): Unknown error', 0); } return $this->formatResponse($response); }
php
{ "resource": "" }
q242517
Tracking.isMailInnovations
validation
private function isMailInnovations() { $patterns = [ // UPS Mail Innovations tracking numbers '/^MI\d{6}\d{1,22}$/',// MI 000000 00000000+ // USPS - Certified Mail '/^94071\d{17}$/', // 9407 1000 0000 0000 0000 00 '/^7\d{19}$/', // 7000 0000 0000 0000 0000 // USPS - Collect on Delivery '/^93033\d{17}$/', // 9303 3000 0000 0000 0000 00 '/^M\d{9}$/', // M000 0000 00 // USPS - Global Express Guaranteed '/^82\d{10}$/', // 82 000 000 00 // USPS - Priority Mail Express International '/^EC\d{9}US$/', // EC 000 000 000 US // USPS Innovations Expedited '/^927\d{23}$/', // 9270 8900 8900 8900 8900 8900 00 // USPS - Priority Mail Express '/^927\d{19}$/', // 9270 1000 0000 0000 0000 00 '/^EA\d{9}US$/', // EA 000 000 000 US // USPS - Priority Mail International '/^CP\d{9}US$/', // CP 000 000 000 US // USPS - Priority Mail '/^92055\d{17}$/', // 9205 5000 0000 0000 0000 00 '/^14\d{18}$/', // 1400 0000 0000 0000 0000 // USPS - Registered Mail '/^92088\d{17}$/', // 9208 8000 0000 0000 0000 00 '/^RA\d{9}US$/', // RA 000 000 000 US // USPS - Signature Confirmation '/^9202\d{16}US$/', // 9202 1000 0000 0000 0000 00 '/^23\d{16}US$/', // 2300 0000 0000 0000 0000 // USPS - Tracking '/^94\d{20}$/', // 9400 1000 0000 0000 0000 00 '/^03\d{18}$/' // 0300 0000 0000 0000 0000 ]; foreach ($patterns as $pattern) { if (preg_match($pattern, $this->trackingNumber)) { return true; } } return false; }
php
{ "resource": "" }
q242518
Tracking.createRequest
validation
private function createRequest() { $xml = new DOMDocument(); $xml->formatOutput = true; $trackRequest = $xml->appendChild($xml->createElement('TrackRequest')); $trackRequest->setAttribute('xml:lang', 'en-US'); $request = $trackRequest->appendChild($xml->createElement('Request')); $node = $xml->importNode($this->createTransactionNode(), true); $request->appendChild($node); $request->appendChild($xml->createElement('RequestAction', 'Track')); if (null !== $this->requestOption) { $request->appendChild($xml->createElement('RequestOption', $this->requestOption)); } if (null !== $this->trackingNumber) { $trackRequest->appendChild($xml->createElement('TrackingNumber', $this->trackingNumber)); } if ($this->isMailInnovations()) { $trackRequest->appendChild($xml->createElement('IncludeMailInnovationIndicator')); } if (null !== $this->referenceNumber) { $trackRequest->appendChild($xml->createElement('ReferenceNumber'))->appendChild($xml->createElement('Value', $this->referenceNumber)); } if (null !== $this->shipperNumber) { $trackRequest->appendChild($xml->createElement('ShipperNumber', $this->shipperNumber)); } if (null !== $this->beginDate || null !== $this->endDate) { $DateRange = $xml->createElement('PickupDateRange'); if (null !== $this->beginDate) { $beginDate = $this->beginDate->format('Ymd'); $DateRange->appendChild($xml->createElement('BeginDate', $beginDate)); } if (null !== $this->endDate) { $endDate = $this->endDate->format('Ymd'); $DateRange->appendChild($xml->createElement('EndDate', $endDate)); } $trackRequest->appendChild($DateRange); } return $xml->saveXML(); }
php
{ "resource": "" }
q242519
Utilities.addLocationInformation
validation
public static function addLocationInformation(stdClass $location, DOMNode $locationNode) { self::appendChild($location, 'CompanyName', $locationNode); self::appendChild($location, 'AttentionName', $locationNode); if (isset($location->Address)) { self::addAddressNode($location->Address, $locationNode); } }
php
{ "resource": "" }
q242520
ScopedJsonDecoder.extractSpaceId
validation
private function extractSpaceId(array $data): string { // Space resource if (isset($data['sys']['type']) && 'Space' === $data['sys']['type']) { return $data['sys']['id']; } // Environment resource if (isset($data['sys']['type']) && 'Environment' === $data['sys']['type']) { return $this->spaceId; } // Resource linked to a space if (isset($data['sys']['space'])) { return $data['sys']['space']['sys']['id']; } // Array resource with at least an element if (isset($data['items'][0]['sys']['space'])) { return $data['items'][0]['sys']['space']['sys']['id']; } // Empty array resource if (isset($data['items']) && !$data['items']) { return $this->spaceId; } return '[blank]'; }
php
{ "resource": "" }
q242521
ScopedJsonDecoder.extractEnvironmentId
validation
public function extractEnvironmentId(array $data): string { // Space resource if (isset($data['sys']['type']) && 'Space' === $data['sys']['type']) { return $this->environmentId; } // Environment resource if (isset($data['sys']['type']) && 'Environment' === $data['sys']['type']) { return $data['sys']['id']; } // Resource linked to a environment if (isset($data['sys']['environment'])) { return $data['sys']['environment']['sys']['id']; } // Array resource with at least an element if (isset($data['items'][0]['sys']['environment'])) { return $data['items'][0]['sys']['environment']['sys']['id']; } // Empty array resource if (isset($data['items']) && !$data['items']) { return $this->environmentId; } return 'master'; }
php
{ "resource": "" }
q242522
Asset.buildFile
validation
protected function buildFile(array $data): FileInterface { if (isset($data['uploadFrom'])) { return new LocalUploadFile( $data['fileName'], $data['contentType'], new Link( $data['uploadFrom']['sys']['id'], $data['uploadFrom']['sys']['linkType'] ) ); } if (isset($data['upload'])) { return new RemoteUploadFile( $data['fileName'], $data['contentType'], $data['upload'] ); } if (isset($data['details']['image'])) { return new ImageFile( $data['fileName'], $data['contentType'], $data['url'], $data['details']['size'], $data['details']['image']['width'], $data['details']['image']['height'] ); } return new File( $data['fileName'], $data['contentType'], $data['url'], $data['details']['size'] ); }
php
{ "resource": "" }
q242523
ContentType.getField
validation
public function getField(string $fieldId, bool $tryCaseInsensitive = false) { if (isset($this->fields[$fieldId])) { return $this->fields[$fieldId]; } if ($tryCaseInsensitive) { foreach ($this->fields as $name => $field) { if (\mb_strtolower($name) === \mb_strtolower($fieldId)) { return $field; } } } return null; }
php
{ "resource": "" }
q242524
ContentType.addUnknownField
validation
public function addUnknownField(string $name): Field { $this->fields[$name] = new Field($name, $name, 'Unknown'); return $this->fields[$name]; }
php
{ "resource": "" }
q242525
LinkResolver.resolveLinksForResourceType
validation
private function resolveLinksForResourceType(string $type, array $links, string $locale = null): array { $resourceIds = \array_map(function (Link $link): string { return $link->getId(); }, \array_filter($links, function (Link $link) use ($type): bool { return $link->getLinkType() === $type; })); $resources = []; $collection = $this->fetchResourcesForGivenIds($resourceIds, $type, $locale); foreach ($collection as $resource) { $resources[$type.'.'.$resource->getId()] = $resource; } return $resources; }
php
{ "resource": "" }
q242526
LinkResolver.fetchResourcesForGivenIds
validation
private function fetchResourcesForGivenIds(array $resourceIds, string $type, string $locale = null): array { $resources = []; $resourcePoolOptions = ['locale' => $locale]; foreach ($resourceIds as $index => $resourceId) { if ($this->resourcePool->has($type, $resourceId, $resourcePoolOptions)) { $resources[] = $this->resourcePool->get($type, $resourceId, $resourcePoolOptions); unset($resourceIds[$index]); } } foreach ($this->createIdChunks($resourceIds) as $chunk) { $resources += $this->fetchCollectionFromApi($chunk, $type, $locale); } return $resources; }
php
{ "resource": "" }
q242527
LinkResolver.createIdChunks
validation
private function createIdChunks(array $resourceIds): array { $chunks = []; $chunkId = -1; $resourceIds = \array_values($resourceIds); foreach ($resourceIds as $index => $resourceId) { if (0 === $index % 30) { ++$chunkId; $chunks[$chunkId] = []; } $chunks[$chunkId][] = $resourceId; } return $chunks; }
php
{ "resource": "" }
q242528
LinkResolver.fetchCollectionFromApi
validation
private function fetchCollectionFromApi(array $resourceIds, string $type, string $locale = null): array { $query = (new Query()) ->where('sys.id[in]', $resourceIds) ; if ('Asset' === $type || 'Entry' === $type) { $query->setLocale($locale); } switch ($type) { case 'Asset': return $this->client->getAssets($query)->getItems(); case 'ContentType': return $this->client->getContentTypes($query)->getItems(); case 'Entry': return $this->client->getEntries($query)->getItems(); case 'Environment': return [$this->client->getEnvironment()]; case 'Space': return [$this->client->getSpace()]; default: throw new \InvalidArgumentException(\sprintf( 'Trying to resolve link for unknown type "%s".', $type )); } }
php
{ "resource": "" }
q242529
ResourceBuilder.buildContentTypeCollection
validation
private function buildContentTypeCollection(array $data) { $items = \array_merge( $data['items'], $data['includes']['Entry'] ?? [] ); $ids = \array_map(function (array $item) { return 'Entry' === $item['sys']['type'] ? $item['sys']['contentType']['sys']['id'] : null; }, $items); $ids = \array_filter(\array_unique($ids), function ($id): bool { return $id && !$this->resourcePool->has('ContentType', $id); }); if ($ids) { $query = (new Query()) ->where('sys.id[in]', \implode(',', $ids)) ; $this->client->getContentTypes($query); } }
php
{ "resource": "" }
q242530
Query.setType
validation
public function setType(string $type = null) { $validTypes = ['all', 'Asset', 'Entry', 'Deletion', 'DeletedAsset', 'DeletedEntry']; if (!\in_array($type, $validTypes, true)) { throw new \InvalidArgumentException(\sprintf( 'Unexpected type "%s".', $type )); } $this->type = $type; return $this; }
php
{ "resource": "" }
q242531
Query.setContentType
validation
public function setContentType($contentType) { if ($contentType instanceof ContentType) { $contentType = $contentType->getId(); } $this->contentType = $contentType; $this->setType('Entry'); return $this; }
php
{ "resource": "" }
q242532
Manager.continueSync
validation
public function continueSync($token): Result { if ($token instanceof Result) { if (!$this->isDeliveryApi && $token->isDone()) { throw new \RuntimeException('Can not continue syncing when using the Content Preview API.'); } $token = $token->getToken(); } $response = $this->client->syncRequest(['sync_token' => $token]); return $this->buildResult($response); }
php
{ "resource": "" }
q242533
Manager.buildResult
validation
private function buildResult(array $data): Result { $token = $this->getTokenFromResponse($data); $done = isset($data['nextSyncUrl']); $items = \array_map(function (array $item): ResourceInterface { return $this->builder->build($item); }, $data['items']); return new Result($items, $token, $done); }
php
{ "resource": "" }
q242534
Manager.getTokenFromResponse
validation
private function getTokenFromResponse(array $data): string { $url = $data['nextSyncUrl'] ?? $data['nextPageUrl']; $queryValues = []; \parse_str(\parse_url($url, \PHP_URL_QUERY), $queryValues); return $queryValues['sync_token']; }
php
{ "resource": "" }
q242535
Factory.create
validation
public static function create(JsonDecoderClientInterface $client, ClientOptions $options): ResourcePoolInterface { if ($options->usesLowMemoryResourcePool()) { return new Standard($client->getApi(), $client->getSpaceId(), $client->getEnvironmentId()); } return new Extended( $client, $options->getCacheItemPool(), $options->hasCacheAutoWarmup(), $options->hasCacheContent() ); }
php
{ "resource": "" }
q242536
Entry.has
validation
public function has(string $name, string $locale = null, bool $checkLinksAreResolved = true): bool { $field = $this->sys->getContentType()->getField($name, true); if (!$field) { return false; } if (!\array_key_exists($field->getId(), $this->fields)) { return false; } try { $result = $this->getUnresolvedField($field, $locale); if ($checkLinksAreResolved) { $this->resolveFieldLinks($result, $locale); } } catch (\Exception $exception) { return false; } return true; }
php
{ "resource": "" }
q242537
Entry.getUnresolvedField
validation
private function getUnresolvedField(Field $field, string $locale = null) { // The field is not currently available on this resource, // but it exists in the content type, so we return an appropriate // default value. if (!isset($this->fields[$field->getId()])) { return 'Array' === $field->getType() ? [] : null; } $value = $this->fields[$field->getId()]; // This also checks two things: // * the compatibility of the given locale with the one present in sys.locale // * the existence of the given locale among those available in the environment // If we're trying to access locale X and the entry was built with locale Y, // or the environment does not support such locale, an exception will be thrown. // To allow accessing multiple locales on a single entry, fetching it // with locale=* is required. $locale = $this->getLocaleFromInput($locale); if (\array_key_exists($locale, $value)) { return $value[$locale]; } // If a field is not localized, it means that there are no values besides // $value[$defaultLocale], so because that check has already happened, we know // we're trying to access an invalid locale which is not correctly set. if (!$field->isLocalized()) { throw new \InvalidArgumentException(\sprintf( 'Trying to access the non-localized field "%s" on content type "%s" using the non-default locale "%s".', $field->getName(), $this->sys->getContentType()->getName(), $locale )); } // If we reach this point, it means: // * the field is localized // * we're trying to get a non-default locale // * the entry was not built using a specific locale (i.e. all locales for a field are available) // Therefore, we can inspect the fallback chain for a suitable locale. $locale = $this->walkFallbackChain($value, $locale, $this->sys->getEnvironment()); if ($locale) { return $value[$locale]; } return 'Array' === $field->getType() ? [] : null; }
php
{ "resource": "" }
q242538
Entry.resolveFieldLinks
validation
private function resolveFieldLinks($field, string $locale = null) { // If no locale is set, to resolve links we use either the special "*" locale, // or the default one, depending whether this entry was built using a locale or not if (null === $locale) { $locale = null === $this->sys->getLocale() ? '*' : $this->getLocale(); } if ($field instanceof Link) { return $this->client->resolveLink($field, $locale); } if (\is_array($field) && isset($field[0]) && $field[0] instanceof Link) { return $this->client->resolveLinkCollection($field, $locale); } return $field; }
php
{ "resource": "" }
q242539
Entry.getReferences
validation
public function getReferences(Query $query = null): ResourceArray { $query = $query ?: new Query(); $query->linksToEntry($this->getId()); return $this->client->getEntries($query); }
php
{ "resource": "" }
q242540
Entry.formatValue
validation
private function formatValue(string $type, $value, string $itemsType = null) { // Certain fields are already built as objects (Location, Link, DateTimeImmutable) // if the entry has already been built partially. // We restore these objects to their JSON implementations to avoid conflicts. if (\is_object($value) && $value instanceof \JsonSerializable) { $value = guzzle_json_decode(guzzle_json_encode($value), true); } if (null === $value) { return null; } switch ($type) { case 'Array': return \array_map(function ($value) use ($itemsType) { return $this->formatValue((string) $itemsType, $value); }, $value); case 'Date': return new DateTimeImmutable($value, new \DateTimeZone('UTC')); case 'Link': return new Link($value['sys']['id'], $value['sys']['linkType']); case 'Location': return new Location($value['lat'], $value['lon']); case 'RichText': return $this->richTextParser->parse($value); default: return $value; } }
php
{ "resource": "" }
q242541
Client.getLocaleForCacheKey
validation
private function getLocaleForCacheKey(string $locale = null): string { if ($locale) { return $locale; } return $this->getEnvironment()->getDefaultLocale()->getCode(); }
php
{ "resource": "" }
q242542
Client.parseJson
validation
public function parseJson(string $json) { return $this->builder->build( $this->scopedJsonDecoder->decode($json) ); }
php
{ "resource": "" }
q242543
Environment.getDefaultLocale
validation
public function getDefaultLocale(): Locale { foreach ($this->locales as $locale) { if ($locale->isDefault()) { return $locale; } } throw new \RuntimeException('No locale marked as default exists in this environment.'); }
php
{ "resource": "" }
q242544
Downloader.get
validation
public function get(string $path, array $headers = [], $cache = true): Response { if (null === $this->endpoint) { return new Response([]); } $headers[] = 'Package-Session: '.$this->sess; $url = $this->endpoint.'/'.ltrim($path, '/'); $cacheKey = $cache ? ltrim($path, '/') : ''; if ($cacheKey && $contents = $this->cache->read($cacheKey)) { $cachedResponse = Response::fromJson(json_decode($contents, true)); if ($lastModified = $cachedResponse->getHeader('last-modified')) { $response = $this->fetchFileIfLastModified($url, $cacheKey, $lastModified, $headers); if (304 === $response->getStatusCode()) { $response = new Response($cachedResponse->getBody(), $response->getOrigHeaders(), 304); } return $response; } } return $this->fetchFile($url, $cacheKey, $headers); }
php
{ "resource": "" }
q242545
ChatterDiscussionController.show
validation
public function show($category, $slug = null) { if (!isset($category) || !isset($slug)) { return redirect(config('chatter.routes.home')); } $discussion = Models::discussion()->where('slug', '=', $slug)->first(); if (is_null($discussion)) { abort(404); } $discussion_category = Models::category()->find($discussion->chatter_category_id); if ($category != $discussion_category->slug) { return redirect(config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$discussion_category->slug.'/'.$discussion->slug); } $posts = Models::post()->with('user')->where('chatter_discussion_id', '=', $discussion->id)->orderBy(config('chatter.order_by.posts.order'), config('chatter.order_by.posts.by'))->paginate(10); $chatter_editor = config('chatter.editor'); if ($chatter_editor == 'simplemde') { // Dynamically register markdown service provider \App::register('GrahamCampbell\Markdown\MarkdownServiceProvider'); } $discussion->increment('views'); return view('chatter::discussion', compact('discussion', 'posts', 'chatter_editor')); }
php
{ "resource": "" }
q242546
ChatterAtomController.index
validation
public function index() { $discussions = Discussion::limit(20)->orderBy('created_at', 'DESC')->get(); $discussions->load(['user', 'posts']); $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US"/>'); $xml->addChild('id', route('chatter.home')); $link = $xml->addChild('link'); $link->addAttribute('type', 'text/html'); $link->addAttribute('href', route('chatter.home')); $link = $xml->addChild('link'); $link->addAttribute('type', 'application/atom+xml'); $link->addAttribute('rel', 'self'); $link->addAttribute('href', route('chatter.atom')); $xml->addChild('title', config('app.name').' Discussions'); $updated = count($discussions) ? Carbon::parse($discussions[0]->created_at) : Carbon::now(); $xml->addChild('updated', $updated->toAtomString()); foreach ($discussions as $discussion) { $child = $xml->addChild('entry'); $child->addChild('id', route('chatter.discussion.show', ['discussion' => $discussion->slug])); $child->addChild('title', $discussion->title); $link = $child->addChild('link'); $link->addAttribute('type', 'text/html'); $link->addAttribute('rel', 'alternate'); $link->addAttribute('href', route('chatter.discussion.show', ['discussion' => $discussion->slug])); $child->addChild('updated', Carbon::parse($discussion->created_at)->toAtomString()); $author = $child->addChild('author'); $author->addChild('name', $discussion->user->name); $content = $child->addChild('content', htmlentities(count($discussion->posts) ? $discussion->posts[0]->body : '')); $content->addAttribute('type', 'html'); } return response($xml->asXML(), 200, [ 'Content-Type' => 'application/atom+xml', ]); }
php
{ "resource": "" }
q242547
ChatterPostController.destroy
validation
public function destroy($id, Request $request) { $post = Models::post()->with('discussion')->findOrFail($id); if ($request->user()->id !== (int) $post->user_id) { return redirect('/'.config('chatter.routes.home'))->with([ 'chatter_alert_type' => 'danger', 'chatter_alert' => trans('chatter::alert.danger.reason.destroy_post'), ]); } if ($post->discussion->posts()->oldest()->first()->id === $post->id) { if(config('chatter.soft_deletes')) { $post->discussion->posts()->delete(); $post->discussion()->delete(); } else { $post->discussion->posts()->forceDelete(); $post->discussion()->forceDelete(); } return redirect('/'.config('chatter.routes.home'))->with([ 'chatter_alert_type' => 'success', 'chatter_alert' => trans('chatter::alert.success.reason.destroy_post'), ]); } $post->delete(); $url = '/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$post->discussion->category->slug.'/'.$post->discussion->slug; return redirect($url)->with([ 'chatter_alert_type' => 'success', 'chatter_alert' => trans('chatter::alert.success.reason.destroy_from_discussion'), ]); }
php
{ "resource": "" }
q242548
ChatterHelper.replaceUrlParameter
validation
private static function replaceUrlParameter($url, $source) { $parameter = static::urlParameter($url); return str_replace('{'.$parameter.'}', $source[$parameter], $url); }
php
{ "resource": "" }
q242549
ChatterHelper.urlParameter
validation
private static function urlParameter($url) { $start = strpos($url, '{') + 1; $length = strpos($url, '}') - $start; return substr($url, $start, $length); }
php
{ "resource": "" }
q242550
ChatterHelper.demoteHtmlHeaderTags
validation
public static function demoteHtmlHeaderTags($html) { $originalHeaderTags = []; $demotedHeaderTags = []; foreach (range(100, 1) as $index) { $originalHeaderTags[] = '<h'.$index.'>'; $originalHeaderTags[] = '</h'.$index.'>'; $demotedHeaderTags[] = '<h'.($index + 1).'>'; $demotedHeaderTags[] = '</h'.($index + 1).'>'; } return str_ireplace($originalHeaderTags, $demotedHeaderTags, $html); }
php
{ "resource": "" }
q242551
ChatterHelper.categoriesMenu
validation
public static function categoriesMenu($categories) { $menu = '<ul class="nav nav-pills nav-stacked">'; foreach ($categories as $category) { $menu .= '<li>'; $menu .= '<a href="/'.config('chatter.routes.home').'/'.config('chatter.routes.category').'/'.$category['slug'].'">'; $menu .= '<div class="chatter-box" style="background-color:'.$category['color'].'"></div>'; $menu .= $category['name'].'</a>'; if (count($category['parents'])) { $menu .= static::categoriesMenu($category['parents']); } $menu .= '</li>'; } $menu .= '</ul>'; return $menu; }
php
{ "resource": "" }
q242552
SignatureMethod.checkSignature
validation
public function checkSignature(Request $request, Consumer $consumer, Token $token, $signature) { $built = $this->buildSignature($request, $consumer, $token); // Check for zero length, although unlikely here if (strlen($built) == 0 || strlen($signature) == 0) { return false; } if (strlen($built) != strlen($signature)) { return false; } // Avoid a timing leak with a (hopefully) time insensitive compare $result = 0; for ($i = 0; $i < strlen($signature); $i++) { $result |= ord($built{$i}) ^ ord($signature{$i}); } return $result == 0; }
php
{ "resource": "" }
q242553
Config.setTimeouts
validation
public function setTimeouts($connectionTimeout, $timeout) { $this->connectionTimeout = (int)$connectionTimeout; $this->timeout = (int)$timeout; }
php
{ "resource": "" }
q242554
Config.setRetries
validation
public function setRetries($maxRetries, $retriesDelay) { $this->maxRetries = (int)$maxRetries; $this->retriesDelay = (int)$retriesDelay; }
php
{ "resource": "" }
q242555
TwitterOAuth.url
validation
public function url($path, array $parameters) { $this->resetLastResponse(); $this->response->setApiPath($path); $query = http_build_query($parameters); return sprintf('%s/%s?%s', self::API_HOST, $path, $query); }
php
{ "resource": "" }
q242556
TwitterOAuth.get
validation
public function get($path, array $parameters = []) { return $this->http('GET', self::API_HOST, $path, $parameters, false); }
php
{ "resource": "" }
q242557
TwitterOAuth.post
validation
public function post($path, array $parameters = [], $json = false) { return $this->http('POST', self::API_HOST, $path, $parameters, $json); }
php
{ "resource": "" }
q242558
TwitterOAuth.delete
validation
public function delete($path, array $parameters = []) { return $this->http('DELETE', self::API_HOST, $path, $parameters, false); }
php
{ "resource": "" }
q242559
TwitterOAuth.put
validation
public function put($path, array $parameters = []) { return $this->http('PUT', self::API_HOST, $path, $parameters, false); }
php
{ "resource": "" }
q242560
TwitterOAuth.cleanUpParameters
validation
private function cleanUpParameters(array $parameters) { foreach ($parameters as $key => $value) { // PHP coerces `true` to `"1"` which some Twitter APIs don't like. if (is_bool($value)) { $parameters[$key] = var_export($value, true); } } return $parameters; }
php
{ "resource": "" }
q242561
TwitterOAuth.curlOptions
validation
private function curlOptions() { $options = [ // CURLOPT_VERBOSE => true, CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout, CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_USERAGENT => $this->userAgent, ]; if ($this->useCAFile()) { $options[CURLOPT_CAINFO] = __DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem'; } if ($this->gzipEncoding) { $options[CURLOPT_ENCODING] = 'gzip'; } if (!empty($this->proxy)) { $options[CURLOPT_PROXY] = $this->proxy['CURLOPT_PROXY']; $options[CURLOPT_PROXYUSERPWD] = $this->proxy['CURLOPT_PROXYUSERPWD']; $options[CURLOPT_PROXYPORT] = $this->proxy['CURLOPT_PROXYPORT']; $options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC; $options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP; } return $options; }
php
{ "resource": "" }
q242562
TwitterOAuth.request
validation
private function request($url, $method, $authorization, array $postfields, $json = false) { $options = $this->curlOptions(); $options[CURLOPT_URL] = $url; $options[CURLOPT_HTTPHEADER] = ['Accept: application/json', $authorization, 'Expect:']; switch ($method) { case 'GET': break; case 'POST': $options[CURLOPT_POST] = true; if ($json) { $options[CURLOPT_HTTPHEADER][] = 'Content-type: application/json'; $options[CURLOPT_POSTFIELDS] = json_encode($postfields); } else { $options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields); } break; case 'DELETE': $options[CURLOPT_CUSTOMREQUEST] = 'DELETE'; break; case 'PUT': $options[CURLOPT_CUSTOMREQUEST] = 'PUT'; break; } if (in_array($method, ['GET', 'PUT', 'DELETE']) && !empty($postfields)) { $options[CURLOPT_URL] .= '?' . Util::buildHttpQuery($postfields); } $curlHandle = curl_init(); curl_setopt_array($curlHandle, $options); $response = curl_exec($curlHandle); // Throw exceptions on cURL errors. if (curl_errno($curlHandle) > 0) { throw new TwitterOAuthException(curl_error($curlHandle), curl_errno($curlHandle)); } $this->response->setHttpCode(curl_getinfo($curlHandle, CURLINFO_HTTP_CODE)); $parts = explode("\r\n\r\n", $response); $responseBody = array_pop($parts); $responseHeader = array_pop($parts); $this->response->setHeaders($this->parseHeaders($responseHeader)); curl_close($curlHandle); return $responseBody; }
php
{ "resource": "" }
q242563
TwitterOAuth.parseHeaders
validation
private function parseHeaders($header) { $headers = []; foreach (explode("\r\n", $header) as $line) { if (strpos($line, ':') !== false) { list ($key, $value) = explode(': ', $line); $key = str_replace('-', '_', strtolower($key)); $headers[$key] = trim($value); } } return $headers; }
php
{ "resource": "" }
q242564
TwitterOAuth.encodeAppAuthorization
validation
private function encodeAppAuthorization(Consumer $consumer) { $key = rawurlencode($consumer->key); $secret = rawurlencode($consumer->secret); return base64_encode($key . ':' . $secret); }
php
{ "resource": "" }
q242565
JsonDecoder.decode
validation
public static function decode($string, $asArray) { if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { return json_decode($string, $asArray, 512, JSON_BIGINT_AS_STRING); } return json_decode($string, $asArray); }
php
{ "resource": "" }
q242566
Request.fromConsumerAndToken
validation
public static function fromConsumerAndToken( Consumer $consumer, Token $token = null, $httpMethod, $httpUrl, array $parameters = [], $json = false ) { $defaults = [ "oauth_version" => Request::$version, "oauth_nonce" => Request::generateNonce(), "oauth_timestamp" => time(), "oauth_consumer_key" => $consumer->key ]; if (null !== $token) { $defaults['oauth_token'] = $token->key; } // The json payload is not included in the signature on json requests, // therefore it shouldn't be included in the parameters array. if ($json) { $parameters = $defaults; } else { $parameters = array_merge($defaults, $parameters); } return new Request($httpMethod, $httpUrl, $parameters); }
php
{ "resource": "" }
q242567
Request.getSignableParameters
validation
public function getSignableParameters() { // Grab all parameters $params = $this->parameters; // Remove oauth_signature if present // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") if (isset($params['oauth_signature'])) { unset($params['oauth_signature']); } return Util::buildHttpQuery($params); }
php
{ "resource": "" }
q242568
Request.toUrl
validation
public function toUrl() { $postData = $this->toPostdata(); $out = $this->getNormalizedHttpUrl(); if ($postData) { $out .= '?' . $postData; } return $out; }
php
{ "resource": "" }
q242569
Option.get
validation
public function get($key, $default = null) { if ($option = self::where('key', $key)->first()) { return $option->value; } return $default; }
php
{ "resource": "" }
q242570
Option.set
validation
public function set($key, $value = null) { $keys = is_array($key) ? $key : [$key => $value]; foreach ($keys as $key => $value) { self::updateOrCreate(['key' => $key], ['value' => $value]); } // @todo: return the option }
php
{ "resource": "" }
q242571
AbstractAdapter.queryToMany
validation
public function queryToMany($relation, EncodingParametersInterface $parameters) { return $this->queryAllOrOne( $relation->newQuery(), $this->getQueryParameters($parameters) ); }
php
{ "resource": "" }
q242572
AbstractAdapter.queryToOne
validation
public function queryToOne($relation, EncodingParametersInterface $parameters) { return $this->queryOne( $relation->newQuery(), $this->getQueryParameters($parameters) ); }
php
{ "resource": "" }
q242573
AbstractAdapter.readWithFilters
validation
protected function readWithFilters($record, EncodingParametersInterface $parameters) { $query = $this->newQuery()->whereKey($record->getKey()); $this->applyFilters($query, collect($parameters->getFilteringParameters())); return $query->exists() ? $record : null; }
php
{ "resource": "" }
q242574
AbstractAdapter.applyFilters
validation
protected function applyFilters($query, Collection $filters) { /** By default we support the `id` filter. */ if ($this->isFindMany($filters)) { $this->filterByIds($query, $filters); } /** Hook for custom filters. */ $this->filter($query, $filters); }
php
{ "resource": "" }
q242575
AbstractAdapter.fillRelated
validation
protected function fillRelated( $record, ResourceObject $resource, EncodingParametersInterface $parameters ) { $relationships = $resource->getRelationships(); $changed = false; foreach ($relationships as $field => $value) { /** Skip any fields that are not fillable. */ if ($this->isNotFillable($field, $record)) { continue; } /** Skip any fields that are not relations */ if (!$this->isRelation($field)) { continue; } $relation = $this->getRelated($field); if ($this->requiresPrimaryRecordPersistence($relation)) { $relation->update($record, $value, $parameters); $changed = true; } } /** If there are changes, we need to refresh the model in-case the relationship has been cached. */ if ($changed) { $record->refresh(); } }
php
{ "resource": "" }
q242576
AbstractAdapter.paginate
validation
protected function paginate($query, EncodingParametersInterface $parameters) { if (!$this->paging) { throw new RuntimeException('Paging is not supported on adapter: ' . get_class($this)); } /** * Set the key name on the strategy, so it knows what column is being used * for the resource's ID. * * @todo 2.0 add `withQualifiedKeyName` to the paging strategy interface. */ if (method_exists($this->paging, 'withQualifiedKeyName')) { $this->paging->withQualifiedKeyName($this->getQualifiedKeyName()); } return $this->paging->paginate($query, $parameters); }
php
{ "resource": "" }
q242577
AbstractAdapter.queryAllOrOne
validation
protected function queryAllOrOne($query, EncodingParametersInterface $parameters) { $filters = collect($parameters->getFilteringParameters()); if ($this->isSearchOne($filters)) { return $this->queryOne($query, $parameters); } return $this->queryAll($query, $parameters); }
php
{ "resource": "" }
q242578
AbstractAdapter.getQueryParameters
validation
protected function getQueryParameters(EncodingParametersInterface $parameters) { return new EncodingParameters( $parameters->getIncludePaths(), $parameters->getFieldSets(), $parameters->getSortParameters() ?: $this->defaultSort(), $parameters->getPaginationParameters() ?: $this->defaultPagination(), $parameters->getFilteringParameters(), $parameters->getUnrecognizedParameters() ); }
php
{ "resource": "" }
q242579
LaravelJsonApi.defaultApi
validation
public static function defaultApi(string $name): self { if (empty($name)) { throw new \InvalidArgumentException('Default API name must not be empty.'); } self::$defaultApi = $name; return new self(); }
php
{ "resource": "" }
q242580
IdentityMap.add
validation
public function add(ResourceIdentifierInterface $identifier, $record) { if (!is_object($record) && !is_bool($record)) { throw new InvalidArgumentException('Expecting an object or a boolean to add to the identity map.'); } $existing = $this->lookup($identifier); if (is_object($existing) && is_bool($record)) { throw new InvalidArgumentException('Attempting to push a boolean into the map in place of an object.'); } $this->map[$identifier->toString()] = $record; return $this; }
php
{ "resource": "" }
q242581
IdentityMap.exists
validation
public function exists(ResourceIdentifierInterface $identifier) { $record = $this->lookup($identifier); return is_object($record) ? true : $record; }
php
{ "resource": "" }
q242582
IdentityMap.find
validation
public function find(ResourceIdentifierInterface $identifier) { $record = $this->lookup($identifier); if (false === $record) { return false; } return is_object($record) ? $record : null; }
php
{ "resource": "" }
q242583
JsonApiRequest.getParameters
validation
public function getParameters(): EncodingParametersInterface { if ($this->parameters) { return $this->parameters; } return $this->parameters = $this->container->make(EncodingParametersInterface::class); }
php
{ "resource": "" }
q242584
JsonApiRequest.isIndex
validation
public function isIndex(): bool { return $this->isMethod('get') && $this->getRoute()->isNotResource() && $this->getRoute()->isNotProcesses(); }
php
{ "resource": "" }
q242585
JsonApiRequest.isReadResource
validation
public function isReadResource(): bool { return $this->isMethod('get') && $this->getRoute()->isResource() && $this->getRoute()->isNotRelationship(); }
php
{ "resource": "" }
q242586
JsonApiRequest.isUpdateResource
validation
public function isUpdateResource(): bool { return $this->isMethod('patch') && $this->getRoute()->isResource() && $this->getRoute()->isNotRelationship(); }
php
{ "resource": "" }
q242587
JsonApiRequest.isDeleteResource
validation
public function isDeleteResource(): bool { return $this->isMethod('delete') && $this->getRoute()->isResource() && $this->getRoute()->isNotRelationship(); }
php
{ "resource": "" }
q242588
JsonApiRequest.isReadProcesses
validation
public function isReadProcesses(): bool { return $this->isMethod('get') && $this->getRoute()->isProcesses() && $this->getRoute()->isNotProcess(); }
php
{ "resource": "" }
q242589
AllowedFieldSets.allow
validation
public function allow(string $resourceType, array $fields = null): self { $this->all = false; $this->allowed[$resourceType] = $fields; return $this; }
php
{ "resource": "" }
q242590
AllowedFieldSets.any
validation
public function any(string ...$resourceTypes): self { foreach ($resourceTypes as $resourceType) { $this->allow($resourceType, null); } return $this; }
php
{ "resource": "" }
q242591
AllowedFieldSets.none
validation
public function none(string ...$resourceTypes): self { foreach ($resourceTypes as $resourceType) { $this->allow($resourceType, []); } return $this; }
php
{ "resource": "" }
q242592
AllowedFieldSets.allowed
validation
protected function allowed(string $resourceType, string $fields): bool { return $this->notAllowed($resourceType, $fields)->isEmpty(); }
php
{ "resource": "" }
q242593
AllowedFieldSets.notAllowed
validation
protected function notAllowed(string $resourceType, string $fields): Collection { $fields = collect(explode(',', $fields)); if (!$this->allowed->has($resourceType)) { return $fields; } $allowed = $this->allowed->get($resourceType); if (is_null($allowed)) { return collect(); } $allowed = collect((array) $allowed); return $fields->reject(function ($value) use ($allowed) { return $allowed->contains($value); }); }
php
{ "resource": "" }
q242594
AllowedFieldSets.invalid
validation
protected function invalid(): Collection { if (!is_array($this->value)) { return collect(); } return collect($this->value)->map(function ($value, $key) { return $this->notAllowed($key, $value); })->flatMap(function (Collection $fields, $type) { return $fields->map(function ($field) use ($type) { return "{$type}.{$field}"; }); }); }
php
{ "resource": "" }
q242595
SortsModels.sort
validation
protected function sort($query, array $sortBy) { /** @var SortParameterInterface $param */ foreach ($sortBy as $param) { $this->sortBy($query, $param); } }
php
{ "resource": "" }
q242596
SortsModels.defaultSort
validation
protected function defaultSort() { return collect($this->defaultSort)->map(function ($param) { $desc = ($param[0] === '-'); $field = ltrim($param, '-'); return new SortParameter($field, !$desc); })->all(); }
php
{ "resource": "" }
q242597
SortsModels.getSortColumn
validation
protected function getSortColumn($field, Model $model) { /** If there is a custom mapping, return that */ if (isset($this->sortColumns[$field])) { return $this->sortColumns[$field]; } return $model::$snakeAttributes ? Str::underscore($field) : Str::camelize($field); }
php
{ "resource": "" }
q242598
RouteRegistration.field
validation
public function field(string $field, string $inverse = null): self { $this->defaults = array_merge($this->defaults, [ ResourceRegistrar::PARAM_RELATIONSHIP_NAME => $field, ResourceRegistrar::PARAM_RELATIONSHIP_INVERSE_TYPE => $inverse ?: Str::plural($field), ]); return $this; }
php
{ "resource": "" }
q242599
Encoding.create
validation
public static function create( $mediaType, int $options = 0, string $urlPrefix = null, int $depth = 512 ): self { if (!$mediaType instanceof MediaTypeInterface) { $mediaType = MediaType::parse(0, $mediaType); } return new self($mediaType, new EncoderOptions($options, $urlPrefix, $depth)); }
php
{ "resource": "" }