sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function parseKeysString($keyString) { // Replace all of the configured delimiters by the first one, so that we can then use explode(). $normalizedString = str_replace($this->delimiter, $this->delimiter[0], $keyString); return (array)explode($this->delimiter[0], $normalizedString); }
Extract individual keys from a delimited string. @since 0.1.6 @param string $keyString Delimited string of keys. @return array Array of key strings.
entailment
public function add($cookie, array $default = [], bool $nonempty = false): Cookies { if (!$cookie instanceof Cookie) { $cookie = new Cookie($cookie, $default); } //只允许非空cookie if ($nonempty && $cookie->value === '') { return $this; } // php array is a natural high-performance hash table // According to chrome's handling, path is only used as a cookie attribute, and the same domain+name is treated as the same cookie. $key = $cookie->domain . self::DELIMITER . $cookie->name; if (isset($this->raw[$key])) { //重置排序(tip:这会消耗很多性能) unset($this->raw[$key]); } $this->raw[$key] = $cookie; return $this; }
Write the complete Cookie object into the $cookie list of the only instance of Cookie @param array|string|Cookie $cookie @param array $default @param bool $nonempty @return Cookies
entailment
public function adds($cookies = [], array $default = [], bool $nonempty = false): Cookies { if (!empty($cookies)) { if ($cookies instanceof Cookies) { $this->raw = array_merge($this->raw, $cookies->raw); } else { if (is_array($cookies)) { if (isset($cookies[0])) { if (is_array($cookies[0])) { //[{array_obj},{array_obj}] array_obj=['name'=>'xxx','value'=>'xxx'] foreach ($cookies as $cookie) { $this->add($cookie, $default, $nonempty); } } else { if (is_string($cookies[0])) { foreach ($cookies as $cookie) { $this->add($cookie, $default, $nonempty); } } } } else { if (is_string(key($cookies))) { //['name'=>'value','name2'=>'value2'] foreach ($cookies as $name => $value) { $this->add(['name' => $name, 'value' => $value], $default, $nonempty); } } } } else { //request header string 'a=b; c=d;' $cookies = rtrim($cookies, '; '); //清除冗余字符 $arr = explode('; ', $cookies); foreach ($arr as $string) { $this->add($string, $default, $nonempty); } } } } return $this; }
Parse any formatted cookie and convert it into a Cookie object in the Cookies list Supports three formats ['name'=>'value',k=>v] | [['name'=>'xxx','value'=>'xxx']] | request_header_string:'a=b; c=d;' @param array|string $cookies @param array $default @param bool $nonempty @return Cookies
entailment
public function toRequestArray(string $uri = ''): array { $r = []; if (!empty($this->raw)) { $priorities = []; /** @var $cookie Cookie */ foreach ($this->raw as $cookie) { if ($cookie->isValid($uri)) { //Session cookie or unexpired && match domain path $priority = strlen($cookie->domain); //Record priority, the higher the match, the higher the priority if (!isset($r[$cookie->name]) || $priorities[$cookie->name] < $priority) { //The cookie of the name is not set or the cookie set has a lower priority than the current cookie $r[$cookie->name] = $cookie->value; $priorities[$cookie->name] = $priority; } } } } return $r; }
Turn Cookies into k=>v key-value pairs for Request @param string $uri 资源标记位置 @return array
entailment
public function toRequestString(string $uri = ''): string { return !empty($this->raw) ? self::kvToRequestString($this->toRequestArray($uri)) : ''; }
Convert Cookies to (k=v; k=v) key-value pair string for Request @param string $uri @return string
entailment
public function toResponse(): array { $r = []; foreach ($this->raw as $cookie) { $r[] = (string)$cookie; } return $r; }
Convert Cookies to a header array for Response @return array
entailment
public static function kvToRequestString(array $kv): string { $r = ''; foreach ($kv as $k => $v) { $r .= $k . '=' . $v . '; '; } $r = rtrim($r, '; '); return $r; }
Convert an array of key-value pairs to a string of the form (a=b; c=d) @param array $kv @return string
entailment
private function init(array $options, array $default = []): void { $options = array_merge($default, $options); //Check if the cookie is valid according to RFC 6265 if (empty($options['name']) && !is_numeric($options['name'])) { throw new InvalidArgumentException('Cookie must have its name!'); } // Check if any of the invalid characters are present in the cookie name if (preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $options['name'])) { throw new InvalidArgumentException( 'Cookie name must not contain invalid characters: ASCII ' . 'Control characters (0-31;127), space, tab and the ' . 'following characters: ()<>@,;:\"/?={}' ); } if (!empty($options['value']) && !isset($options['expires'])) { //有值但没有设定过期时间,是会话cookie $this->session = true; $this->expires = time(); } foreach ($options as $key => $val) { //insure value is the correct type if (isset($this->$key) && settype($val, gettype($this->$key)) && !empty($key)) { $this->$key = $val; } } //tip: (if it's necessary?) if (substr($this->path, 0, 1) !== '/') { $this->path = '/' . $this->path; // complete the leftmost "/" } //check is it hostonly if (substr($this->domain, 0, 1) === '.') { $this->domain = ltrim($this->domain, '.'); $this->hostonly = false; } }
initialization @param array $options @param array $default
entailment
public static function parseHeader(string $header): array { $cookie = []; $kvs = explode('; ', $header); $nv = explode('=', array_shift($kvs)); $cookie['name'] = $nv[0]; //because of some stupid system could return Set-Cookie: foo=''; so we must replace it. $cookie['value'] = str_replace(['\'\'', '""'], '', $nv[1]); foreach ($kvs as $kv) { $kv = explode('=', $kv); $kv[0] = strtolower($kv[0]); if (isset($kv[1])) { $cookie[$kv[0]] = $kv[1]; } else { $cookie[$kv[0]] = true; } } /** * If a response includes both an Expires header and a max-age directive, * the max-age directive overrides the Expires header! */ if (isset($cookie['max-age'])) { $cookie['expires'] = time() + $cookie['max-age']; } else { if (isset($cookie['expires'])) { $cookie['expires'] = strtotime($cookie['expires']); } } return $cookie; }
parse header string (aaa=bbb;Expires=123; Path=/;) to cookie array @param string $header @return array
entailment
public function toArray($simplify = false): array { $r = []; foreach ($this as $key => $val) { $r[$key] = $val; } if ($simplify) { $r = array_filter($r); } return $r; }
Convert this object to an array minimized @param bool $simplify @return array
entailment
public function isThere(string $uri): bool { if (empty($uri)) { return true; } $uri = parse_url($uri); //检查是否在路径中 if ($this->path !== '/' && strpos($uri['path'], rtrim($this->path, '/')) === false) { return false; } if ($this->hostonly) { return $this->domain === $uri['host']; } else { $rest = str_replace($this->domain, '', $uri['host'], $is_there); //uri的host中是否包含了该cookie的domain if ($is_there) { if (substr_count($rest, '.') > 1) { //通配符匹配,最多向下一级(参考chrome) return false; } else { return true; } } else { return false; } } }
Check if the cookie belongs to this url @param string $uri @return bool
entailment
public function isValid(string $uri = ''): bool { return !empty($this->value) && $this->isNotExpired() && $this->isThere($uri); }
Check whether the cookie takes effect in the url @param string $uri @return bool
entailment
public function runInstall(CommandLineArgumentContainer $commandLineArgumentContainer, CommandLineOptionContainer $commandLineOptionContainer, StyleInterface $style) { $this->getFactory()->createInstallRunner()->run($commandLineArgumentContainer, $commandLineOptionContainer, $style); }
@param \Spryker\Install\CommandLine\CommandLineArgumentContainer $commandLineArgumentContainer @param \Spryker\Install\CommandLine\CommandLineOptionContainer $commandLineOptionContainer @param \Spryker\Style\StyleInterface $style @return void
entailment
public function execute(StyleInterface $output): int { $process = $this->buildProcess(); $process->inheritEnvironmentVariables(true); $process->start(); foreach ($process as $buffer) { $output->innerCommand($buffer); } if (!$process->isSuccessful()) { $this->abortInstallIfNotAllowedToContinue($output); } return ($process->getExitCode() === null) ? static::CODE_SUCCESS : $process->getExitCode(); }
@param \Spryker\Style\StyleInterface $output @return int
entailment
protected function abortInstallIfNotAllowedToContinue(StyleInterface $output) { if ($this->command->breakOnFailure() || !$this->askToContinue($output)) { $output->flushBuffer(); throw new InstallException('Aborted install...'); } }
@param \Spryker\Style\StyleInterface $output @throws \Spryker\Install\Exception\InstallException @return void
entailment
protected function askToContinue(StyleInterface $output): bool { if (!$this->configuration->shouldAskBeforeContinueAfterException()) { return true; } $output->newLine(); $question = sprintf('Command <fg=yellow>%s</> failed! Continue with install?', $this->command->getName()); return $output->confirm($question, true); }
@param \Spryker\Style\StyleInterface $output @return bool
entailment
protected function validateCommands(array $configuration) { foreach ($configuration[static::SECTIONS] as $sectionName => $commands) { if ($commands === null || count($commands) === 0) { throw new ConfigurationException(sprintf('No commands defined in section "%s".', $sectionName)); } } }
@param array $configuration @throws \Spryker\Install\Configuration\Exception\ConfigurationException @return void
entailment
private function _userId($userId) { if (!$userId) { $currentUser = Craft::$app->getUser()->getIdentity(); if ($currentUser) { $userId = $currentUser->id; } } return (int)($userId); }
============== default values =============
entailment
protected function loadTranslatableMetadata($className, $config) { if (! isset($config[$className]) || ! isset($config[$className]['prezent']) || ! array_key_exists('translatable', $config[$className]['prezent']) ) { return; } $classMetadata = new TranslatableMetadata($className); $translatable = $config[$className]['prezent']['translatable'] ?: array(); $propertyMetadata = new PropertyMetadata( $className, // defaults to translatable isset($translatable['field']) ? $translatable['field'] : 'translations' ); // default targetEntity $targetEntity = $className . 'Translation'; $classMetadata->targetEntity = isset($translatable['targetEntity']) ? $translatable['targetEntity']: $targetEntity; $classMetadata->translations = $propertyMetadata; $classMetadata->addPropertyMetadata($propertyMetadata); if (isset($translatable['currentLocale'])) { $propertyMetadata = new PropertyMetadata($className, $translatable['currentLocale']); $classMetadata->currentLocale = $propertyMetadata; $classMetadata->addPropertyMetadata($propertyMetadata); } if (isset($translatable['fallbackLocale'])) { $propertyMetadata = new PropertyMetadata($className, $translatable['fallbackLocale']); $classMetadata->fallbackLocale = $propertyMetadata; $classMetadata->addPropertyMetadata($propertyMetadata); } return $classMetadata; }
Load metadata for a translatable class @param string $className @param mixed $config @return TranslatableMetadata|null
entailment
protected function loadTranslationMetadata($className, $config) { if (! isset($config[$className]) || ! isset($config[$className]['prezent']) || ! array_key_exists('translatable', $config[$className]['prezent']) ) { return; } $classMetadata = new TranslationMetadata($className); $translatable = $config[$className]['prezent']['translatable'] ?: array(); $propertyMetadata = new PropertyMetadata( $className, // defaults to translatable isset($translatable['field']) ? $translatable['field'] : 'translatable' ); $targetEntity = 'Translation' === substr($className, -11) ? substr($className, 0, -11) : null; $classMetadata->targetEntity = isset($translatable['targetEntity']) ? $translatable['targetEntity']: $targetEntity; $classMetadata->translatable = $propertyMetadata; $classMetadata->addPropertyMetadata($propertyMetadata); $locale = isset($translatable['locale']) ? $translatable['locale'] : 'locale'; $propertyMetadata = new PropertyMetadata($className, $locale); $classMetadata->locale = $propertyMetadata; $classMetadata->addPropertyMetadata($propertyMetadata); return $classMetadata; }
Load metadata for a translation class @param string $className @param mixed $config @return TranslationMetadata|null
entailment
public function load($uri) { try { $uri = $this->validateUri($uri); $data = $this->loadUri($uri); return $this->parseData($data); } catch (Exception $exception) { throw new FailedToLoadConfigException( sprintf( _('Could not load resource located at "%1$s". Reason: "%2$s".'), $uri, $exception->getMessage() ), $exception->getCode(), $exception ); } }
Load the configuration from an URI. @since 0.4.0 @param string $uri URI of the resource to load. @return array|null Data contained within the resource. Null if no data could be loaded/parsed. @throws FailedToLoadConfigException If the configuration could not be loaded.
entailment
public static function createFromUri($uri) { foreach (static::$loaders as $loader) { if ($loader::canLoad($uri)) { return static::getLoader($loader); } } throw new FailedToLoadConfigException( sprintf( _('Could not find a suitable loader for URI "%1$s".'), $uri ) ); }
Create a new Loader from an URI. @since 0.4.0 @param string $uri URI of the resource to create a loader for. @return LoaderInterface Loader that is able to load the given URI. @throws FailedToLoadConfigException If no suitable loader was found.
entailment
public static function getLoader($loaderClass) { try { if (! array_key_exists($loaderClass, static::$loaderInstances)) { static::$loaderInstances[$loaderClass] = new $loaderClass; } return static::$loaderInstances[$loaderClass]; } catch (Exception $exception) { throw new FailedToLoadConfigException( sprintf( _('Could not instantiate the requested loader class "%1$s".'), $loaderClass ) ); } }
Get an instance of a specific loader. The loader is lazily instantiated if needed. @since 0.4.0 @param string $loaderClass Fully qualified class name of the loader to get. @return LoaderInterface Instance of the requested loader. @throws FailedToLoadConfigException If the loader class could not be instantiated.
entailment
public function fire() { $filter = $this->argument('filter'); $verbose = $this->option('verbose'); $aliasLoader = AliasLoader::getInstance(); $first = true; foreach ($aliasLoader->getAliases() as $alias => $class) { // If a filter is given, only display aliases that start with that substring if ($filter && stripos($alias, $filter) !== 0) continue; // Put a blank line between each one if ($first) $first = false; else $this->line(''); // Display the alias name $this->comment($alias); // Display the class that this alias maps to and all of its parents $type = 'alias '; while ($class) { if ($verbose) $this->line("<info>$type ></info> $class"); else $this->line("<info>-></info> $class"); if ($this->isFacade($class)) { if ($verbose) { if ($accessor = $this->getFacadeAccessor($class)) $this->line("<info>facade ></info> <comment>App::make('$accessor')</comment>"); else $this->line("<info>facade ></info> <comment>$class::getFacadeRoot()</comment>"); } $type = 'resolve'; $class = get_class($class::getFacadeRoot()); } else { $type = 'parent '; $class = get_parent_class($class); } } } }
Execute the console command. @return void
entailment
public function log($message) { $formattedMessage = $this->formatMessage($message); if (!empty($formattedMessage)) { $this->logger->info($formattedMessage); } }
@param string|array $message @return void
entailment
private function formatMessage($message) { $formattedMessage = implode('', (array)$message); $formattedMessage = str_replace(PHP_EOL, '', $formattedMessage); $formattedMessage = strip_tags($formattedMessage); $formattedMessage = preg_replace([ '/\\x1b[[][^A-Za-z]*[A-Za-z]/', '/[-=]{2,}/', ], '', $formattedMessage); return $formattedMessage !== null ? trim($formattedMessage, " \t\n\r\0\x0B-=") : (string)$formattedMessage; }
@param string|array $message @return string
entailment
private static function _fromJson(&$json) { $fields = json_decode($json); if (is_null($fields)) { throw new UnexpectedResponseException( json_last_error_msg(), $json ); } return $fields; }
Attempts to parse the given JSON blob into an object. Uses `json_decode`. If parse fails then an exception is thrown. @param string $json the JSON text @return object an object as returned by `json_decode`
entailment
private static function _dateTime(&$json, $str) { try { return new \DateTime($str); } catch (\Exception $ex) { throw new UnexpectedResponseException($ex->getMessage(), $json); } }
Deserializes the given string into a `DateTime`. Assumes the string is in ISO-8601 format. @param string $json original JSON message @param string $str the string holding the date time @return DateTime a date time @throws UnexpectedResponseException if given invalid time string
entailment
private static function _batchResponseHelper( &$json, \stdClass &$fields, Api\MtBatchSmsResult &$object ) { $object->setBatchId($fields->id); $object->setRecipients($fields->to); $object->setSender($fields->from); $object->setCanceled($fields->canceled); if (isset($fields->delivery_report)) { $object->setDeliveryReport($fields->delivery_report); } if (isset($fields->send_at)) { $object->setSendAt( Deserialize::_dateTime($json, $fields->send_at) ); } if (isset($fields->expire_at)) { $object->setExpireAt( Deserialize::_dateTime($json, $fields->expire_at) ); } if (isset($fields->created_at)) { $object->setCreatedAt( Deserialize::_dateTime($json, $fields->created_at) ); } if (isset($fields->modified_at)) { $object->setModifiedAt( Deserialize::_dateTime($json, $fields->modified_at) ); } if (isset($fields->callback_url)) { $object->setCallbackUrl($fields->callback_url); } }
Helper that populates the given batch result. The batch result is populated from an object as returned by `json_decode`. @param string $json original JSON string @param object $fields the JSON fields @param Api\MtBatchSmsResult $object the target object @return void
entailment
private static function _convertParameters(&$params) { $res = []; foreach ($params as $param => $substitutions) { $res["$param"] = []; foreach ($substitutions as $key => $value) { $res["$param"]["$key"] = "$value"; } } return $res; }
Converts an object describing parameter mappings to associative arrays. We want an associative array but since `json_decode` produces an object whose fields correspond to the substitutions we need to do a bit of conversion. @param object $params the parameter mapping object @return array the parameter mappings
entailment
private static function _batchResponseFromFields(&$json, &$fields) { if ($fields->type == 'mt_text') { $result = new Api\MtBatchTextSmsResult(); $result->setBody($fields->body); if (isset($fields->parameters)) { $result->setParameters( Deserialize::_convertParameters($fields->parameters) ); } } else if ($fields->type == 'mt_binary') { $result = new Api\MtBatchBinarySmsResult(); $result->setUdh(hex2bin($fields->udh)); $result->setBody(base64_decode($fields->body)); } else { throw new UnexpectedResponseException( "Received unexpected batch type " . $fields->type, $json ); } // Read the common fields. Deserialize::_batchResponseHelper($json, $fields, $result); return $result; }
Helper that creates and populates a batch result object. The result is populated from the result of `json_decode`. @param string $json the JSON formatted string @param object $fields the `json_decode` containing the result @return Api\MtBatchSmsResult the parsed result @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public static function batchResponse($json) { $fields = Deserialize::_fromJson($json); return Deserialize::_batchResponseFromFields($json, $fields); }
Reads a JSON blob describing a batch result. If the `type` field has the value `mt_text` then an `MtBatchSmsTextCreate` object is returned, if the value is `mt_binary` then an `MtBatchTextSmsCreate` object is returned, otherwise an exception is thrown. @param string $json the JSON text to interpret @return Api\MtBatchSmsResult the parsed result @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public static function batchesPage($json) { $fields = Deserialize::_fromJson($json); $result = new Api\Page(); $result->setPage($fields->page); $result->setSize($fields->page_size); $result->setTotalSize($fields->count); $result->setContent( array_map( function ($s) use ($json) { return Deserialize::_batchResponseFromFields($json, $s); }, $fields->batches ) ); return $result; }
Reads a JSON blob describing a page of batches. @param string $json the JSON text @return Api\Page the parsed page @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public static function batchDryRun($json) { $fields = Deserialize::_fromJson($json); $result = new Api\MtBatchDryRunResult(); $result->setNumberOfRecipients($fields->number_of_recipients); $result->setNumberOfMessages($fields->number_of_messages); if (isset($fields->per_recipient)) { $result->setPerRecipient( array_map( function ($s) { $pr = new Api\DryRunPerRecipient(); $pr->setRecipient($s->recipient); $pr->setNumberOfParts($s->number_of_parts); $pr->setBody($s->body); $pr->setEncoding($s->encoding); return $pr; }, $fields->per_recipient ) ); } return $result; }
Reads a JSON formatted string describing a dry-run result. @param string $json the JSON text @return Api\MtBatchDryRunResult the parsed result
entailment
public static function batchDeliveryReport($json) { $fields = Deserialize::_fromJson($json); if (!isset($fields->type) || $fields->type != 'delivery_report_sms') { throw new UnexpectedResponseException( "Expected delivery report", $json ); } $result = new Api\BatchDeliveryReport(); $result->setBatchId($fields->batch_id); $result->setTotalMessageCount($fields->total_message_count); $result->setStatuses( array_map( function ($s) { $r = new Api\BatchDeliveryReportStatus(); $r->setCode($s->code); $r->setStatus($s->status); $r->setCount($s->count); if (isset($s->recipients)) { $r->setRecipients($s->recipients); } return $r; }, $fields->statuses ) ); return $result; }
Reads a JSON blob describing a batch delivery report. @param string $json the JSON text @return Api\BatchDeliveryReport the parsed batch delivery report @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public static function batchRecipientDeliveryReport($json) { $fields = Deserialize::_fromJson($json); if (!isset($fields->type) || $fields->type != 'recipient_delivery_report_sms' ) { throw new UnexpectedResponseException( "Expected recipient delivery report", $json ); } $result = new Api\BatchRecipientDeliveryReport(); $result->setBatchId($fields->batch_id); $result->setRecipient($fields->recipient); $result->setCode($fields->code); $result->setStatus($fields->status); $result->setStatusAt(Deserialize::_dateTime($json, $fields->at)); if (isset($fields->status_message)) { $result->setStatusMessage($fields->status_message); } if (isset($fields->operator)) { $result->setOperator($fields->operator); } if (isset($fields->operator_status_at)) { $result->setOperatorStatusAt( Deserialize::_dateTime( $json, $fields->operator_status_at ) ); } return $result; }
Reads a batch recipient delivery report from the given JSON text. @param string $json JSON formatted text @return Api\batchRecipientDeliveryReport a delivery report @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
private static function _autoUpdateFromFields(&$fields) { $addKeywords = [null, null]; $removeKeywords = [null, null]; if (isset($fields->add) && isset($fields->add->first_word)) { $addKeywords[0] = $fields->add->first_word; } if (isset($fields->add) && isset($fields->add->second_word)) { $addKeywords[1] = $fields->add->second_word; } if (isset($fields->remove) && isset($fields->remove->first_word)) { $removeKeywords[0] = $fields->remove->first_word; } if (isset($fields->remove) && isset($fields->remove->second_word)) { $removeKeywords[1] = $fields->remove->second_word; } return new Api\GroupAutoUpdate( $fields->to, $addKeywords, $removeKeywords ); }
Helper that creates a group auto update object from the given fields. @param object $fields the fields as generated by `json_decode` @return Api\GroupAutoUpdate the created group auto update
entailment
private static function _groupResponseFromFields(&$json, &$fields) { $result = new Api\GroupResult(); $result->setChildGroups($fields->child_groups); $result->setGroupId($fields->id); $result->setSize($fields->size); $result->setCreatedAt( Deserialize::_dateTime($json, $fields->created_at) ); $result->setModifiedAt( Deserialize::_dateTime($json, $fields->modified_at) ); if (isset($fields->name)) { $result->setName($fields->name); } if (isset($fields->auto_update)) { $result->setAutoUpdate( Deserialize::_autoUpdateFromFields($fields->auto_update) ); } return $result; }
Helper that creates a group response object from the given fields. @param string $json original JSON message @param object $fields the fields as generated by `json_decode` @return Api\GroupResult the created group response
entailment
public static function groupResponse($json) { $fields = Deserialize::_fromJson($json); return Deserialize::_groupResponseFromFields($json, $fields); }
Parses a group response from the given JSON text. @param string $json JSON formatted text @return Api\GroupResult the created group response
entailment
public static function groupsPage($json) { $fields = Deserialize::_fromJson($json); $result = new Api\Page(); $result->setPage($fields->page); $result->setSize($fields->page_size); $result->setTotalSize($fields->count); $result->setContent( array_map( function ($s) use ($json) { return Deserialize::_groupResponseFromFields($json, $s); }, $fields->groups ) ); return $result; }
Parses a page of groups from the given JSON text. @param string $json JSON formatted text @return Api\Page the created page of groups
entailment
public static function error($json) { $fields = Deserialize::_fromJson($json); $result = new Api\Error(); $result->setCode($fields->code); $result->setText($fields->text); return $result; }
Reads a JSON blob containing an error response. @param string $json a JSON formatted text @return Api\Error the decoded error
entailment
private static function _moSmsFromFields(&$json, &$fields) { if ($fields->type === 'mo_text') { $result = new Api\MoTextSms(); $result->setBody($fields->body); if (isset($fields->keyword)) { $result->setKeyword($fields->keyword); } } else if ($fields->type === 'mo_binary') { $result = new Api\MoBinarySms(); $result->setBody(base64_decode($fields->body)); $result->setUdh(hex2bin($fields->udh)); } else { throw new UnexpectedResponseException( "Received unexpected inbound type " . $fields->type, $json ); } $result->setMessageId($fields->id); $result->setSender($fields->from); $result->setRecipient($fields->to); if (isset($fields->operator)) { $result->setOperator($fields->operator); } if (isset($fields->sent_at)) { $result->setSentAt( Deserialize::_dateTime($json, $fields->sent_at) ); } if (isset($fields->received_at)) { $result->setReceivedAt( Deserialize::_dateTime($json, $fields->received_at) ); } return $result; }
Helper that reads an MO from the given fields. @param string $json original JSON formatted text @param object $fields the result of `json_decode` @return Api\MoSms the parsed inbound message @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public static function moSms($json) { $fields = Deserialize::_fromJson($json); return Deserialize::_moSmsFromFields($json, $fields); }
Reads a JSON blob containing an MO message. @param string $json a JSON formatted text @return Api\MoSms the decoded error @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public static function inboundsPage($json) { $fields = Deserialize::_fromJson($json); $result = new Api\Page(); $result->setPage($fields->page); $result->setSize($fields->page_size); $result->setTotalSize($fields->count); $result->setContent( array_map( function ($s) { return Deserialize::_moSmsFromFields($json, $s); }, $fields->inbounds ) ); return $result; }
Reads a JSON blob describing a page of MO messages. @param string $json the JSON text @return Api\Page the parsed page @throws UnexpectedResponseException if the JSON contained an unexpected message type
entailment
public function setTranslatable(TranslatableInterface $translatable = null) { if ($this->translatable == $translatable) { return $this; } $old = $this->translatable; $this->translatable = $translatable; if ($old !== null) { $old->removeTranslation($this); } if ($translatable !== null) { $translatable->addTranslation($this); } return $this; }
Set the translatable object @param TranslatableInterface $translatable @return self
entailment
public function validate() { if (!$this->translatable) { throw new MappingException(sprintf('No translatable specified for %s', $this->name)); } if (!$this->targetEntity) { throw new MappingException(sprintf('No translatable targetEntity specified for %s', $this->name)); } if (!$this->locale) { throw new MappingException(sprintf('No locale specified for %s', $this->name)); } }
Validate the metadata @return void
entailment
public function merge(MergeableInterface $object) { if (!$object instanceof self) { throw new \InvalidArgumentException(sprintf('$object must be an instance of %s.', __CLASS__)); } parent::merge($object); if ($object->targetEntity) { $this->targetEntity = $object->targetEntity; } if ($object->translatable) { $this->translatable = $object->translatable; } if ($object->locale) { $this->locale = $object->locale; } }
{@inheritdoc}
entailment
public function serialize() { return serialize(array( $this->targetEntity, $this->translatable ? $this->translatable->name : null, $this->locale ? $this->locale->name : null, parent::serialize(), )); }
{@inheritdoc}
entailment
public function unserialize($str) { list ( $this->targetEntity, $translatable, $locale, $parent ) = unserialize($str); parent::unserialize($parent); if ($translatable) { $this->translatable = $this->propertyMetadata[$translatable]; } if ($locale) { $this->locale = $this->propertyMetadata[$locale]; } }
{@inheritdoc}
entailment
public function withStatus($code, $reasonPhrase = '') { $this->statusCode = (int)$code; if ($reasonPhrase == '') { $this->reasonPhrase = Status::getReasonPhrase($this->statusCode); } else { $this->reasonPhrase = $reasonPhrase; } return $this; }
Set status code @param int $code @param string $reasonPhrase @return Response
entailment
public function seek($offset, $whence = SEEK_SET) { if ($whence !== SEEK_SET || $offset < 0) { throw new RuntimeException(sprintf( 'Cannot seek to offset % with whence %s', $offset, $whence )); } $offset += $this->offset; if ($this->limit !== -1) { if ($offset > $this->offset + $this->limit) { $offset = $this->offset + $this->limit; } } $this->stream->seek($offset); }
Allow for a bounded seek on the read limited stream {@inheritdoc}
entailment
public function scopeOnlyUnkeptOlderThanHours(Builder $builder, $hours) { return $builder ->withoutGlobalScope(KeptFlagScope::class) ->where('is_kept', 0) ->where(static::getCreatedAtColumn(), '<=', Date::now()->subHours($hours)->toDateTimeString()); }
Get unkept models that are older than the given number of hours. @param \Illuminate\Database\Eloquent\Builder $builder @param int $hours @return \Illuminate\Database\Eloquent\Builder
entailment
protected function resolveOptions($config) { if (! $this->schema) { return $config; } try { $resolver = new OptionsResolver(); if ($this->configureOptions($resolver)) { $config = $resolver->resolve($config); } } catch (Exception $exception) { throw new FailedToResolveConfigException( sprintf( _('Error while resolving config options: %1$s'), $exception->getMessage() ) ); } return $config; }
Process the passed-in defaults and merge them with the new values, while checking that all required options are set. @since 0.1.0 @param array $config Configuration settings to resolve. @return array Resolved configuration settings. @throws FailedToResolveConfigException If there are errors while resolving the options.
entailment
protected function configureOptions(OptionsResolver $resolver) { $defined = $this->schema->getDefinedOptions(); $defaults = $this->schema->getDefaultOptions(); $required = $this->schema->getRequiredOptions(); if (! $defined && ! $defaults && ! $required) { return false; } try { if ($defined) { $resolver->setDefined($defined); } if ($defaults) { $resolver->setDefaults($defaults); } if ($required) { $resolver->setRequired($required); } } catch (Exception $exception) { throw new FailedToResolveConfigException( sprintf( _('Error while processing config options: %1$s'), $exception->getMessage() ) ); } return true; }
Configure the possible and required options for the Config. This should return a bool to let the resolve_options() know whether the actual resolving needs to be done or not. @since 0.1.0 @param OptionsResolver $resolver Reference to the OptionsResolver instance. @return bool Whether to do the resolving. @throws FailedToResolveConfigException If there are errors while processing.
entailment
function current() { if (!isset($this->_curPage) || $this->_curPage->getPage() != $this->_position ) { $this->_curPage = $this->_pages->get($this->_position); } return $this->_curPage; }
Returns the current page. @return Page the current page
entailment
public function registerAssets() { $view = $this->getView(); AutoCompleteAsset::register($view); $id = $this->options['id']; if (!isset($this->clientOptions['lookup'])){ $this->clientOptions['lookup'] = array_values($this->data); } $options = $this->clientOptions !== false && !empty($this->clientOptions) ? Json::encode($this->clientOptions) : 'null'; $js[] = "jQuery('#$id').autocomplete($options);"; $view->registerJs(implode("\n", $js)); }
Register assets
entailment
protected function processConfig(ConfigInterface $config) { if (func_num_args() > 1) { try { $keys = func_get_args(); array_shift($keys); $config = $config->getSubConfig($keys); } catch (Exception $exception) { throw new FailedToProcessConfigException( sprintf( _('Could not process the config with the arguments "%1$s".'), print_r(func_get_args(), true) ) ); } } $this->config = $config; }
Process the passed-in configuration file. @since 0.1.2 @param ConfigInterface $config The Config to process. @param string ... List of keys. @throws FailedToProcessConfigException If the arguments could not be parsed into a Config.
entailment
protected function getConfigCallable($key, array $args = []) { $value = $this->config->getKey($key); if (is_callable($value)) { $value = $value(...$args); } return $value; }
Get the callable Config value for a specific key. If the fetched value is indeed a callable, it will be executed with the provided arguments, and the resultant value will be returned instead. @since 0.4.8 @param string|array $key Key or array of nested keys. @param array $args Optional. Array of arguments to pass to the callable. @return mixed Resultant value of the key's callable.
entailment
protected function fetchDefaultConfig() { $configFile = method_exists($this, 'getDefaultConfigFile') ? $this->getDefaultConfigFile() : __DIR__ . '/../config/defaults.php'; return $this->fetchConfig($configFile); }
Get a default configuration in case none was injected into the constructor. The name and path of the configuration needs to be set as a const called DEFAULT_CONFIG within the class containing the trait. The path needs to be relative to the location of the containing class file. @since 0.4.2 @return ConfigInterface Configuration settings to use.
entailment
protected function fetchConfig($configFile) { if (is_string($configFile) && ! is_readable($configFile)) { $configFile = []; } return ConfigFactory::create($configFile); }
Get a configuration from a specified $file. If file is not accessible or readable, returns an empty Config. @since 0.4.2 @return ConfigInterface Configuration settings to use.
entailment
public function loadConfiguration(string $recipe): array { $pathToRecipe = $this->getPathToRecipe($recipe); $configuration = (array)Yaml::parse((string)file_get_contents($pathToRecipe)); $this->configurationValidator->validate($configuration); return $configuration; }
@param string $recipe @return array
entailment
protected function getPathToRecipe(string $recipe): string { $recipePaths = $this->buildRecipePaths($recipe); foreach ($recipePaths as $recipePath) { if (file_exists($recipePath)) { return $recipePath; } } throw new ConfigurationFileNotFoundException( sprintf( 'Could not resolve path for your recipe. Check %s.', implode(', ', $recipePaths) ) ); }
@param string $recipe @throws \Spryker\Install\Configuration\Loader\Exception\ConfigurationFileNotFoundException @return string
entailment
protected function buildRecipePaths(string $recipe): array { $recipePaths = [ sprintf('%s/config/install/%s.yml', SPRYKER_ROOT, $recipe), sprintf('%s/config/install/%s', SPRYKER_ROOT, $recipe), sprintf('%s/%s', SPRYKER_ROOT, $recipe), $recipe, ]; return $recipePaths; }
@param string $recipe @return array
entailment
public function filter(array $items): array { $filtered = []; foreach ($items as $sectionName => $sectionDefinition) { $isExcluded = true; if ($this->output->confirm(sprintf('Should section <fg=yellow>%s</> be executed?', $sectionName), true) === true) { $isExcluded = false; } $sectionDefinition[static::EXCLUDED] = $isExcluded; $filtered[$sectionName] = $sectionDefinition; } return $filtered; }
@param array $items @return array
entailment
public function apply(Builder $builder, Model $model): void { if (method_exists($model, 'shouldApplyApprovedFlagScope') && $model->shouldApplyApprovedFlagScope()) { $builder->where('is_approved', 1); } }
Apply the scope to a given Eloquent query builder. @param \Illuminate\Database\Eloquent\Builder $builder @param \Illuminate\Database\Eloquent\Model $model @return void
entailment
protected function addApprove(Builder $builder): void { $builder->macro('approve', function (Builder $builder) { $builder->withNotApproved(); return $builder->update(['is_approved' => 1]); }); }
Add the `approve` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addUndoApprove(Builder $builder): void { $builder->macro('undoApprove', function (Builder $builder) { return $builder->update(['is_approved' => 0]); }); }
Add the `undoApprove` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addWithNotApproved(Builder $builder): void { $builder->macro('withNotApproved', function (Builder $builder) { return $builder->withoutGlobalScope($this); }); }
Add the `withNotApproved` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addWithoutNotApproved(Builder $builder): void { $builder->macro('withoutNotApproved', function (Builder $builder) { return $builder->withoutGlobalScope($this)->where('is_approved', 1); }); }
Add the `withoutNotApproved` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addOnlyNotApproved(Builder $builder): void { $builder->macro('onlyNotApproved', function (Builder $builder) { return $builder->withoutGlobalScope($this)->where('is_approved', 0); }); }
Add the `onlyNotApproved` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
public function init() { parent::init(); self::$plugin = $this; $this->setComponents([ 'collision' => \marionnewlevant\snitch\services\Collision::class, ]); if (Craft::$app->getRequest()->getIsCpRequest() && !Craft::$app->getUser()->getIsGuest() && !Craft::$app->getRequest()->getIsAjax()) { // Register our asset bundle Craft::$app->getView()->registerAssetBundle(SnitchAsset::class); // on save, remove any collision for this element. Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) { $elementId = $event->element->id; $this->collision->remove($elementId); }); } }
Set our $plugin static property to this class so that it can be accessed via Snitch::$plugin
entailment
protected function addApprove(Builder $builder): void { $builder->macro('approve', function (Builder $builder) { $builder->withNotApproved(); return $builder->update(['approved_at' => Date::now()]); }); }
Add the `approve` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addWithoutNotApproved(Builder $builder): void { $builder->macro('withoutNotApproved', function (Builder $builder) { return $builder->withoutGlobalScope($this)->whereNotNull('approved_at'); }); }
Add the `withoutNotApproved` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addOnlyNotApproved(Builder $builder): void { $builder->macro('onlyNotApproved', function (Builder $builder) { return $builder->withoutGlobalScope($this)->whereNull('approved_at'); }); }
Add the `onlyNotApproved` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addClose(Builder $builder): void { $builder->macro('close', function (Builder $builder) { return $builder->update(['closed_at' => Date::now()]); }); }
Add the `close` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addWithoutClosed(Builder $builder): void { $builder->macro('withoutClosed', function (Builder $builder) { return $builder->withoutGlobalScope($this)->whereNull('closed_at'); }); }
Add the `withoutClosed` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
protected function addOnlyClosed(Builder $builder): void { $builder->macro('onlyClosed', function (Builder $builder) { return $builder->withoutGlobalScope($this)->whereNotNull('closed_at'); }); }
Add the `onlyClosed` extension to the builder. @param \Illuminate\Database\Eloquent\Builder $builder @return void
entailment
public function sendRequest($method, $endpoint, $endpointType = 'api', array $params = [], $accessToken = null) { //Access Token $accessToken = $this->getAccessToken() ? $this->getAccessToken() : $accessToken; //Make a BoxRequest object $request = new BoxRequest($method, $endpoint, $accessToken, $endpointType, $params); //Send Request through the BoxClient //Fetch and return the Response return $this->getClient()->sendRequest($request); }
Make Request to the API @param string $method HTTP Request Method @param string $endpoint API Endpoint to send Request to @param string $endpointType Endpoint type ['api'|'content'] @param array $params Request Query Params @param string $accessToken Access Token to send with the Request @return BoxResponse @throws Exceptions\BoxClientException
entailment
public function deleteToAPI($endpoint, array $params = [], $accessToken = null) { return $this->sendRequest("DELETE", $endpoint, 'api', $params, $accessToken); }
Make a HTTP DELETE Request to the API endpoint type @param string $endpoint API Endpoint to send Request to @param array $params Request Query Params @param string $accessToken Access Token to send with the Request @return BoxResponse
entailment
public function postToContent($endpoint, array $params = [], $accessToken = null) { return $this->sendRequest("POST", $endpoint, 'upload', $params, $accessToken); }
Make a HTTP POST Request to the Content endpoint type @param string $endpoint Content Endpoint to send Request to @param array $params Request Query Params @param string $accessToken Access Token to send with the Request @return BoxResponse
entailment
public function deleteToContent($endpoint, array $params = [], $accessToken = null) { return $this->sendRequest("DELETE", $endpoint, 'upload', $params, $accessToken); }
Make a HTTP DELETE Request to the Content endpoint type @param string $endpoint Content Endpoint to send Request to @param array $params Request Query Params @param string $accessToken Access Token to send with the Request @return BoxResponse
entailment
public function makeBoxFile($boxFile, $maxLength = -1, $offset = -1) { //Uploading file by file path if (!$boxFile instanceof BoxFile) { //File is valid if (is_file($boxFile)) { //Create a BoxFile Object $boxFile = new BoxFile($boxFile, $maxLength, $offset); } else { //File invalid/doesn't exist throw new Exceptions\BoxClientException("File '{$boxFile}' is invalid."); } } $boxFile->setOffset($offset); $boxFile->setMaxLength($maxLength); //Return the BoxFile Object return $boxFile; }
Make BoxFile Object @param string|BoxFile $boxFile BoxFile object or Path to file @param int $maxLength Max Bytes to read from the file @param int $offset Seek to specified offset before reading @return \Box\BoxFile
entailment
public function getMetadata($path, array $params = []) { //Root folder is unsupported if ($path === '/') { throw new Exceptions\BoxClientException("Metadata for the root folder is unsupported."); } //Set the path $params['path'] = $path; //Get File Metadata $response = $this->postToAPI('/files/get_metadata', $params); //Make and Return the Model return $this->makeModelFromResponse($response); }
Get the Metadata for a file or folder @param string $path Path of the file or folder @param array $params Additional Params @link https://www.box.com/developers/documentation/http/documentation#files-get_metadata @return \Ziggeo\BoxContent\Content\BoxFileMetadata|\Ziggeo\BoxContent\Content\FolderMetadata
entailment
public function listRevisions($path, array $params = []) { //Set the Path $params['path'] = $path; //Fetch the Revisions $response = $this->postToAPI('/files/list_revisions', $params); //The file metadata of the entries, returned by this //endpoint doesn't include a '.tag' attribute, which //is used by the ModelFactory to resolve the correct //model. But since we know that revisions returned //are file metadata objects, we can explicitly cast //them as \Ziggeo\BoxContent\Content\BoxFileMetadata manually. $body = $response->getDecodedBody(); $entries = isset($body['entries']) ? $body['entries'] : []; $processedEntries = []; foreach ($entries as $entry) { $processedEntries[] = new BoxFileMetadata($entry); } return new ModelCollection($processedEntries); }
Get Revisions of a File @param string $path Path to the file @param array $params Additional Params @link https://www.box.com/developers/documentation/http/documentation#files-list_revisions @return \Ziggeo\BoxContent\Content\ModelCollection
entailment
public function createFolder($name, $autorename = false) { //Path cannot be null if (is_null($name)) { throw new Exceptions\BoxClientException("Name cannot be null."); } //Create Folder $response = $this->postToAPI('/folders', ['name' => $name, 'autorename' => $autorename, 'parent' => array("id" => 0)]); //Fetch the Metadata if ($response->getHttpStatusCode() === 409) { $body = $response->getDecodedBody(); $body = $body["context_info"]["conflicts"][0]; } else{ $body = $response->getDecodedBody(); } //Make and Return the Model return new FolderMetadata($body); }
Create a folder at the given path @param string $name Path to create @param boolean $autorename Auto Rename File @link https://www.box.com/developers/documentation/http/documentation#files-create_folder @return \Ziggeo\BoxContent\Content\FolderMetadata
entailment
public function deleteFile($fileId) { //Path cannot be null if (is_null($fileId)) { throw new Exceptions\BoxClientException("Id cannot be null."); } //Delete $response = $this->deleteToAPI('/files/' . $fileId); return $response; }
Delete a file or folder at the given path @param string $path Path to file/folder to delete @link https://www.box.com/developers/documentation/http/documentation#files-delete @return \Ziggeo\BoxContent\Content\DeletedMetadata|BoxFileMetadata|FolderMetadata
entailment
public function deleteFolder($folderId) { //Path cannot be null if (is_null($folderId)) { throw new Exceptions\BoxClientException("Id cannot be null."); } //Delete $response = $this->deleteToAPI('/folders/' . $folderId); return $response; }
Delete a file or folder at the given path @param string $path Path to file/folder to delete @link https://www.box.com/developers/documentation/http/documentation#files-delete @return \Ziggeo\BoxContent\Content\DeletedMetadata|BoxFileMetadata|FolderMetadata
entailment
public function copy($fromPath, $toPath) { //From and To paths cannot be null if (is_null($fromPath) || is_null($toPath)) { throw new Exceptions\BoxClientException("From and To paths cannot be null."); } //Response $response = $this->postToAPI('/files/copy', ['from_path' => $fromPath, 'to_path' => $toPath]); //Make and Return the Model return $this->makeModelFromResponse($response); }
Copy a file or folder to a different location @param string $fromPath Path to be copied @param string $toPath Path to be copied to @link https://www.box.com/developers/documentation/http/documentation#files-copy @return \Ziggeo\BoxContent\Content\BoxFileMetadata|BoxFileMetadata|DeletedMetadata
entailment
public function restore($path, $rev) { //Path and Revision cannot be null if (is_null($path) || is_null($rev)) { throw new Exceptions\BoxClientException("Path and Revision cannot be null."); } //Response $response = $this->postToAPI('/files/restore', ['path' => $path, 'rev' => $rev]); //Fetch the Metadata $body = $response->getDecodedBody(); //Make and Return the Model return new BoxFileMetadata($body); }
Restore a file to the specific version @param string $path Path to the file to restore @param string $rev Revision to store for the file @link https://www.box.com/developers/documentation/http/documentation#files-restore @return \Ziggeo\BoxContent\Content\DeletedMetadata|BoxFileMetadata|FolderMetadata
entailment
public function getCopyReference($path) { //Path cannot be null if (is_null($path)) { throw new Exceptions\BoxClientException("Path cannot be null."); } //Get Copy Reference $response = $this->postToAPI('/files/copy_reference/get', ['path' => $path]); $body = $response->getDecodedBody(); //Make and Return the Model return new CopyReference($body); }
Get Copy Reference @param string $path Path to the file or folder to get a copy reference to @link https://www.box.com/developers/documentation/http/documentation#files-copy_reference-get @return \Ziggeo\BoxContent\Content\CopyReference
entailment
public function saveCopyReference($path, $copyReference) { //Path and Copy Reference cannot be null if (is_null($path) || is_null($copyReference)) { throw new Exceptions\BoxClientException("Path and Copy Reference cannot be null."); } //Save Copy Reference $response = $this->postToAPI('/files/copy_reference/save', ['path' => $path, 'copy_reference' => $copyReference]); $body = $response->getDecodedBody(); //Response doesn't have Metadata if (!isset($body['metadata']) || !is_array($body['metadata'])) { throw new Exceptions\BoxClientException("Invalid Response."); } //Make and return the Model return ModelFactory::make($body['metadata']); }
Save Copy Reference @param string $path Path to the file or folder to get a copy reference to @param string $copyReference Copy reference returned by getCopyReference @link https://www.box.com/developers/documentation/http/documentation#files-copy_reference-save @return \Ziggeo\BoxContent\Content\BoxFileMetadata|\Ziggeo\BoxContent\Content\FolderMetadata
entailment
public function getTemporaryLink($path) { //Path cannot be null if (is_null($path)) { throw new Exceptions\BoxClientException("Path cannot be null."); } //Get Temporary Link $response = $this->postToAPI('/files/get_temporary_link', ['path' => $path]); //Make and Return the Model return $this->makeModelFromResponse($response); }
Get a temporary link to stream contents of a file @param string $path Path to the file you want a temporary link to https://www.box.com/developers/documentation/http/documentation#files-get_temporary_link @return \Ziggeo\BoxContent\Content\TemporaryLink
entailment
public function saveUrl($path, $url) { //Path and URL cannot be null if (is_null($path) || is_null($url)) { throw new Exceptions\BoxClientException("Path and URL cannot be null."); } //Save URL $response = $this->postToAPI('/files/save_url', ['path' => $path, 'url' => $url]); $body = $response->getDecodedBody(); if (!isset($body['async_job_id'])) { throw new Exceptions\BoxClientException("Could not retrieve Async Job ID."); } //Return the Asunc Job ID return $body['async_job_id']; }
Save a specified URL into a file in user's Box @param string $path Path where the URL will be saved @param string $url URL to be saved @link https://www.box.com/developers/documentation/http/documentation#files-save_url @return string Async Job ID
entailment
public function checkJobStatus($asyncJobId) { //Async Job ID cannot be null if (is_null($asyncJobId)) { throw new Exceptions\BoxClientException("Async Job ID cannot be null."); } //Get Job Status $response = $this->postToAPI('/files/save_url/check_job_status', ['async_job_id' => $asyncJobId]); $body = $response->getDecodedBody(); //Status $status = isset($body['.tag']) ? $body['.tag'] : ''; //If status is complete if ($status === 'complete') { return new BoxFileMetadata($body); } //Return the status return $status; }
Save a specified URL into a file in user's Box @param string $path Path where the URL will be saved @param string $url URL to be saved @link https://www.box.com/developers/documentation/http/documentation#files-save_url-check_job_status @return string|BoxFileMetadata Status (failed|in_progress) or BoxFileMetadata (if complete)
entailment
public function upload($boxFile, $attributes, array $params = []) { //Make BoxMain File $boxFile = $this->makeBoxFile($boxFile); //Simple file upload return $this->simpleUpload($boxFile, $attributes, $params); }
Upload a File to Box @param string|BoxFile $boxFile BoxFile object or Path to file @param string $folder Path to upload the file to @param array $params Additional Params @link https://www.box.com/developers/documentation/http/documentation#files-upload @return \Ziggeo\BoxContent\Content\BoxFileMetadata
entailment
public function simpleUpload($boxFile, $attributes, array $params = []) { //Make BoxMain File $boxFile = $this->makeBoxFile($boxFile); //Set the attributes and file $params['attributes'] = $attributes; $params['file'] = $boxFile; //Upload File $file = $this->postToContent('/files/content', $params); $body = $file->getDecodedBody(); if ($body["type"] == "error") throw new Exceptions\BoxClientException($body["message"] . " - ID: " . $body["context_info"]["conflicts"]["id"], $body["status"]); //Make and Return the Model $fileData = array(); if (!empty($body["total_count"]) && $body["total_count"]) $fileData = $body["entries"][0]; return new BoxFileMetadata($fileData); }
Upload a File to BoxMain in a single request @param string|BoxFile $boxFile BoxFile object or Path to file @param array $path Path to upload the file to @param array $params Additional Params @link https://www.box.com/developers/documentation/http/documentation#files-upload @return \Ziggeo\BoxContent\Content\BoxFileMetadata
entailment
public function download($path) { //Path cannot be null if (is_null($path)) { throw new Exceptions\BoxClientException("Path cannot be null."); } //Download File $response = $this->postToContent('/files/download', ['path' => $path]); //Get file metadata from response headers $metadata = $this->getMetadataFromResponseHeaders($response); //File Contents $contents = $response->getBody(); //Make and return a File model return new File($metadata, $contents); }
Download a File @param string $path Path to the file you want to download @link https://www.box.com/developers/documentation/http/documentation#files-download @return \Ziggeo\BoxContent\Content\File
entailment
public function handle(GetResponseEvent $event) { if (null !== $this->logger) { $this->logger->info('Checking for guard authentication credentials.', array('firewall_key' => $this->providerKey, 'authenticators' => count($this->guardAuthenticators))); } foreach ($this->guardAuthenticators as $key => $guardAuthenticator) { // get a key that's unique to *this* guard authenticator // this MUST be the same as GuardAuthenticationProvider $uniqueGuardKey = $this->providerKey.'_'.$key; $this->executeGuardAuthenticator($uniqueGuardKey, $guardAuthenticator, $event); } }
Iterates over each authenticator to see if each wants to authenticate the request. @param GetResponseEvent $event
entailment
private function triggerRememberMe(GuardAuthenticatorInterface $guardAuthenticator, Request $request, TokenInterface $token, Response $response = null) { if (!$guardAuthenticator->supportsRememberMe()) { return; } if (null === $this->rememberMeServices) { if (null !== $this->logger) { $this->logger->info('Remember me skipped: it is not configured for the firewall.', array('authenticator' => get_class($guardAuthenticator))); } return; } if (!$response instanceof Response) { throw new \LogicException(sprintf( '%s::onAuthenticationSuccess *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.', get_class($guardAuthenticator) )); } $this->rememberMeServices->loginSuccess($request, $response, $token); }
Checks to see if remember me is supported in the authenticator and on the firewall. If it is, the RememberMeServicesInterface is notified. @param GuardAuthenticatorInterface $guardAuthenticator @param Request $request @param TokenInterface $token @param Response $response
entailment
public function getUsersList() { $response=CodeBank_ClientAPI::responseBase(); $members=Permission::get_members_by_permission(array('ADMIN', 'CODE_BANK_ACCESS')); foreach($members as $member) { $response['data'][]=array( 'id'=>$member->ID, 'username'=>$member->Email, 'lastLogin'=>$member->LastVisited ); } return $response; }
Gets a list of users in the database @return {array} Returns a standard response array
entailment