sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function getQueue() { if (isset($this->meta)) return $this->meta; return $this->meta = $this->container['queue']->getIron()->getQueue($this->argument('queue')); }
Get the queue information from Iron.io. @return object
entailment
public function addHeader($name, $value, $override = true) { return $this->addHeaderRequest($name, $value, $override); }
Adiciona um campo de cabeçalho para ser enviado com a requisição. @param string $name Nome do campo de cabeçalho. @param string $value Valor do campo de cabeçalho. @param bool $override Indica se o campo deverá ser sobrescrito caso já tenha sido definido. @return bool @throws \InvalidArgumentException Se o nome ou o valor do campo não forem valores scalar. @see \Moip\Http\HTTPRequest::addRequestHeader()
entailment
private function getHeader($key) { if (isset($this->requestHeader[$key])) { $header = $this->requestHeader[$key]['value']; unset($this->requestHeader[$key]); } else { if ($key === 'host') { $header = $this->getHost(); } elseif ($key === 'accept') { $header = '*/*'; } elseif ($key === 'user-agent') { $header = self::$userAgent; } } return $header; }
Verifica se existe um header e retorna o seu valor. @param string $key @return string
entailment
public function execute($path = '/', $method = HTTPRequest::GET) { $request = $this->newRequest(); if ($request instanceof HTTPRequest) { $request->addRequestHeader('Host', $this->getHeader('host')); $request->addRequestHeader('Accept', $this->getHeader('accept')); $request->addRequestHeader('User-Agent', $this->getHeader('user-agent')); if ($this->httpAuthenticator != null) { $request->authenticate($this->httpAuthenticator); } foreach ($this->requestHeader as $header) { $request->addRequestHeader($header['name'], $header['value']); } $cookieManager = $this->getCookieManager(); if ($cookieManager != null) { $cookies = $cookieManager->getCookie($this->getHostName(), $this->isSecure(), $path); if (isset($this->requestHeader['cookie'])) { $buffer = $this->requestHeader['cookie']['value'].'; '. $cookies; } else { $buffer = $cookies; } $request->addRequestHeader('Cookie', $buffer); } foreach ($this->requestParameter as $name => $value) { $request->setParameter($name, $value); } $request->setRequestBody($this->requestBody); if ($path == null || !is_string($path) || empty($path)) { $path = '/'; } elseif (substr($path, 0, 1) != '/') { $path = '/'.$path; } if ($this->timeout != null) { $request->setTimeout($this->timeout); } if ($this->connectionTimeout != null) { $request->setConnectionTimeout($this->connectionTimeout); } $request->open($this); $request->execute($path, $method); return $request->getResponse(); } else { throw new BadMethodCallException('Invalid request object.'); } }
Executa a requisição a requisição HTTP em um caminho utilizando um método específico. @param string $path Caminho da requisição. @param string $method Método da requisição. @return string Resposta HTTP. @throws \BadMethodCallException Se não houver uma conexão inicializada ou se o objeto de requisição não for válido.
entailment
public function getHost() { if ($this->initialized) { $hostname = $this->getHostName(); if (($this->secure && $this->port != self::HTTPS_PORT) || (!$this->secure && $this->port != self::HTTP_PORT)) { $hostname .= ':'.$this->port; } return $hostname; } throw new BadMethodCallException('Connection not initialized'); }
Recupera o host da conexão. @return string @throws \BadMethodCallException Se a conexão não tiver sido inicializada.
entailment
public function initialize($hostname, $secure = false, $port = self::HTTP_PORT, $connectionTimeout = 0, $timeout = 0) { if ($this->initialized) { $this->close(); } $this->initialized = true; $this->hostname = $hostname; $this->secure = $secure === true; if (func_num_args() == 2) { $this->port = $this->secure ? self::HTTPS_PORT : self::HTTP_PORT; } else { $this->port = (int) $port; } $this->connectionTimeout = (int) $connectionTimeout; $this->timeout = (int) $timeout; }
Inicializa a conexão HTTP. @param string $hostname Servidor que receberá a requisição. @param bool $secure Indica se a conexão será segura (https). @param int $port Porta da requisição. @param int $connectionTimeout Timeout de conexão em segundos. @param int $timeout Timeout de espera em segundos.
entailment
public function setParam($name, $value = null) { if (is_scalar($name) && (is_scalar($value) || is_null($value))) { $this->requestParameter[$name] = $value; } else { throw new InvalidArgumentException('Name and value MUST be scalar'); } }
Define um parâmetro que será enviado com a requisição, um parâmetro é um par nome-valor que será enviado como uma query string. @param string $name Nome do parâmetro. @param string $value Valor do parâmetro. @throws \InvalidArgumentException Se o nome ou o valor do campo não forem valores scalar.
entailment
protected function hasTooManyLoginAttempts(Request $request) { $rateLimiter = App::make('Nova\Cache\RateLimiter'); return $rateLimiter->tooManyAttempts( $this->getThrottleKey($request), $this->maxLoginAttempts(), $this->lockoutTime() / 60 ); }
Determine if the user has too many failed login attempts. @param \Nova\Http\Request $request @return bool
entailment
protected function incrementLoginAttempts(Request $request) { $rateLimiter = App::make('Nova\Cache\RateLimiter'); $rateLimiter->hit($this->getThrottleKey($request)); }
Increment the login attempts for the user. @param \Nova\Http\Request $request @return int
entailment
protected function retriesLeft(Request $request) { $rateLimiter = App::make('Nova\Cache\RateLimiter'); $attempts = $rateLimiter->attempts($this->getThrottleKey($request)); return $this->maxLoginAttempts() - $attempts + 1; }
Determine how many retries are left for the user. @param \Nova\Http\Request $request @return int
entailment
protected function sendLockoutResponse(Request $request) { $rateLimiter = App::make('Nova\Cache\RateLimiter'); $seconds = $rateLimiter->availableIn($this->getThrottleKey($request)); return Redirect::back() ->withInput($request->only($this->loginUsername(), 'remember')) ->withErrors(array( $this->loginUsername() => $this->getLockoutErrorMessage($seconds), )); }
Redirect the user after determining they are locked out. @param \Nova\Http\Request $request @return \Nova\Http\RedirectResponse
entailment
protected function clearLoginAttempts(Request $request) { $rateLimiter = App::make('Nova\Cache\RateLimiter'); $rateLimiter->clear($this->getThrottleKey($request)); }
Clear the login locks for the given user credentials. @param \Nova\Http\Request $request @return void
entailment
protected function getThrottleKey(Request $request) { return mb_strtolower($request->input($this->loginUsername())) .'|' .$request->ip(); }
Get the throttle key for the given request. @param \Nova\Http\Request $request @return string
entailment
public function connect(array $config) { $queue = new RedisQueue( $this->redis, $config['queue'], array_get($config, 'connection', $this->connection) ); $queue->setExpire(array_get($config, 'expire', 60)); return $queue; }
Establish a queue connection. @param array $config @return \Nova\Queue\Contracts\QueueInterface
entailment
protected static function boot() { $class = get_called_class(); static::$mutatorCache[$class] = array(); foreach (get_class_methods($class) as $method) { if (preg_match('/^get(.+)Attribute$/', $method, $matches)) { if (static::$snakeAttributes) $matches[1] = Str::snake($matches[1]); static::$mutatorCache[$class][] = lcfirst($matches[1]); } } static::bootTraits(); }
The "booting" method of the model. @return void
entailment
public static function getGlobalScope($scope) { return array_first(static::$globalScopes[get_called_class()], function($key, $value) use ($scope) { return $scope instanceof $value; }); }
Get a global scope registered with the model. @param \Nova\Database\ORM\ScopeInterface $scope @return \Nova\Database\ORM\ScopeInterface|null
entailment
protected function fillableFromArray(array $attributes) { if (count($this->fillable) > 0 && ! static::$unguarded) { return array_intersect_key($attributes, array_flip($this->fillable)); } return $attributes; }
Get the fillable attributes of a given array. @param array $attributes @return array
entailment
public static function hydrate(array $items, $connection = null) { $collection = with($instance = new static)->newCollection(); foreach ($items as $item) { $model = $instance->newFromBuilder($item); if (! is_null($connection)) { $model->setConnection($connection); } $collection->push($model); } return $collection; }
Create a collection of models from plain arrays. @param array $items @param string $connection @return \Nova\Database\ORM\Collection
entailment
public static function firstOrCreate(array $attributes) { if (! is_null($instance = static::where($attributes)->first())) { return $instance; } return static::create($attributes); }
Get the first record matching the attributes or create it. @param array $attributes @return static
entailment
public static function find($id, $columns = array('*')) { $instance = new static; if (is_array($id) && empty($id)) return $instance->newCollection(); return $instance->newQuery()->find($id, $columns); }
Find a model by its primary key. @param mixed $id @param array $columns @return \Nova\Support\Collection|static|null
entailment
public static function with($relations) { if (is_string($relations)) $relations = func_get_args(); $instance = new static; return $instance->newQuery()->with($relations); }
Being querying a model with eager loading. @param array|string $relations @return \Nova\Database\ORM\Builder|static
entailment
public function hasOne($related, $foreignKey = null, $localKey = null) { $foreignKey = $foreignKey ?: $this->getForeignKey(); $instance = new $related; $localKey = $localKey ?: $this->getKeyName(); return new HasOne($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey); }
Define a one-to-one relationship. @param string $related @param string $foreignKey @param string $localKey @return \Nova\Database\ORM\Relations\HasOne
entailment
public function hasOneThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null) { $through = new $through; $firstKey = $firstKey ?: $this->getForeignKey(); $secondKey = $secondKey ?: $through->getForeignKey(); $localKey = $localKey ?: $this->getKeyName(); return new HasOneThrough((new $related)->newQuery(), $this, $through, $firstKey, $secondKey, $localKey); }
Define a has-one-through relationship. @param string $related @param string $through @param string|null $firstKey @param string|null $secondKey @param string|null $localKey @return \Nova\Database\ORM\Relations\HasOneThrough
entailment
public function belongsToThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null) { $through = new $through; $firstKey = $firstKey ?: $this->getForeignKey(); $secondKey = $secondKey ?: $through->getForeignKey(); $localKey = $localKey ?: $this->getKeyName(); return new BelongsToThrough((new $related)->newQuery(), $this, $through, $firstKey, $secondKey, $localKey); }
Define a has-one-through relationship. @param string $related @param string $through @param string|null $firstKey @param string|null $secondKey @param string|null $localKey @return \Nova\Database\ORM\Relations\BelongsToThrough
entailment
public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null) { if (is_null($relation)) { $relation = $this->getBelongsToManyCaller(); } $foreignKey = $foreignKey ?: $this->getForeignKey(); $instance = new $related; $otherKey = $otherKey ?: $instance->getForeignKey(); if (is_null($table)) { $table = $this->joiningTable($related); } $query = $instance->newQuery(); return new BelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation); }
Define a many-to-many relationship. @param string $related @param string $table @param string $foreignKey @param string $otherKey @param string $relation @return \Nova\Database\ORM\Relations\BelongsToMany
entailment
public function morphedByMany($related, $name, $table = null, $foreignKey = null, $otherKey = null) { $foreignKey = $foreignKey ?: $this->getForeignKey(); $otherKey = $otherKey ?: $name.'_id'; return $this->morphToMany($related, $name, $table, $foreignKey, $otherKey, true); }
Define a polymorphic, inverse many-to-many relationship. @param string $related @param string $name @param string $table @param string $foreignKey @param string $otherKey @return \Nova\Database\ORM\Relations\MorphToMany
entailment
public function joiningTable($related) { $base = Str::snake(class_basename($this)); $related = Str::snake(class_basename($related)); $models = array($related, $base); // sort($models); return strtolower(implode('_', $models)); }
Get the joining table name for a many-to-many relation. @param string $related @return string
entailment
public function addObservableEvents($observables) { $observables = is_array($observables) ? $observables : func_get_args(); $this->observables = array_unique(array_merge($this->observables, $observables)); }
Add an observable event name. @param mixed $observables @return void
entailment
public function removeObservableEvents($observables) { $observables = is_array($observables) ? $observables : func_get_args(); $this->observables = array_diff($this->observables, $observables); }
Remove an observable event name. @param mixed $observables @return void
entailment
public function update(array $attributes = array()) { if (! $this->exists) { return $this->newQuery()->update($attributes); } return $this->fill($attributes)->save(); }
Update the model in the database. @param array $attributes @return bool|int
entailment
public function push() { if (! $this->save()) return false; foreach ($this->relations as $models) { foreach (Collection::make($models) as $model) { if (! $model->push()) return false; } } return true; }
Save the model and all of its relationships. @return bool
entailment
protected function performUpdate(Builder $query, array $options = []) { $dirty = $this->getDirty(); if (count($dirty) > 0) { if ($this->fireModelEvent('updating') === false) { return false; } if ($this->timestamps && array_get($options, 'timestamps', true)) { $this->updateTimestamps(); } $dirty = $this->getDirty(); if (count($dirty) > 0) { $this->setKeysForSaveQuery($query)->update($dirty); $this->fireModelEvent('updated', false); } } return true; }
Perform a model update operation. @param \Nova\Database\ORM\Builder $query @param array $options @return bool|null
entailment
public function touchOwners() { foreach ($this->touches as $relation) { $this->$relation()->touch(); if (! is_null($this->$relation)) { $this->$relation->touchOwners(); } } }
Touch the owning relations of the model. @return void
entailment
protected function getKeyForSaveQuery() { if (isset($this->original[$this->getKeyName()])) { return $this->original[$this->getKeyName()]; } return $this->getAttribute($this->getKeyName()); }
Get the primary key value for a save query. @return mixed
entailment
protected function updateTimestamps() { $time = $this->freshTimestamp(); if (! is_null($column = $this->getUpdatedAtColumn()) && ! $this->isDirty($column)) { $this->setAttribute($column, $time); } if (! $this->exists && ! is_null($column = $this->getCreatedAtColumn()) && ! $this->isDirty($column)) { $this->setAttribute($column, $time); } }
Update the creation and update timestamps. @return void
entailment
public function setCreatedAt($value) { if (! is_null($column = $this->getCreatedAtColumn())) { $this->setAttribute($column, $value); } }
Set the value of the "created at" attribute. @param mixed $value @return void
entailment
public function setUpdatedAt($value) { if (! is_null($column = $this->getUpdatedAtColumn())) { $this->setAttribute($column, $value); } }
Set the value of the "updated at" attribute. @param mixed $value @return void
entailment
public function newQueryWithoutScope($scope) { $this->getGlobalScope($scope)->remove($builder = $this->newQuery(), $this); return $builder; }
Get a new query instance without a given scope. @param \Nova\Database\ORM\ScopeInterface $scope @return \Nova\Database\ORM\Builder
entailment
public function newQueryWithoutScopes() { $builder = $this->newQueryBuilder( $this->newBaseQueryBuilder() ); return $builder->setModel($this)->with($this->with); }
Get a new query builder that doesn't have any global scopes. @return \Nova\Database\ORM\Builder|static
entailment
public function applyGlobalScopes($builder) { foreach ($this->getGlobalScopes() as $scope) { $scope->apply($builder, $this); } return $builder; }
Apply all of the global scopes to an ORM builder. @param \Nova\Database\ORM\Builder $builder @return \Nova\Database\ORM\Builder
entailment
public function removeGlobalScopes($builder) { foreach ($this->getGlobalScopes() as $scope) { $scope->remove($builder, $this); } return $builder; }
Remove all of the global scopes from an ORM builder. @param \Nova\Database\ORM\Builder $builder @return \Nova\Database\ORM\Builder
entailment
public function newPivot(Model $parent, array $attributes, $table, $exists, $using = null) { $className = $using ?: Pivot::class; return new $className($parent, $attributes, $table, $exists); }
Create a new pivot model instance. @param \Nova\Database\ORM\Model $parent @param array $attributes @param string $table @param bool $exists @param string|null $using @return \Nova\Database\ORM\Relations\Pivot
entailment
public function isFillable($key) { if (static::$unguarded) { return true; } else if (in_array($key, $this->fillable)) { return true; } else if ($this->isGuarded($key)) { return false; } return empty($this->fillable) && ! Str::startsWith($key, '_'); }
Determine if the given attribute may be mass assigned. @param string $key @return bool
entailment
public function attributesToArray() { $attributes = $this->getArrayableAttributes(); foreach ($this->getDates() as $key) { if (! isset($attributes[$key])) { continue; } $attributes[$key] = (string) $this->asDateTime($attributes[$key]); } foreach ($this->getMutatedAttributes() as $key) { if (! array_key_exists($key, $attributes)) { continue; } $attributes[$key] = $this->mutateAttributeForArray($key, $attributes[$key]); } foreach ($this->getArrayableAppends() as $key) { $attributes[$key] = $this->mutateAttributeForArray($key, null); } return $attributes; }
Convert the model's attributes to an array. @return array
entailment
public function getAttribute($key) { // If the key references an attribute, return its plain value from the model. if (array_key_exists($key, $this->attributes) || $this->hasGetMutator($key)) { return $this->getAttributeValue($key); } // If the key already exists in the relationships array... else if (array_key_exists($key, $this->relations)) { return $this->relations[$key]; } // If the "attribute" exists as a method on the model, it is a relationship. $camelKey = Str::camel($key); if (method_exists($this, $camelKey)) { return $this->getRelationshipFromMethod($key, $camelKey); } }
Get an attribute from the model. @param string $key @return mixed
entailment
protected function getAttributeValue($key) { $value = $this->getAttributeFromArray($key); if ($this->hasGetMutator($key)) { return $this->mutateAttribute($key, $value); } else if (in_array($key, $this->getDates()) && ! empty($value)) { return $this->asDateTime($value); } return $value; }
Get a plain attribute (not a relationship). @param string $key @return mixed
entailment
protected function getRelationshipFromMethod($key, $camelKey) { $relation = call_user_func(array($this, $camelKey)); if (! $relation instanceof Relation) { throw new LogicException('Relationship method must return an object of type [Nova\Database\ORM\Relations\Relation]'); } return $this->relations[$key] = $relation->getResults(); }
Get a relationship value from a method. @param string $key @param string $camelKey @return mixed @throws \LogicException
entailment
protected function mutateAttribute($key, $value) { $method = 'get' .Str::studly($key) .'Attribute'; return call_user_func(array($this, $method), $value); }
Get the value of an attribute using its mutator. @param string $key @param mixed $value @return mixed
entailment
public function setAttribute($key, $value) { if ($this->hasSetMutator($key)) { $method = 'set' .Str::studly($key) .'Attribute'; return call_user_func(array($this, $method), $value); } else if (in_array($key, $this->getDates()) && $value) { $value = $this->fromDateTime($value); } $this->attributes[$key] = $value; }
Set a given attribute on the model. @param string $key @param mixed $value @return void
entailment
public function handle() { $config = $this->container['config']; if (file_exists($path = $config->get('app.manifest') .DS .'services.php')) { @unlink($path); } //$this->info('Compiled class file removed successfully!'); }
Execute the console command. @return void
entailment
public function buildResult($result) { $chatMembers = []; foreach ($result as $item) { $chatMembers[] = new ChatMember($item); } return $chatMembers; }
@param array $result @return ChatMember[]
entailment
public function removeTransformation(TransformationInterface $transformation) { $this->transformations = array_filter($this->transformations, function (TransformationInterface $t) use ($transformation) { return $t !== $transformation; }); return $this; }
@param TransformationInterface $transformation @return $this
entailment
public function removeFilter(FilterInterface $filter) { $this->filters = array_filter($this->filters, function (FilterInterface $f) use ($filter) { return $f !== $filter; }); return $this; }
@param FilterInterface $filter @return $this
entailment
public function handle($request, Closure $next) { if ($this->app->isDownForMaintenance()) { throw new HttpException(503); } return $next($request); }
Handle an incoming request. @param \Nova\Http\Request $request @param \Closure $next @return mixed @throws \Symfony\Component\HttpKernel\Exception\HttpException
entailment
public function push($job, $data = '', $queue = null) { return $this->pushRaw($this->createPayload($job, $data, $queue), $queue); }
Push a new job onto the queue. @param string $job @param mixed $data @param string $queue @return mixed
entailment
public function recreate($payload, $queue = null, $delay) { $options = array('delay' => $this->getSeconds($delay)); return $this->pushRaw($payload, $queue, $options); }
Push a raw payload onto the queue after encrypting the payload. @param string $payload @param string $queue @param int $delay @return mixed
entailment
public function later($delay, $job, $data = '', $queue = null) { $delay = $this->getSeconds($delay); $payload = $this->createPayload($job, $data, $queue); return $this->pushRaw($payload, $queue, compact('delay')); }
Push a new job onto the queue after a delay. @param \DateTime|int $delay @param string $job @param mixed $data @param string $queue @return mixed
entailment
protected function createPayload($job, $data = '', $queue = null) { $payload = $this->setMeta(parent::createPayload($job, $data), 'attempts', 1); return $this->setMeta($payload, 'queue', $this->getQueue($queue)); }
Create a payload string from the given job and data. @param string $job @param mixed $data @param string $queue @return string
entailment
public function handle() { $events = $this->schedule->dueEvents($this->container); foreach ($events as $event) { $this->line('<info>Running scheduled command:</info> ' .$event->getSummaryForDisplay()); $event->run($this->container); } if (count($events) === 0) { $this->info('No scheduled commands are ready to run.'); } }
Execute the console command. @return void
entailment
public function handle() { if ($this->container['queue.failer']->forget($this->argument('id'))) { $this->info('Failed job deleted successfully!'); } else { $this->error('No failed job matches the given ID.'); } }
Execute the console command. @return void
entailment
public function put($key, $value, $minutes) { $this->memcached->set($this->prefix.$key, $value, $minutes * 60); }
Store an item in the cache for a given number of minutes. @param string $key @param mixed $value @param int $minutes @return void
entailment
public function start() { // add server type $this->serverSetting['server_type'] = self::TYPE_HTTP; if (!empty($this->setting['open_http2_protocol'])) { $this->httpSetting['type'] = SWOOLE_SOCK_TCP|SWOOLE_SSL; } $this->server = new Server($this->httpSetting['host'], $this->httpSetting['port'], $this->httpSetting['mode'], $this->httpSetting['type']); // Bind event callback $this->server->set($this->setting); $this->server->on(SwooleEvent::ON_START, [$this, 'onStart']); $this->server->on(SwooleEvent::ON_WORKER_START, [$this, 'onWorkerStart']); $this->server->on(SwooleEvent::ON_MANAGER_START, [$this, 'onManagerStart']); $this->server->on(SwooleEvent::ON_REQUEST, [$this, 'onRequest']); $this->server->on(SwooleEvent::ON_PIPE_MESSAGE, [$this, 'onPipeMessage']); $this->server->on(SwooleEvent::ON_WORKER_STOP, [$this, 'onWorkerStop']); $this->server->on(SwooleEvent::ON_MANAGER_STOP, [$this, 'onManagerStop']); $this->server->on(SwooleEvent::ON_SHUTDOWN, [$this, 'onShutdown']); // Start RPC Server if ((int)$this->serverSetting['tcpable'] === 1) { $this->registerRpcEvent(); } $this->registerSwooleServerEvents(); $this->beforeServerStart(); $this->server->start(); }
Start Server @throws \Swoft\Exception\RuntimeException
entailment
protected function registerRpcEvent() { $swooleListeners = SwooleListenerCollector::getCollector(); if (!isset($swooleListeners[SwooleEvent::TYPE_PORT][0]) || empty($swooleListeners[SwooleEvent::TYPE_PORT][0])) { throw new RuntimeException("Please use swoft/rpc-server, run 'composer require swoft/rpc-server'"); } $this->listen = $this->server->listen($this->tcpSetting['host'], $this->tcpSetting['port'], $this->tcpSetting['type']); $tcpSetting = $this->getListenTcpSetting(); $this->listen->set($tcpSetting); $swooleRpcPortEvents = $swooleListeners[SwooleEvent::TYPE_PORT][0]; $this->registerSwooleEvents($this->listen, $swooleRpcPortEvents); }
Register rpc event, swoft/rpc-server required @throws \Swoft\Exception\RuntimeException
entailment
public function onRequest(Request $request, Response $response) { // Initialize Request and Response and set to RequestContent $psr7Request = \Swoft\Http\Message\Server\Request::loadFromSwooleRequest($request); $psr7Response = new \Swoft\Http\Message\Server\Response($response); /** @var \Swoft\Http\Server\ServerDispatcher $dispatcher */ $dispatcher = App::getBean('serverDispatcher'); $dispatcher->dispatch($psr7Request, $psr7Response); }
onRequest event callback Each request will create an coroutine @param Request $request @param Response $response @throws \InvalidArgumentException
entailment
public function getByLabel($label) { return isset($this->items[$label]) ? $this->items[$label] : null; }
Returns user data item by its label. @param string $label @return UserDataItem|null
entailment
private function createDataItems(array $data) { $items = []; foreach ($data as $item) { $items[$item['label']] = new UserDataItem( $item['label'], $item['value'], $item['isValid'], $item['isOwner'] ); } return $items; }
Creates data item object from array. @param array $data @return array
entailment
public function display(Exception $exception, $code) { $content = $this->whoops()->handleException($exception); if( $this->request->wantsJson() ) { return Response::create( $content, $code )->header( 'Content-Type', 'application/json'); } else { return Response::create( $content, $code); } }
Get the Whoops HTML content associated with the given exception. @param \Exception $exception @param int $code @return string
entailment
protected function whoops() { // Default to the Whoops HTML Handler $handler = new WhoopsHtmlHandler(); // For JSON or XML Requests, return the proper output too. if ($this->request instanceof Request && $this->request->wantsJson() ) { $handler = new WhoopsJsonHandler(); $handler->addTraceToOutput(true); } // Build Whoops. $whoops = new Whoops(); $whoops->allowQuit(false); $whoops->writeToOutput(false); $whoops->pushHandler($handler); $whoops->register(); // Return Whoops. return $whoops; }
Get the whoops instance. @return \Whoops\Run
entailment
public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector) { $instanceCount = 0; $values = array_values($parameters); foreach ($reflector->getParameters() as $key => $parameter) { $instance = $this->transformDependency($parameter, $parameters); if (! is_null($instance)) { $instanceCount++; $this->spliceIntoParameters($parameters, $key, $instance); } // If the parameter is not defined and it have a default value. else if (! isset($values[$key - $instanceCount]) && $parameter->isDefaultValueAvailable()) { $this->spliceIntoParameters($parameters, $key, $parameter->getDefaultValue()); } } return $parameters; }
Resolve the given method's type-hinted dependencies. @param array $parameters @param \ReflectionFunctionAbstract $reflector @return array
entailment
protected function transformDependency(ReflectionParameter $parameter, $parameters) { $class = $parameter->getClass(); // If the parameter has a type-hinted class, we will check to see if it is already in // the list of parameters. If it is we will just skip it as it is probably a model // binding and we do not want to mess with those; otherwise, we resolve it here. if (! is_null($class) && ! $this->alreadyInParameters($className = $class->name, $parameters)) { return $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : $this->container->make($className); } }
Attempt to transform the given parameter into a class instance. @param \ReflectionParameter $parameter @param array $parameters @param array $originalParameters @return mixed
entailment
protected function alreadyInParameters($class, array $parameters) { $result = Arr::first($parameters, function ($key, $value) use ($class) { return ($value instanceof $class); }); return ! is_null($result); }
Determine if an object of the given class is in a list of parameters. @param string $class @param array $parameters @return bool
entailment
public function parser( string $className, $objectAnnotation = null, string $propertyName = '', string $methodName = '', $propertyValue = null ) { $collector = ControllerCollector::getCollector(); if (!isset($collector[$className])) { return; } // Collect requestMapping ControllerCollector::collect($className, $objectAnnotation, $propertyName, $methodName, $propertyValue); }
RequestMapping注解解析 @param string $className @param RequestMapping $objectAnnotation @param string $propertyName @param string $methodName @param null|mixed $propertyValue
entailment
public function boot(Application $app) { // Register our filters to use if (isset($app['assetic.filters']) && is_callable($app['assetic.filters'])) { $app['assetic.filters']($app['assetic.filter_manager']); } /** * Writes down all lazy asset manager and asset managers assets */ $app->after(function () use ($app) { // Boot assetic $assetic = $app['assetic']; if (!isset($app['assetic.options']['auto_dump_assets']) || !$app['assetic.options']['auto_dump_assets']) { return; } $helper = $app['assetic.dumper']; if (isset($app['twig'])) { $helper->addTwigAssets(); } $helper->dumpAssets(); }); }
Bootstraps the application. @param \Silex\Application $app The application
entailment
protected function checkSpecificObject(array $acceptedTypes, $value) { if (is_object($value)) { foreach ($acceptedTypes as $type) { $c = get_class($value); if ($c == ltrim($type, '\\') || is_subclass_of($c, $type)) { return $value; } } } return null; }
Will check to see if the value is an object and its class is listed in the accepted types. @param array $acceptedTypes Accepted types. @param mixed $value Value to test. @return null|object
entailment
public function register() { $this->app->bindShared('command.cache.clear', function ($app) { return new Console\ClearCommand($app['cache'], $app['files']); }); $this->app->bindShared('command.cache.forget', function ($app) { return new Console\ForgetCommand($app['cache']); }); $this->app->bindShared('command.cache.table', function ($app) { return new Console\CacheTableCommand($app['files']); }); $this->commands('command.cache.clear', 'command.cache.forget', 'command.cache.table'); }
Register the service provider. @return void
entailment
public function execute(AbstractMethod $method): \Generator { switch ($method->getHttpMethod()) { case $method::HTTP_GET: $response = yield from $this->get('/'.$method->getMethodName(), $method->getParams()); break; case $method::HTTP_POST: if ($method instanceof \JsonSerializable) { $body = json_encode($method); $bodyStream = new MemoryStream(0, $body); yield from $bodyStream->end(); $contentLength = mb_strlen($body); } else { $bodyStream = null; $contentLength = 0; } $headers = [ 'Content-Type' => 'application/json', 'Content-Length' => $contentLength ]; $response = yield from $this->post('/'.$method->getMethodName(), $method->getParams(), $headers, $bodyStream); break; } $body = yield from $this->getResponseBody($response); $body = json_decode($body, true); if ($body['ok'] === false) { $exception = new TelegramBotApiException($body['description'], $body['error_code']); if (isset($body['parameters'])) { $parameters = new Type\ResponseParameters($body['parameters']); $exception->setParameters($parameters); } throw $exception; } return $method->buildResult($body['result']); }
Execute an API method. @param AbstractMethod $method @return \Generator @throws TelegramBotApiException @resolve object
entailment
public function getUpdates($lastUpdateId = null, int $limit = 5, int $timeout = 30) : \Generator { if ($lastUpdateId !== null) { $this->lastUpdateId = $lastUpdateId; } $method = new GetUpdates($this->lastUpdateId + 1, $limit, $timeout); $updates = yield from $this->execute($method); $this->lastUpdateId = $method->getLastUpdateId(); return $updates; }
@param int $lastUpdateId @param int $limit @param int $timeout @return \Generator @resolve Update[]
entailment
protected function get(string $pathName, array $params = [], $headers = []): \Generator { $url = $this->buildUrl($pathName, $params); return $this->httpClient->request('GET', $url, $headers, null, [ 'timeout' => 60 ]); }
@param string $url @param array $params @return \Generator
entailment
protected function post(string $pathName, array $params = [], $headers = [], ReadableStream $body = null): \Generator { $url = $this->buildUrl($pathName, $params); return $this->httpClient->request('POST', $url, $headers, $body, [ 'timeout' => 60 ]); }
@param string $pathName @param array $params @yield Generator
entailment
protected function buildUrl(string $pathName, array $params = []): string { $uri = new BasicUri($this->baseUrl.$this->token.$pathName); foreach ($params as $name => $value) { if (is_bool($value)) { $value = (int)$value; } $uri = $uri->withQueryValue($name, $value); } return (string) $uri; }
Build full URL to a telegram API with given pathName @param string $pathName @return string
entailment
protected function getResponseBody(Response $response): \Generator { $data = ''; $stream = $response->getBody(); while ($stream->isReadable()) { $data .= yield $stream->read(); } return $data; }
@param Response $response @return \Generator @resolve string
entailment
protected function doExecute(Profile $profile, InputInterface $input, OutputInterface $output) { $this->getBackupHelper()->getExecutor()->backup($profile, $input->getOption('clear')); }
{@inheritdoc}
entailment
public function find($key, $default = null) { if ($key instanceof Model) { $key = $key->getKey(); } return array_first($this->items, function($itemKey, $model) use ($key) { return $model->getKey() == $key; }, $default); }
Find a model in the collection by key. @param mixed $key @param mixed $default @return \Nova\Database\ORM\Model
entailment
public function max($key) { return $this->reduce(function($result, $item) use ($key) { return (is_null($result) || $item->{$key} > $result) ? $item->{$key} : $result; }); }
Get the max value of a given key. @param string $key @return mixed
entailment
public function getDictionary($items = null) { $items = is_null($items) ? $this->items : $items; $dictionary = array(); foreach ($items as $value) { $dictionary[$value->getKey()] = $value; } return $dictionary; }
Get a dictionary keyed by primary keys. @param \ArrayAccess|array $items @return array
entailment
protected function registerAssetPublishCommand() { $this->app->bindShared('asset.publisher', function($app) { $publisher = new AssetPublisher($app['files'], $app['path.public']); // $path = $app['path.base'] .DS .'vendor'; $publisher->setPackagePath($path); return $publisher; }); $this->app->bindShared('command.asset.publish', function($app) { $assetPublisher = $app['asset.publisher']; return new AssetPublishCommand($app['assets.dispatcher'], $assetPublisher); }); }
Register the configuration publisher class and command. @return void
entailment
protected function registerConfigPublishCommand() { $this->app->bindShared('config.publisher', function($app) { $path = $app['path'] .DS .'Config'; $publisher = new ConfigPublisher($app['files'], $app['config'], $path); return $publisher; }); $this->app->bindShared('command.config.publish', function($app) { $configPublisher = $app['config.publisher']; return new ConfigPublishCommand($configPublisher); }); }
Register the configuration publisher class and command. @return void
entailment
protected function registerViewPublishCommand() { $this->app->bindShared('view.publisher', function($app) { $viewPath = $app['path'] .DS .'Views'; $vendorPath = $app['path.base'] .DS .'vendor'; // $publisher = new ViewPublisher($app['files'], $viewPath); $publisher->setPackagePath($vendorPath); return $publisher; }); $this->app->bindShared('command.view.publish', function($app) { return new ViewPublishCommand($app['packages'], $app['view.publisher']); }); }
Register the configuration publisher class and command. @return void
entailment
public function bindInstallPaths(array $paths) { $this->instance('path', realpath($paths['app'])); foreach (array_except($paths, array('app')) as $key => $value) { $this->instance("path.{$key}", realpath($value)); } }
Bind the installation paths to the application. @param array $paths @return void
entailment
public function startExceptionHandling() { $this['exception']->register($this->environment()); // $debug = $this['config']['app.debug']; $this['exception']->setDebug($debug); }
Start the exception handling for the request. @return void
entailment
public function detectEnvironment($envs) { $args = isset($_SERVER['argv']) ? $_SERVER['argv'] : null; return $this['env'] = (new EnvironmentDetector())->detect($envs, $args); }
Detect the application's current environment. @param array|string $envs @return string
entailment
public function getRegistered($provider) { $name = is_string($provider) ? $provider : get_class($provider); if (array_key_exists($name, $this->loadedProviders)) { return array_first($this->serviceProviders, function($key, $value) use ($name) { return get_class($value) == $name; }); } }
Get the registered service provider instance if it exists. @param \Nova\Support\ServiceProvider|string $provider @return \Nova\Support\ServiceProvider|null
entailment
public function make($abstract, $parameters = array()) { $abstract = $this->getAlias($abstract); if (isset($this->deferredServices[$abstract])) { $this->loadDeferredProvider($abstract); } return parent::make($abstract, $parameters); }
Resolve the given type from the container. (Overriding Container::make) @param string $abstract @param array $parameters @return mixed
entailment
public function extend($abstract, Closure $closure) { $abstract = $this->getAlias($abstract); if (isset($this->deferredServices[$abstract])) { $this->loadDeferredProvider($abstract); } return parent::extend($abstract, $closure); }
"Extend" an abstract type in the container. (Overriding Container::extend) @param string $abstract @param \Closure $closure @return void @throws \InvalidArgumentException
entailment
public function boot() { if ($this->booted) { return; } array_walk($this->serviceProviders, function($provider) { $this->bootProvider($provider); }); $this->bootApplication(); }
Boot the application's service providers. @return void
entailment
protected function bootApplication() { $this->fireAppCallbacks($this->bootingCallbacks); $this->booted = true; $this->fireAppCallbacks($this->bootedCallbacks); }
Boot the application and fire app callbacks. @return void
entailment
public function run(SymfonyRequest $request = null) { $request = $request ?: $this['request']; // Setup the Router middlewares. $middlewareGroups = $this['config']->get('app.middlewareGroups'); foreach ($middlewareGroups as $key => $middleware) { $this['router']->middlewareGroup($key, $middleware); } $routeMiddleware = $this['config']->get('app.routeMiddleware'); foreach($routeMiddleware as $name => $middleware) { $this['router']->middleware($name, $middleware); } try { $request->enableHttpMethodParameterOverride(); $response = $this->sendRequestThroughRouter($request); } catch (Exception $e) { $response = $this->handleException($request, $e); } catch (Throwable $e) { $response = $this->handleException($request, new FatalThrowableError($e)); } $response->send(); $this->shutdown($request, $response); }
Run the application and send the response. @param \Symfony\Component\HttpFoundation\Request $request @return void
entailment
protected function sendRequestThroughRouter($request) { $this->refreshRequest($request = Request::createFromBase($request)); $this->boot(); // Create a Pipeline instance. $pipeline = new Pipeline( $this, $this->shouldSkipMiddleware() ? array() : $this->middleware ); return $pipeline->handle($request, function ($request) { $this->instance('request', $request); return $this->router->dispatch($request); }); }
Send the given request through the middleware / router. @param \Nova\Http\Request $request @return \Nova\Http\Response
entailment
protected function handleException($request, Exception $e) { $this->reportException($e); return $this->renderException($request, $e); }
Handle the given exception. @param \Nova\Http\Request $request @param \Exception $e @return \Symfony\Component\HttpFoundation\Response
entailment
protected function gatherRouteMiddleware($request) { if (! is_null($route = $request->route())) { return $this->router->gatherRouteMiddleware($route); } return array(); }
Gather the route middleware for the given request. @param \Nova\Http\Request $request @return array
entailment