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 ar...
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)) { ...
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 unexpi...
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 hav...
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['v...
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->hostonl...
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()) { ...
@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->getNam...
@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...
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 ...
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( _('...
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 s...
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...
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 ($fi...
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]...
@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($f...
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( ...
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 J...
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\MtBat...
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( ...
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_rec...
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 ); } ...
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...
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($f...
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($...
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( ...
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); } } e...
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( ...
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->removeTransl...
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->nam...
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 = $o...
{@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[$trans...
{@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->offse...
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 (...
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 optio...
entailment
protected function configureOptions(OptionsResolver $resolver) { $defined = $this->schema->getDefinedOptions(); $defaults = $this->schema->getDefaultOptions(); $required = $this->schema->getRequiredOptions(); if (! $defined && ! $defaults && ! $required) { return false;...
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 Fai...
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->clie...
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...
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...
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 C...
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 ConfigurationFileNotFoundE...
@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, ]; ...
@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) { $isE...
@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->g...
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, ...
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...
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, $maxLen...
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 Metad...
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...
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' => $a...
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', ['fr...
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' => $...
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]); $bo...
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 $respo...
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\BoxFileM...
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]); //...
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, 'ur...
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', ['...
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...
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\BoxCont...
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-...
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 @r...
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 f...
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->guardAuthe...
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 !=...
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 $res...
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,...
Gets a list of users in the database @return {array} Returns a standard response array
entailment