sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function prepend($value, $key = null) { $this->items = ArrayHelper::prepend($this->items, $value, $key); return $this; }
Push an item onto the beginning of the collection. @param mixed $value @param mixed $key @return $this
entailment
public function sortByDesc($callback, int $options = SORT_REGULAR) { return $this->sortBy($callback, $options, true); }
Sort the collection in descending order using the given callback. @param callable|string $callback @param int $options @return static
entailment
public function unique($key = null, bool $strict = false) { if (is_null($key)) { return new static(array_unique($this->items, SORT_REGULAR)); } $callback = $this->valueRetriever($key); $exists = []; return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) { if (in_array($id = $callback($item, $key), $exists, $strict)) { return true; } $exists[] = $id; }); }
Return only unique items from the collection array. @param string|callable|null $key @param bool $strict @return static
entailment
protected function valueRetriever($value) { if ($this->useAsCallable($value)) { return $value; } return function ($item) use ($value) { return ArrayHelper::getValue($item, $value); }; }
Get a value retrieving callback. @param string $value @return callable
entailment
public function getCachingIterator(int $flags = CachingIterator::CALL_TOSTRING): CachingIterator { return new CachingIterator($this->getIterator(), $flags); }
Get a CachingIterator instance. @param int $flags @return CachingIterator
entailment
public function init() { if ($this->dataProvider === null) { throw new InvalidConfigException('The "dataProvider" property must be set'); } $this->channelAttributes = $this->getAttributes($this->channel); foreach ($this->requiredChannelElements as $channelElement) { if (!in_array($channelElement, $this->channelAttributes)) { throw new InvalidConfigException('Required channel attribute "' . $channelElement . '" must be set'); } } $this->itemAttributes = $this->getAttributes($this->items); foreach ($this->requiredItemElements as $itemElement) { if (!in_array($itemElement, $this->itemAttributes)) { throw new InvalidConfigException('Required item attribute "' . $itemElement . '" must be set'); } } $this->feed = new Feed; }
@inheritdoc @throws InvalidConfigException
entailment
public function run() { $this->renderChannel(); if ($this->dataProvider->getCount() > 0) { $this->renderItems(); } return $this->feed; }
@inheritdoc @return string|Feed
entailment
private function getAttributes($configArray) { $attributes = []; foreach ($configArray as $key => $value) { if (is_string($key)) { $attributes[] = $key; } else { if (is_string($value)) { $attributes[] = $value; } else { throw new InvalidConfigException('Wrong configured attribute'); } } } return $attributes; }
@param $configArray @return array @throws InvalidConfigException
entailment
public function validateSchema() { $meta_schema_validator = new SchemaValidator(); $json_loader = new JsonLoader(); // we have to check if we use a prefix $meta_json = file_get_contents(__DIR__.'/../../../data/MetaSchema.json'); $meta_json = str_replace('#', $this->prefix, $meta_json); // we validate the schema using the meta schema, defining the structure of our schema $meta_schema_validator->validate($json_loader->load($meta_json), $this->schema); return true; }
can take up to a second
entailment
public function getDocumentationForNode(array $keys = array(), $unfold_all = false) { $node = $this->findNode($this->schema['root'], $keys, $unfold_all); return array( 'name' => end($keys) ?: 'root', 'node' => $node, 'prefix' => $this->prefix ); }
get the documentation
entailment
public function getPrefixedMethodName($prefix, $name) { $name = $this->replaceDollar($name); return sprintf("%s%s", $prefix, Inflector::classify($name)); }
Get a method name given a prefix @param $prefix @param $name @return string
entailment
public function getClassName($name) { $name = $this->replaceDollar($name); $name = preg_replace_callback('#[/\{\}]+(\w)#', function ($matches) { return ucfirst($matches[1]); }, $name); $name = Inflector::classify($name); if (preg_match(self::BAD_CLASS_NAME_REGEX, $name)) { $name = '_'.$name; } return $name; }
Get a class name @param $name @return string
entailment
public function supportObject($object) { return ( ($object instanceof JsonSchema) && ( $object->getItems() instanceof JsonSchema || ( is_array($object->getItems()) && count($object->getItems()) > 0 ) ) ); }
{@inheritDoc}
entailment
protected function createGetter($name, Type $type, $namespace) { return new Stmt\ClassMethod( // getProperty $this->getNaming()->getPrefixedMethodName('get', $name), [ // public function 'type' => Stmt\Class_::MODIFIER_PUBLIC, 'stmts' => [ // return $this->property; new Stmt\Return_( new Expr\PropertyFetch(new Expr\Variable('this'), $this->getNaming()->getPropertyName($name)) ), ], ], [ 'comments' => [$this->createGetterDoc($type, $namespace)], ] ); }
Create get method. @param $name @param Type $type @param string $namespace @return Stmt\ClassMethod
entailment
protected function createSetter($name, Type $type, $namespace) { return new Stmt\ClassMethod( // setProperty $this->getNaming()->getPrefixedMethodName('set', $name), [ // public function 'type' => Stmt\Class_::MODIFIER_PUBLIC, // ($property) 'params' => [ new Param($this->getNaming()->getPropertyName($name), new Expr\ConstFetch(new Name('null')), $type->getTypeHint($namespace)), ], 'stmts' => [ // $this->property = $property; new Expr\Assign( new Expr\PropertyFetch( new Expr\Variable('this'), $this->getNaming()->getPropertyName($name) ), new Expr\Variable($this->getNaming()->getPropertyName($name)) ), // return $this; new Stmt\Return_(new Expr\Variable('this')), ], ], [ 'comments' => [$this->createSetterDoc($name, $type, $namespace)], ] ); }
Create set method. @param $name @param Type $type @param string $namespace @return Stmt\ClassMethod
entailment
protected function createSetterDoc($name, Type $type, $namespace) { return new Doc(sprintf(<<<EOD /** * @param %s %s * * @return self */ EOD , $type->getDocTypeHint($namespace), '$'.$this->getNaming()->getPropertyName($name))); }
Return doc for set method. @param $name @param Type $type @param string $namespace @return Doc
entailment
public function resolve($reference, $class) { $result = $reference; while ($result instanceof Reference) { $result = $result->resolve(function ($data) use($result, $class) { return $this->serializer->denormalize($data, $class, 'json', [ 'document-origin' => (string) $result->getMergedUri()->withFragment('') ]); }); } return $result; }
Resolve a reference with a denormalizer @param Reference $reference @param string $class @return mixed
entailment
public function listMetadataFormats($identifier = null) { $params = ($identifier) ? array('identifier' => $identifier) : array(); return new RecordIterator($this->client, 'ListMetadataFormats', $params); }
List Metadata Formats Return the list of supported metadata format for a particular record (if $identifier is provided), or the entire repository (if no arguments are provided) @param string $identifier If specified, will return only those metadata formats that a particular record supports @return RecordIteratorInterface
entailment
public function getRecord($id, $metadataPrefix) { $params = array( 'identifier' => $id, 'metadataPrefix' => $metadataPrefix ); return $this->client->request('GetRecord', $params); }
Get a single record @param string $id Record Identifier @param string $metadataPrefix Required by OAI-PMH endpoint @return \SimpleXMLElement An XML document corresponding to the record
entailment
public function listIdentifiers($metadataPrefix, $from = null, $until = null, $set = null, $resumptionToken = null) { return $this->createRecordIterator("ListIdentifiers", $metadataPrefix, $from, $until, $set, $resumptionToken); }
List Record identifiers Corresponds to OAI Verb to list record identifiers @param string $metadataPrefix Required by OAI-PMH endpoint @param \DateTimeInterface $from An optional 'from' date for selective harvesting @param \DateTimeInterface $until An optional 'until' date for selective harvesting @param string $set An optional setSpec for selective harvesting @param string $resumptionToken An optional resumptionToken for selective harvesting @return RecordIteratorInterface
entailment
private function createRecordIterator($verb, $metadataPrefix, $from, $until, $set = null, $resumptionToken = null) { $params = array('metadataPrefix' => $metadataPrefix); if ($from instanceof \DateTimeInterface) { $params['from'] = Granularity::formatDate($from, $this->getGranularity()); } elseif (null !== $from) { throw new \InvalidArgumentException(sprintf( '%s::%s $from parameter must be an instance of \DateTimeInterface', get_called_class(), 'createRecordIterator' )); } if ($until instanceof \DateTimeInterface) { $params['until'] = Granularity::formatDate($until, $this->getGranularity()); } elseif (null !== $until) { throw new \InvalidArgumentException(sprintf( '%s::%s $until parameter must be an instance of \DateTimeInterface', get_called_class(), 'createRecordIterator' )); } if ($set) { $params['set'] = $set; } return new RecordIterator($this->client, $verb, $params, $resumptionToken); }
Create a record iterator @param string $verb OAI Verb @param string $metadataPrefix Required by OAI-PMH endpoint @param \DateTimeInterface $from An optional 'from' date for selective harvesting @param \DateTimeInterface $until An optional 'from' date for selective harvesting @param string $set An optional setSpec for selective harvesting @param string $resumptionToken An optional resumptionToken for selective harvesting @return RecordIteratorInterface
entailment
private function getGranularity() { // If the granularity is not specified, attempt to retrieve it from the server // Fall back on DATE granularity if ($this->granularity === null) { $response = $this->identify(); return (isset($response->Identify->granularity)) ? (string) $response->Identify->granularity : Granularity::DATE; } return $this->granularity; }
Lazy load granularity from Identify, if not specified @return string
entailment
public function build($schema_config, $indent = true) { $this->schema_config = $schema_config; // we're gonna create XSD (XML) using a XmlWriter $writer = new \XMLWriter(); $writer->openMemory(); if ($indent) { $writer->setIndent(true); // will be easier to read $writer->setIndentString(' '); // soft tab, 4 spaces } $writer->startDocument('1.0', 'UTF-8'); // build writer - use a reference, we don't want to recopy it each time $this->buildRootNode($schema_config['root'][$this->getFullName('type')], $schema_config['root'], $writer); $writer->endDocument(); return $writer->outputMemory(); }
main function
entailment
public function buildRootNode($type, $node, \XMLWriter &$writer) { if ($type !== 'array') { throw new \Exception('Only array root nodes are supported'); } $writer->startElementNs('xsd', 'schema', 'http://www.w3.org/2001/XMLSchema'); foreach ($node[$this->getFullName('children')] as $key => $value) { $this->buildNode($key, $value[$this->getFullName('type')], $value, $writer, true); } $writer->endElement(); }
build nodes
entailment
public function merge(JsonSchema $left, JsonSchema $right) { $merged = clone $right; if ($left->getType() !== null && $right->getType() !== null && $left->getType() !== $right->getType()) { throw new \RuntimeException("Both types are defined and different, merge is not possible"); } if ($right->getType() === null && $left->getType() !== null) { $merged->setType($left->getType()); } $merged->setProperties($this->arrayMerge($left->getProperties(), $right->getProperties())); $merged->setRequired($this->arrayUnique($this->arrayMerge($left->getRequired(), $right->getRequired()))); return $merged; }
Create a new JsonSchema based on two merged schema @param JsonSchema $left @param JsonSchema $right @TODO Handle more fields @return JsonSchema
entailment
public function generate($schema, $className, Context $context) { $files = []; foreach ($schema->getClasses() as $class) { $properties = []; $methods = []; foreach ($class->getProperties() as $property) { $properties[] = $this->createProperty($property->getName(), $property->getType(), $schema->getNamespace()."\\Model"); $methods[] = $this->createGetter($property->getName(), $property->getType(), $schema->getNamespace()."\\Model"); $methods[] = $this->createSetter($property->getName(), $property->getType(), $schema->getNamespace()."\\Model"); } $model = $this->createModel( $class->getName(), $properties, $methods ); $namespace = new Stmt\Namespace_(new Name($schema->getNamespace()."\\Model"), [$model]); $files[] = new File($schema->getDirectory().'/Model/'.$class->getName().'.php', $namespace, self::FILE_TYPE_MODEL); } return $files; }
Generate a model given a schema @param Schema $schema Schema to generate from @param string $className Class to generate @param Context $context Context for generation @return File[]
entailment
final protected function hhmac($string, $api_key_secret) { $key = base64_decode($api_key_secret); $hashed = hash_hmac('sha256', $string, $key, true); $encoded = base64_encode($hashed); $signature = rtrim($encoded, "\n"); return strval($signature); }
Generate HMAC cryptographic hash. @param (string) $string Message to be hashed. @param (string) $api_key_secret Shared secret key used for generating the HMAC. @return (string) Authorization token used in the HTTP headers.
entailment
final protected function auth($string = '') { $canonical = strtoupper($this->method) . $this->path() . strval($this->datetime) . $string; $signature = $this->hhmac($canonical, $this->api_key_secret); return sprintf('HHMAC; key=%s; signature=%s; date=%s', $this->api_key_id, $signature, $this->datetime ); }
Create canonical version of the request as a byte-wise concatenation. @param (string) $string String to concatenate (see POST method). @return (string) HMAC cryptographic hash
entailment
protected function path() { $params = []; // Take arguments and pass them to the path by replacing {argument} tokens. foreach ($this->path_args as $argument => $value) { $params["{{$argument}}"] = $value; } $path = str_replace(array_keys($params), array_values($params), $this->path); return $this->endpoint . $path; }
Generate HTTP request URL. @return (string) URL to create request.
entailment
protected function initVars($method, $path, Array $path_args, Array $data) { $this->method = $method; $this->path = $path; $this->path_args = $path_args; }
Initialize variables needed to make a request. @param (string) $method Request method (POST/GET/DELETE). @param (string) $path Path to API endpoint. @param (array) $path_args Endpoint path arguments to replace tokens in the path. @param (array) $data Data to pass to the endpoint. @see PublisherAPI::post().
entailment
protected function onErrorResponse($error_code, $error_message, $response) { $message = print_r( [ 'code' => $error_code, 'message' => $error_message, 'response' => $response ], true ); $this->triggerError($message); }
Callback for error HTTP response. @param (int) $error_code HTTP status code. @param (string) $error_message HTTP status message. @param (object) $response Structured object.
entailment
public function get($path, Array $path_args, Array $data) { $this->initVars(__FUNCTION__, $path, $path_args, $data); }
Create GET request to a specified endpoint. @param (string) $path Path to API endpoint. @param (array) $path_args Endpoint path arguments to replace tokens in the path. @param (array) $data Raw content of the request or associative array to pass to endpoints. @return object Preprocessed structured object.
entailment
public function post($path, Array $path_args, Array $data) { $this->initVars(__FUNCTION__, $path, $path_args, $data); }
Create POST request to a specified endpoint. @param (string) $path Path to API endpoint. @param (array) $path_args Endpoint path arguments to replace tokens in the path. @param (array) $data Raw content of the request or associative array to pass to endpoints. @return object Preprocessed structured object.
entailment
public function delete($path, Array $path_args, Array $data) { $this->initVars(__FUNCTION__, $path, $path_args, $data); }
Create DELETE request to a specified endpoint. @param (string) $path Path to API endpoint. @param (array) $path_args Endpoint path arguments to replace tokens in the path. @param (array) $data Raw content of the request or associative array to pass to endpoints. @return object Preprocessed structured object and returns 204 No Content on success, with no response body.
entailment
public function jsonSerialize() { $valid = (!isset($this->backgroundColor) || $this->validateBackgroundColor($this->backgroundColor)); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
protected function request($urlSuffix, array $options) { $client = new Client([ 'base_uri' => $this->blizzardClient->getApiUrl(), ]); $options = $this->generateQueryOptions($options); return $client->get($this->serviceParam.$urlSuffix, $options); }
Request Make request with API url and specific URL suffix @param string $urlSuffix API URL method @param array $options Options @return ResponseInterface
entailment
private function generateQueryOptions(array $options = []) { if (isset($options['query'])) { $result = $options['query'] + $this->getDefaultOptions(); } else { $result['query'] = $options + $this->getDefaultOptions(); } return $result; }
Generate query options Setting default option to given options array if it does have 'query' key, otherwise creating 'query' key with default options @param array $options @return array
entailment
public function setBannerType($bannerType) { if (!in_array($bannerType, [ self::BANNER_TYPE_ANY, self::BANNER_TYPE_DOUBLE, self::BANNER_TYPE_LARGE, self::BANNER_TYPE_STANDARD, ])) { $this->triggerError('Invalid value for bannerType advertisingSettings.'); } else { $this->bannerType = $bannerType; } return $this; }
Setting for bannerType. @param string $bannerType The banner type that should be shown. One of 'any', 'standard', 'double_height', and 'large'. @return $this
entailment
public function setFrequency($frequency) { if ($frequency >= 0 && $frequency <= 10) { $this->frequency = $frequency; } else { $this->triggerError('Invalid value for frequency advertisingSettings.'); } return $this; }
Setter for frequency. @param int $frequency A number between 0 and 10 defining the frequency for automatically inserting advertising components into articles. @return $this
entailment
public function setTextStyle($value, Document $document = NULL) { $class = 'ChapterThree\AppleNewsAPI\Document\Styles\TextStyle'; if (is_string($value)) { // Check that value exists. if ($document && empty($document->getTextStyles()[$value]) ) { $this->triggerError("No TextStyle \"${value}\" found."); return $this; } } elseif (!$value instanceof $class) { $this->triggerError("Style not of class ${class}."); return $this; } $this->textStyle = $value; return $this; }
Setter for textStyle. @param string|\ChapterThree\AppleNewsAPI\Document\Styles\TextStyle $value Either a TextStyle object, or a string reference to one defined in $document. @param \ChapterThree\AppleNewsAPI\Document|NULL $document If required by first parameter. @return $this
entailment
public function jsonSerialize() { if (isset($this->rangeStart) && !isset($this->rangeLength)) { $msg = "If rangeStart is specified, rangeLength is required."; $this->triggerError($msg); return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function jsonSerialize() { $valid = (!isset($this->textAlignment) || $this->validateTextAlignment($this->textAlignment)); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function getInvoices($params = null, $headers = null) { $allowed = array('subject_id', 'since', 'updated_since', 'page', 'status', 'custom_id'); return $this->get('/invoices.json', $this->filterOptions($params, $allowed), $headers); }
/* Invoice
entailment
public function getExpenses($params = null, $headers = null) { $allowed = array('subject_id', 'since', 'updated_since', 'page', 'status'); return $this->get('/expenses.json', $this->filterOptions($params, $allowed), $headers); }
/* Expense
entailment
public function getSubjects($params = null, $headers = null) { $allowed = array('since', 'updated_since', 'page', 'custom_id'); return $this->get('/subjects.json', $this->filterOptions($params, $allowed), $headers); }
/* Subject
entailment
public function getGenerators($params = null, $headers = null) { $allowed = array('subject_id', 'since', 'updated_since', 'page'); return $this->get('/generators.json', $this->filterOptions($params, $allowed), $headers); }
/* Generator
entailment
public function getEvents($params = null, $headers = null) { return $this->get('/events.json', $this->filterOptions($params, array('subject_id', 'since', 'page')), $headers); }
/* Event
entailment
public function getTodos($params = null, $headers = null) { return $this->get('/todos.json', $this->filterOptions($params, array('subject_id', 'since', 'page')), $headers); }
/* Todo
entailment
private function get($path, $params = null, $headers = null) { return $this->run($path, array('method' => 'get', 'params' => $params, 'headers' => $headers)); }
/* Helper functions
entailment
private function run($path, $options) { $method = $options['method']; $data = isset($options['data']) ? $options['data'] : null; $params = isset($options['params']) ? $options['params'] : null; $headers = isset($options['headers']) ? $options['headers'] : array(); $body = !empty($data) ? json_encode($data) : null; // Arrays in constants are in PHP 5.6+ $allowedHeaders = array( 'If-None-Match', // Pairs with `ETag` response header. 'If-Modified-Since' // Pairs with `Last-Modified` response header. ); $headers = $this->filterOptions($headers, $allowedHeaders); $headers['User-Agent'] = $this->userAgent; $headers['Content-Type'] = 'application/json'; if (!empty($headers['If-Modified-Since']) && $headers['If-Modified-Since'] instanceof DateTime) { $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s \G\M\T', $headers['If-Modified-Since']->getTimestamp()); } $response = $this->requester->run(array( 'url' => self::URL . $this->slug . $path, 'method' => $method, 'params' => $params, 'body' => $body, 'userpwd' => "$this->email:$this->apiKey", 'headers' => $headers )); return $response; }
Execute HTTP method on path with data
entailment
public function setTargetAnchorPosition($value) { if ($this->validateTargetAnchorPosition($value)) { $this->targetAnchorPosition = (string) $value; } return $this; }
Setter for targetAnchorPosition. @param mixed $value TargetAnchorPosition. @return $this
entailment
public function jsonSerialize() { if (isset($this->rangeStart) && !isset($this->rangeLength)) { $msg = "If rangeStart is specified, rangeLength is required."; $this->triggerError($msg); return NULL; } $valid = (!isset($this->targetAnchorPosition) || $this->validateTargetAnchorPosition($this->targetAnchorPosition)); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function buildUrl($apiEndPoint) { if (is_null($this->request['url'])) { return $apiEndPoint . '/' . $this->uri . ($this->queryStr ? '?' . http_build_query($this->queryStr) : ''); } if (strpos($this->url, $apiEndPoint) !== 0) { throw new PaysafeException('Unexpected endpoint in url: ' . $this->url . ' expected: ' . $apiEndPoint); } return $this->url; }
Build url for the paysafe api client. @param string $apiEndPoint @return string @throws PaysafeException if the url has been set, and does not match the endpoint.
entailment
public function setLayout($layout, Document $document = NULL) { $class = 'ChapterThree\AppleNewsAPI\Document\Layouts\ComponentLayout'; if (is_string($layout)) { // Check that layout exists. if ($document && empty($document->getComponentLayouts()[$layout]) ) { $this->triggerError("No component layout \"${layout}\" found."); return $this; } } elseif (!$layout instanceof $class) { $this->triggerError("Layout not of class ${class}."); return $this; } $this->layout = $layout; return $this; }
Setter for layout. @param \ChapterThree\AppleNewsAPI\Document\Layouts\ComponentLayout|string $layout Either a ComponentLayout object, or a string reference to one defined in $document. @param \ChapterThree\AppleNewsAPI\Document|NULL $document If required by first parameter. @return $this
entailment
public function setStyle($style, Document $document = NULL) { $class = 'ChapterThree\AppleNewsAPI\Document\Styles\ComponentStyle'; if (is_string($style)) { // Check that style exists. if ($document && empty($document->getComponentStyles()[$style]) ) { $this->triggerError("No component style \"${style}\" found."); return $this; } } elseif (!$style instanceof $class) { $this->triggerError("Style not of class ${class}."); return $this; } $this->style = $style; return $this; }
Setter for style. @param \ChapterThree\AppleNewsAPI\Document\Styles\ComponentStyle|string $style Either a ComponentStyle object, or a string reference to one defined in $document. @param \ChapterThree\AppleNewsAPI\Document|NULL $document If required by first parameter. @return $this
entailment
public function jsonSerialize() { $valid = (!isset($this->textColor) || $this->validateTextColor($this->textColor)) && (!isset($this->backgroundColor) || $this->validateBackgroundColor($this->backgroundColor)); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function jsonSerialize() { $valid = (!isset($this->color) || $this->validateColor($this->color)); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function jsonSerialize() { $valid = !isset($this->preferredStartingPosition) || $this->validatePreferredStartingPosition($this->preferredStartingPosition); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function setColorStops(array $items) { if (isset($items[0]) && is_object($items[0]) && !$items[0] instanceof Fills\Gradients\ColorStop ) { $this->triggerError('Object not of type Gradients\ColorStop'); } else { $this->colorStops = $items; } return $this; }
Setter for url. @param array|\ChapterThree\AppleNewsAPI\Document\Styles\Fills\Gradients\ColorStop $items An array of color stops. Each stop sets a color and percentage. @return $this
entailment
public function getUser($accessToken = null, array $options = []) { if (null === $accessToken) { $options['access_token'] = $this->blizzardClient->getAccessToken(); } else { $options['access_token'] = $accessToken; } return $this->request('/account/user', $options); }
Get user Returns the account information of a user @param null|string $accessToken Authorized user access token @param array $options Options @return ResponseInterface
entailment
public function setItems(array $value) { if (isset($value[0]) && is_object($value[0]) && !$value[0] instanceof GalleryItem ) { $this->triggerError('Object not of type GalleryItem'); } else { $this->items = $value; } return $this; }
Setter for items. @param array $value Items. @return $this
entailment
public function authorize(CardPayments\Authorization $auth) { $auth->setRequiredFields(array( 'merchantRefNum', 'amount', 'card' )); $auth->setOptionalFields(array( 'settleWithAuth', 'profile', 'customerIp', 'dupCheck', 'description', 'authentication', 'billingDetails', 'shippingDetails', 'recurring', 'merchantDescriptor', 'accordD', 'description', 'splitpay', 'storedCredential' )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI("/auths"), 'body' => $auth )); $response = $this->client->processRequest($request); return new CardPayments\Authorization($response); }
Authorize. @param CardPayments\Authorization $auth @return CardPayments\Authorization @throws PaysafeException
entailment
public function cancelHeldAuth(CardPayments\Authorization $auth) { $auth->setRequiredFields(array('id')); $auth->checkRequiredFields(); $tmpAuth = new CardPayments\Authorization(array( 'status' => 'CANCELLED' )); $request = new Request(array( 'method' => Request::PUT, 'uri' => $this->prepareURI("/auths/" . $auth->id), 'body' => $tmpAuth )); $response = $this->client->processRequest($request); return new CardPayments\Authorization($response); }
Cancel held authorization. @param \Paysafe\CardPayments\Authorization $auth @return \Paysafe\CardPayments\Authorization @throws PaysafeException
entailment
public function reverseAuth(CardPayments\AuthorizationReversal $authReversal) { $authReversal->setRequiredFields(array('authorizationID')); $authReversal->checkRequiredFields(); $authReversal->setRequiredFields(array('merchantRefNum')); $authReversal->setOptionalFields(array( 'amount', 'dupCheck' )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI("/auths/" . $authReversal->authorizationID . "/voidauths"), 'body' => $authReversal )); $response = $this->client->processRequest($request); return new CardPayments\AuthorizationReversal($response); }
Reverse Authorization. @param \Paysafe\CardPayments\AuthorizationReversal $authReversal @return \Paysafe\CardPayments\AuthorizationReversal @throws PaysafeException
entailment
public function settlement(CardPayments\Settlement $settlement) { $settlement->setRequiredFields(array('authorizationID')); $settlement->checkRequiredFields(); $settlement->setRequiredFields(array('merchantRefNum')); $settlement->setOptionalFields(array( 'amount', 'dupCheck', 'splitpay', )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI("/auths/" . $settlement->authorizationID . "/settlements"), 'body' => $settlement )); $response = $this->client->processRequest($request); return new CardPayments\Settlement($response); }
Settlement. @param \Paysafe\CardPayments\Settlement $settlement @return \Paysafe\CardPayments\Settlement @throws PaysafeException
entailment
public function cancelSettlement(CardPayments\Settlement $settlement) { $settlement->setRequiredFields(array('id')); $settlement->checkRequiredFields(); $tmpSettlement = new CardPayments\Settlement(array( 'status' => 'CANCELLED' )); $request = new Request(array( 'method' => Request::PUT, 'uri' => $this->prepareURI("/settlements/" . $settlement->id), 'body' => $tmpSettlement )); $response = $this->client->processRequest($request); return new CardPayments\Settlement($response); }
Cancel settlement. @param \Paysafe\CardPayments\Settlement $settlement @return \Paysafe\CardPayments\Settlement @throws PaysafeException
entailment
public function refund(CardPayments\Refund $refund) { $refund->setRequiredFields(array('settlementID')); $refund->checkRequiredFields(); $refund->setRequiredFields(array('merchantRefNum')); $refund->setOptionalFields(array( 'amount', 'dupCheck', 'splitpay', )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI("/settlements/" . $refund->settlementID . "/refunds"), 'body' => $refund )); $response = $this->client->processRequest($request); return new CardPayments\Refund($response); }
Refund. @param \Paysafe\CardPayments\Refund $refund @return \Paysafe\CardPayments\Refund @throws PaysafeException
entailment
public function cancelRefund(CardPayments\Refund $refund) { $refund->setRequiredFields(array('id')); $refund->checkRequiredFields(); $tmpRefund = new CardPayments\Refund(array( 'status' => 'CANCELLED' )); $request = new Request(array( 'method' => Request::PUT, 'uri' => $this->prepareURI("/refunds/" . $refund->id), 'body' => $tmpRefund )); $response = $this->client->processRequest($request); return new CardPayments\Refund($response); }
Cancel Refund. @param \Paysafe\CardPayments\Refund $refund @return \Paysafe\CardPayments\Refund @throws PaysafeException
entailment
public function verify(CardPayments\Verification $verify) { $verify->setRequiredFields(array( 'merchantRefNum', 'card', )); $verify->setOptionalFields(array( 'profile', 'customerIp', 'dupCheck', 'description', 'billingDetails' )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI("/verifications"), 'body' => $verify )); $response = $this->client->processRequest($request); return new CardPayments\Verification($response); }
Verify. @param \Paysafe\CardPayments\Verification $verify @return \Paysafe\CardPayments\Verification @throws PaysafeException
entailment
public function getAuth(CardPayments\Authorization $auth) { $auth->setRequiredFields(array('id')); $auth->checkRequiredFields(); $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/auths/" . $auth->id) )); $response = $this->client->processRequest($request); return new CardPayments\Authorization($response); }
Get the authorization. @param CardPayments\Authorization $auth @return CardPayments\Authorization @throws PaysafeException
entailment
public function getAuthReversal(CardPayments\AuthorizationReversal $authReversal) { $authReversal->setRequiredFields(array('id')); $authReversal->checkRequiredFields(); $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/voidauths/" . $authReversal->id) )); $response = $this->client->processRequest($request); return new CardPayments\AuthorizationReversal($response); }
Get the authrozation reversal @param CardPayments\AuthorizationReversal $authReversal @return CardPayments\AuthorizationReversal @throws PaysafeException
entailment
public function getSettlement(CardPayments\Settlement $settlement) { $settlement->setRequiredFields(array('id')); $settlement->checkRequiredFields(); $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/settlements/" . $settlement->id) )); $response = $this->client->processRequest($request); return new CardPayments\Settlement($response); }
Get the settlement. @param CardPayments\Settlement $settlement @return CardPayments\Settlement @throws PaysafeException
entailment
public function getRefund(CardPayments\Refund $refund) { $refund->setRequiredFields(array('id')); $refund->checkRequiredFields(); $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/refunds/" . $refund->id) )); $response = $this->client->processRequest($request); return new CardPayments\Refund($response); }
Get the refund. @param CardPayments\Refund $refund @return CardPayments\Refund[] @throws PaysafeException
entailment
public function getVerification(CardPayments\Verification $verify) { $verify->setRequiredFields(array('id')); $verify->checkRequiredFields(); $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/verifications/" . $verify->id) )); $response = $this->client->processRequest($request); return new CardPayments\Verification($response); }
Get the verification. @param CardPayments\Verification $verify @return CardPayments\Verification @throws PaysafeException
entailment
public function getAuths(CardPayments\Authorization $auth = null, CardPayments\Filter $filter = null) { $queryStr = array(); if($auth && $auth->merchantRefNum) { $queryStr['merchantRefNum'] = $auth->merchantRefNum; } if($filter) { if(isset($filter->limit)) { $queryStr['limit'] = $filter->limit; } if(isset($filter->offset)) { $queryStr['offset'] = $filter->offset; } if(isset($filter->startDate)) { $queryStr['startDate'] = $filter->startDate; } if(isset($filter->endDate)) { $queryStr['endDate'] = $filter->endDate; } } $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/auths"), 'queryStr' => $queryStr )); $response = $this->client->processRequest($request); return new CardPayments\Pagerator($this->client, $response, '\Paysafe\CardPayments\Authorization'); }
Get matching authorizations. @param CardPayments\Authorization $auth @param CardPayments\Filter $filter @return CardPayments\Authorization[] iterator @throws PaysafeException
entailment
public function getAuthReversals(CardPayments\AuthorizationReversal $authReversal = null, CardPayments\Filter $filter = null) { $queryStr = array(); if($authReversal && $authReversal->merchantRefNum) { $queryStr['merchantRefNum'] = $authReversal->merchantRefNum; } if($filter) { if(isset($filter->limit)) { $queryStr['limit'] = $filter->limit; } if(isset($filter->offset)) { $queryStr['offset'] = $filter->offset; } if(isset($filter->startDate)) { $queryStr['startDate'] = $filter->startDate; } if(isset($filter->endDate)) { $queryStr['endDate'] = $filter->endDate; } } $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/voidauths"), 'queryStr' => $queryStr )); $response = $this->client->processRequest($request); return new CardPayments\Pagerator($this->client, $response, '\Paysafe\CardPayments\AuthorizationReversal'); }
Get matching authorization reversals. @param CardPayments\AuthorizationReversal $authReversal @param CardPayments\Filter $filter @return CardPayments\AuthorizationReversal[] iterator @throws PaysafeException
entailment
public function getSettlements(CardPayments\Settlement $settlement = null, CardPayments\Filter $filter = null) { $queryStr = array(); if($settlement && $settlement->merchantRefNum) { $queryStr['merchantRefNum'] = $settlement->merchantRefNum; } if($filter) { if(isset($filter->limit)) { $queryStr['limit'] = $filter->limit; } if(isset($filter->offset)) { $queryStr['offset'] = $filter->offset; } if(isset($filter->startDate)) { $queryStr['startDate'] = $filter->startDate; } if(isset($filter->endDate)) { $queryStr['endDate'] = $filter->endDate; } } $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/settlements"), 'queryStr' => $queryStr )); $response = $this->client->processRequest($request); return new CardPayments\Pagerator($this->client, $response, '\Paysafe\CardPayments\Settlement'); }
Get matching settlements. @param CardPayments\Settlement $settlement @param CardPayments\Filter $filter @return CardPayments\Settlement[] iterator @throws PaysafeException
entailment
public function getRefunds(CardPayments\Refund $refund = null, CardPayments\Filter $filter = null) { $queryStr = array(); if($refund && $refund->merchantRefNum) { $queryStr['merchantRefNum'] = $refund->merchantRefNum; } if($filter) { if(isset($filter->limit)) { $queryStr['limit'] = $filter->limit; } if(isset($filter->offset)) { $queryStr['offset'] = $filter->offset; } if(isset($filter->startDate)) { $queryStr['startDate'] = $filter->startDate; } if(isset($filter->endDate)) { $queryStr['endDate'] = $filter->endDate; } } $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/refunds"), 'queryStr' => $queryStr )); $response = $this->client->processRequest($request); return new CardPayments\Pagerator($this->client, $response, '\Paysafe\CardPayments\Refund'); }
Get matching refunds. @param CardPayments\Refund $refund @param CardPayments\Filter $filter @return CardPayments\Refund[] iterator @throws PaysafeException
entailment
public function getVerifications(CardPayments\Verification $verify = null, CardPayments\Filter $filter = null) { $queryStr = array(); if($verify && $verify->merchantRefNum) { $queryStr['merchantRefNum'] = $verify->merchantRefNum; } if($filter) { if(isset($filter->limit)) { $queryStr['limit'] = $filter->limit; } if(isset($filter->offset)) { $queryStr['offset'] = $filter->offset; } if(isset($filter->startDate)) { $queryStr['startDate'] = $filter->startDate; } if(isset($filter->endDate)) { $queryStr['endDate'] = $filter->endDate; } } $request = new Request(array( 'method' => Request::GET, 'uri' => $this->prepareURI("/verifications"), 'queryStr' => $queryStr )); $response = $this->client->processRequest($request); return new CardPayments\Pagerator($this->client, $response, '\Paysafe\CardPayments\Verification'); }
Get matching verifications. @param CardPayments\Verification $verify @param CardPayments\Filter $filter @return CardPayments\Verification[] iterator @throws PaysafeException
entailment
protected function setHeaders(Array $headers = []) { foreach ($headers as $property => $value) { $this->client->setHeader($property, $value); } }
Set HTTP headers. @param (array) $headers Associative array [header field name => value].
entailment
protected function unsetHeaders(Array $headers = []) { foreach ($headers as $property) { $this->client->unsetHeader($property); } }
Remove specified header names from HTTP request. @param (array) $headers Associative array [header1, header2, ..., headerN].
entailment
protected function request($data) { try { if ($this->method == 'delete') { $response = $this->client->{$this->method}($this->path(), [], $data); } else { $response = $this->client->{$this->method}($this->path(), $data); } $this->client->close(); } catch (\Exception $e) { // Throw an expection if something goes wrong. $this->triggerError($e->getMessage()); } return $this->response($response); }
Create HTTP request. @param (array|string) $data Raw content of the request or associative array to pass to endpoints. @return (object) HTTP Response object.
entailment
protected function response($response) { // Check for HTTP response error codes. if ($this->client->error) { $this->onErrorResponse( $this->client->errorCode, $this->client->errorMessage, $response ); } else { $this->onSuccessfulResponse($response); } return $response; }
Preprocess HTTP response. @param (object) $response Structured object. @return (object) HTTP Response object.
entailment
public function get($path, Array $path_args = [], Array $data = []) { parent::get($path, $path_args, $data); $this->setHeaders( [ 'Authorization' => $this->auth() ] ); return $this->request($data); }
Create GET request to a specified endpoint. @param (string) $path API endpoint path. @param (string) $path_args Endpoint path arguments to replace tokens in the path. @param (string) $data Raw content of the request or associative array to pass to endpoints. @return object Preprocessed structured object.
entailment
public function delete($path, Array $path_args = [], Array $data = []) { parent::delete($path, $path_args, $data); $this->setHeaders( [ 'Authorization' => $this->auth() ] ); $this->unsetHeaders( [ 'Content-Type' ] ); return $this->request($data); }
Create DELETE request to a specified endpoint. @param (string) $path API endpoint path. @param (string) $path_args Endpoint path arguments to replace tokens in the path. @param (string) $data Raw content of the request or associative array to pass to endpoints. @return object Preprocessed structured object and returns 204 No Content on success, with no response body.
entailment
public function post($path, Array $path_args, Array $data = []) { parent::post($path, $path_args, $data); // JSON string to be posted to PublisherAPI instead of article.json file. $json = !empty($data['json']) ? $data['json'] : ''; // Article assests (article.json, images, fonts etc...). $files = !empty($data['files']) ? $data['files'] : []; // Raw HTTP contents of the POST request. $multiparts = []; // Make sure you don't submit article.json if you passing json // as a parameter to Post method. if (!empty($json)) { $multiparts[] = $this->multipartPart( [ 'name' => 'article', 'filename' => 'article.json', 'mimetype' => 'application/json', 'size' => strlen($json) ], 'application/json', $json ); } // Article metadata. if (!empty($data['metadata'])) { $multiparts[] = $this->multipartPart( [ 'name' => 'metadata' ], 'application/json', $data['metadata'] ); } // Process each file and generate multipart form data. foreach ($files as $url => $path) { // Load file information. $info = $this->getFileInformation($path); $multiparts[] = $this->multipartPart( [ 'filename' => pathinfo($url, PATHINFO_BASENAME), 'name' => pathinfo($url, PATHINFO_FILENAME), 'size' => $info['size'], ], ($info['extension'] == 'json') ? 'application/json' : $info['mimetype'], $info['contents'] ); } // Set content type and boundary token. $content_type = sprintf('multipart/form-data; boundary=%s', $this->boundary); // Put together all the multipart data. $contents = $this->multipartFinalize($multiparts); // String to add to generate Authorization hash. $string = $content_type . $contents; // Make sure no USERAGENET in headers. $this->client->setOpt(CURLOPT_USERAGENT, NULL); $this->SetHeaders( [ 'Accept' => 'application/json', 'Content-Type' => $content_type, 'Content-Length' => strlen($contents), 'Authorization' => $this->auth($string) ] ); // Send POST request. return $this->request($contents); }
Create POST request to a specified endpoint. @param (string) $path API endpoint path. @param (array) $path_args Endpoint path arguments to replace tokens in the path. @param (array) $data Associative array to pass to endpoints, with keys: - json - JSON string. - files - Array of file paths keyed on URL used to reference file in json. - metadata - Associative array of metadata. @return object Preprocessed structured object.
entailment
protected function getFileInformation($path) { $file = pathinfo($path); $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimetype = finfo_file($finfo, $path); // Check if mimetype is supported. if (!in_array($mimetype, $this->valid_mimes)) { if ($mimetype == 'text/plain') { $mimetype = 'application/octet-stream'; } else { $this->triggerError('Unsupported mime type: ' . $mimetype); } } $contents = file_get_contents($path); return [ 'name' => str_replace(' ', '-', $file['filename']), 'filename' => $file['basename'], 'extension' => $file['extension'], 'mimetype' => $mimetype, 'contents' => $contents, 'size' => strlen($contents) ]; }
Get file information and its contents to upload. @param (string) $path Path to a file included in the POST request. @return (array) Associative array. The array contains information about a file.
entailment
protected function multipartPart(Array $attributes, $mimetype = null, $contents = null) { $multipart = ''; $headers = []; foreach ($attributes as $name => $value) { $headers[] = $name . '=' . $value; } // Generate multipart data and contents. $multipart .= '--' . $this->boundary . static::EOL; $multipart .= 'Content-Type: ' . $mimetype . static::EOL; $multipart .= 'Content-Disposition: form-data; ' . join('; ', $headers) . static::EOL; $multipart .= static::EOL . $contents . static::EOL; return $multipart; }
Generate individual multipart data parts. @param (array) $attributes Associative array with information about each file (mimetype, filename, size). @param (string) $mimetype Multipart mime type. @param (string) $contents Contents of the multipart content chunk. @return (string) Raw HTTP multipart chunk formatted according to the RFC. @see https://www.ietf.org/rfc/rfc2388.txt
entailment
protected function multipartFinalize(Array $multiparts = []) { $contents = ''; foreach ($multiparts as $multipart) { $contents .= $multipart; } $contents .= '--' . $this->boundary . '--'; $contents .= static::EOL; return $contents; }
Finalize multipart data. @param (array) $multiparts Multipart data with its headers. @return (string) Raw HTTP multipart data formatted according to the RFC. @see https://www.ietf.org/rfc/rfc2388.txt
entailment
protected function validateOpacity($value) { if (!is_numeric($value) || $value < 0 || $value > 100) { $this->triggerError('opacity is not valid'); return FALSE; } return TRUE; }
Validates the opacity attribute.
entailment
protected function validateRadius($value) { if (!is_numeric($value) || $value < 0 || $value > 100) { $this->triggerError('radius is not valid'); return FALSE; } return TRUE; }
Validates the radius attribute.
entailment
public function setCaption($value) { $class = CaptionDescriptor::class; if (is_object($value)) { if ($value instanceof $class) { $this->caption = $value; } else { $this->triggerError("Caption not of class ${class}."); } } else { $this->caption = (string) $value; } return $this; }
Setter for caption. @param string|CaptionDescriptor $value Caption. @return $this
entailment
private function filterHeaders() { $headers = array(); foreach ($this->headers as $name => $value) { if (strtolower($name) != 'user-agent') { $headers[] = "$name: $value"; } } return $headers; }
User-Agent header is sent differently.
entailment
public function current() { if (array_key_exists($this->position, $this->results)) { return $this->results[$this->position]; } }
Get the current element. @return mixed
entailment
public function next() { $this->position++; if (!$this->valid() && $this->nextPage) { $request = new \Paysafe\Request($this->nextPage); $this->nextPage = null; $response = $this->client->processRequest($request); $this->parseResponse($response); } }
Go to the next element
entailment
public function jsonSerialize() { $valid = (!isset($this->initialAlpha) || $this->validateInitialAlpha($this->initialAlpha)) && (!isset($this->initialScale) || $this->validateInitialScale($this->initialScale)); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function getHeroProfile($battleTag, $heroId, array $options = []) { return $this->request('/profile/'.(string) $battleTag.'/hero/'.(int) $heroId, $options); }
Get hero profile by battle tag and hero id Returns the hero profile of a Battle Tag's hero @param string $battleTag Battle Tag in name-#### format (ie. Noob-1234) @param string $heroId The hero id of the hero to look up @param array $options Options @return ResponseInterface
entailment
public function jsonSerialize() { $valid = !isset($this->initialAlpha) || $this->validateInitialAlpha($this->initialAlpha); if (!$valid) { return NULL; } return parent::jsonSerialize(); }
Implements JsonSerializable::jsonSerialize().
entailment
public function transferDebit(Transfer $transfer) { $transfer->setRequiredFields(array( 'amount', 'linkedAccount', 'merchantRefNum', )); $transfer->setOptionalFields(array( 'detail', 'dupCheck', )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI($this->debitPath), 'body' => $transfer )); $response = $this->client->processRequest($request); return new Transfer($response); }
Move funds from the account identified in the API endpoint URI to the linked account in the body of the request @param \Paysafe\AccountManagement\Transfer $transfer @return \Paysafe\AccountManagement\Transfer @throws \Paysafe\PaysafeException
entailment
public function transferCredit(Transfer $transfer) { $transfer->setRequiredFields(array( 'amount', 'linkedAccount', 'merchantRefNum', )); $transfer->setOptionalFields(array( 'detail', 'dupCheck', )); $request = new Request(array( 'method' => Request::POST, 'uri' => $this->prepareURI($this->creditPath), 'body' => $transfer )); $response = $this->client->processRequest($request); return new Transfer($response); }
Move funds from the linked account in the body of the request to the account identified in the API endpoint URI. @param \Paysafe\AccountManagement\Transfer $transfer @return \Paysafe\AccountManagement\Transfer
entailment